<?php
require_once 'auth.php';

// Require admin login
requireAdminLogin();

$page_title = 'Payments';
$current_page = 'payments.php';

ob_start();
?>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-success text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-rupee-sign fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-success" id="total-revenue">₹0</h3>
                    <p class="text-muted mb-0">Total Revenue</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-calendar-day fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-primary" id="today-revenue">₹0</h3>
                    <p class="text-muted mb-0">Today's Revenue</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-warning text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-clock fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-warning" id="pending-payments">0</h3>
                    <p class="text-muted mb-0">Pending Payments</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-info text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-check-circle fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-info" id="successful-payments">0</h3>
                    <p class="text-muted mb-0">Successful Payments</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="row mb-4">
    <div class="col-12">
        <div class="content-card">
            <h4 class="mb-3">
                <i class="fas fa-filter me-2 text-primary"></i>
                Payment Filters
            </h4>
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label for="dateFrom" class="form-label">From Date</label>
                    <input type="date" class="form-control" id="dateFrom" name="dateFrom">
                </div>
                <div class="col-md-3 mb-3">
                    <label for="dateTo" class="form-label">To Date</label>
                    <input type="date" class="form-control" id="dateTo" name="dateTo">
                </div>
                <div class="col-md-3 mb-3">
                    <label for="statusFilter" class="form-label">Payment Status</label>
                    <select class="form-select" id="statusFilter" name="statusFilter">
                        <option value="">All Status</option>
                        <option value="SUCCESS">Success</option>
                        <option value="PENDING">Pending</option>
                        <option value="FAILED">Failed</option>
                        <option value="CANCELLED">Cancelled</option>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label for="paymentMethod" class="form-label">Payment Method</label>
                    <select class="form-select" id="paymentMethod" name="paymentMethod">
                        <option value="">All Methods</option>
                        <option value="PHONEPE">PhonePe</option>
                        <option value="UPI">UPI</option>
                        <option value="CARD">Card</option>
                        <option value="NETBANKING">Net Banking</option>
                    </select>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="amountMin" class="form-label">Minimum Amount</label>
                    <input type="number" class="form-control" id="amountMin" name="amountMin" placeholder="Enter minimum amount">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="amountMax" class="form-label">Maximum Amount</label>
                    <input type="number" class="form-control" id="amountMax" name="amountMax" placeholder="Enter maximum amount">
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <button type="button" class="btn btn-primary me-2" onclick="applyFilters()">
                        <i class="fas fa-search me-1"></i>Apply Filters
                    </button>
                    <button type="button" class="btn btn-outline-secondary me-2" onclick="clearFilters()">
                        <i class="fas fa-times me-1"></i>Clear Filters
                    </button>
                    <button type="button" class="btn btn-success" onclick="exportPayments()">
                        <i class="fas fa-download me-1"></i>Export Data
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Payments Table -->
<div class="row">
    <div class="col-12">
        <div class="content-card">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h4 class="mb-0">
                    <i class="fas fa-credit-card me-2 text-primary"></i>
                    Payment Records
                </h4>
                <div class="d-flex align-items-center gap-2">
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="refreshPayments()">
                        <i class="fas fa-sync-alt me-1"></i>Refresh
                    </button>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="autoRefresh" onchange="toggleAutoRefresh()">
                        <label class="form-check-label" for="autoRefresh">
                            Auto Refresh
                        </label>
                    </div>
                </div>
            </div>
            
            <div id="payments-container">
                <div class="text-center py-5">
                    <i class="fas fa-spinner fa-spin fa-2x text-muted mb-3"></i>
                    <p class="text-muted">Loading payment data...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Payment Details Modal -->
<div class="modal fade" id="paymentDetailsModal" tabindex="-1" aria-labelledby="paymentDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="paymentDetailsModalLabel">Payment Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="paymentDetailsContent">
                <!-- Payment details will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
let autoRefreshInterval;
let currentFilters = {};

document.addEventListener('DOMContentLoaded', function() {
    // Set default date range (last 30 days)
    const today = new Date();
    const thirtyDaysAgo = new Date(today.getTime() - (30 * 24 * 60 * 60 * 1000));
    
    document.getElementById('dateFrom').value = thirtyDaysAgo.toISOString().split('T')[0];
    document.getElementById('dateTo').value = today.toISOString().split('T')[0];
    
    loadPaymentsData();
    startAutoRefresh();
});

function loadPaymentsData() {
    console.log('Loading payments data...');
    
    // Get current filters
    const filters = {
        dateFrom: document.getElementById('dateFrom').value,
        dateTo: document.getElementById('dateTo').value,
        status: document.getElementById('statusFilter').value,
        paymentMethod: document.getElementById('paymentMethod').value,
        amountMin: document.getElementById('amountMin').value,
        amountMax: document.getElementById('amountMax').value
    };
    
    currentFilters = filters;
    
    // Show loading state
    const container = document.getElementById('payments-container');
    container.innerHTML = `
        <div class="text-center py-5">
            <i class="fas fa-spinner fa-spin fa-2x text-muted mb-3"></i>
            <p class="text-muted">Loading payment data...</p>
        </div>
    `;
    
    fetch('../api/get_payments_data.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(filters)
    })
    .then(response => {
        console.log('Response status:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.text();
    })
    .then(text => {
        console.log('Raw response:', text);
        try {
            const data = JSON.parse(text);
            console.log('Parsed data:', data);
            if (data.success) {
                updatePaymentStats(data.stats);
                updatePaymentsTable(data.payments);
            } else {
                console.error('Error loading payments data:', data.message);
                showError('Failed to load payments data: ' + data.message);
            }
        } catch (e) {
            console.error('JSON parse error:', e);
            console.error('Response text:', text);
            showError('Invalid response from server');
        }
    })
    .catch(error => {
        console.error('Fetch error:', error);
        showError('Network error while loading data: ' + error.message);
    });
}

function updatePaymentStats(stats) {
    document.getElementById('total-revenue').textContent = '₹' + stats.total_revenue.toLocaleString();
    document.getElementById('today-revenue').textContent = '₹' + stats.today_revenue.toLocaleString();
    document.getElementById('pending-payments').textContent = stats.pending_payments.toLocaleString();
    document.getElementById('successful-payments').textContent = stats.successful_payments.toLocaleString();
}

function updatePaymentsTable(payments) {
    const container = document.getElementById('payments-container');
    
    if (payments.length === 0) {
        container.innerHTML = `
            <div class="text-center py-5">
                <i class="fas fa-credit-card fa-3x text-muted mb-3"></i>
                <p class="text-muted">No payment records found</p>
            </div>
        `;
        return;
    }
    
    let tableHTML = `
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Transaction ID</th>
                        <th>User</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Method</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    payments.forEach(payment => {
        const statusClass = getStatusClass(payment.status);
        const statusIcon = getStatusIcon(payment.status);
        
        tableHTML += `
            <tr>
                <td>
                    <code class="text-primary">${escapeHtml(payment.transaction_id)}</code>
                </td>
                <td>
                    <div class="d-flex align-items-center">
                        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 35px; height: 35px;">
                            ${payment.user_name ? payment.user_name.charAt(0).toUpperCase() : 'U'}
                        </div>
                        <div>
                            <div class="fw-bold">${escapeHtml(payment.user_name || 'Unknown User')}</div>
                            <small class="text-muted">${escapeHtml(payment.user_mobile || 'N/A')}</small>
                        </div>
                    </div>
                </td>
                <td>
                    <span class="fw-bold text-success">₹${parseInt(payment.amount).toLocaleString()}</span>
                </td>
                <td>
                    <span class="badge bg-${statusClass}">
                        <i class="${statusIcon} me-1"></i>
                        ${payment.status}
                    </span>
                </td>
                <td>
                    <span class="badge bg-info">
                        ${escapeHtml(payment.payment_method)}
                    </span>
                </td>
                <td>
                    <div>
                        <div class="fw-bold">${formatDate(payment.created_at)}</div>
                        <small class="text-muted">${formatTime(payment.created_at)}</small>
                    </div>
                </td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="viewPaymentDetails('${payment.id}')">
                        <i class="fas fa-eye"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    tableHTML += `
                </tbody>
            </table>
        </div>
    `;
    
    container.innerHTML = tableHTML;
}

function getStatusClass(status) {
    switch(status) {
        case 'SUCCESS': return 'success';
        case 'PENDING': return 'warning';
        case 'FAILED': return 'danger';
        case 'CANCELLED': return 'secondary';
        default: return 'secondary';
    }
}

function getStatusIcon(status) {
    switch(status) {
        case 'SUCCESS': return 'fas fa-check-circle';
        case 'PENDING': return 'fas fa-clock';
        case 'FAILED': return 'fas fa-times-circle';
        case 'CANCELLED': return 'fas fa-ban';
        default: return 'fas fa-question-circle';
    }
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-IN');
}

function formatTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit' });
}

function applyFilters() {
    loadPaymentsData();
}

function clearFilters() {
    document.getElementById('dateFrom').value = '';
    document.getElementById('dateTo').value = '';
    document.getElementById('statusFilter').value = '';
    document.getElementById('paymentMethod').value = '';
    document.getElementById('amountMin').value = '';
    document.getElementById('amountMax').value = '';
    loadPaymentsData();
}

function refreshPayments() {
    loadPaymentsData();
}

function toggleAutoRefresh() {
    const autoRefresh = document.getElementById('autoRefresh');
    if (autoRefresh.checked) {
        startAutoRefresh();
    } else {
        stopAutoRefresh();
        console.log('Auto-refresh stopped');
    }
}

function startAutoRefresh() {
    stopAutoRefresh(); // Clear any existing interval
    autoRefreshInterval = setInterval(() => {
        console.log('Auto-refreshing payments data...');
        loadPaymentsData();
    }, 30000); // Refresh every 30 seconds
    console.log('Auto-refresh started (30 seconds interval)');
}

function stopAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
    }
}

function viewPaymentDetails(paymentId) {
    fetch('../api/get_payment_details.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ payment_id: paymentId })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showPaymentDetailsModal(data.payment);
        } else {
            alert('Error loading payment details: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Network error while loading payment details');
    });
}

function showPaymentDetailsModal(payment) {
    const modalContent = document.getElementById('paymentDetailsContent');
    modalContent.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <h6 class="text-muted">Transaction Details</h6>
                <table class="table table-sm">
                    <tr>
                        <td><strong>Transaction ID:</strong></td>
                        <td><code>${escapeHtml(payment.transaction_id)}</code></td>
                    </tr>
                    <tr>
                        <td><strong>Amount:</strong></td>
                        <td><span class="text-success fw-bold">₹${parseInt(payment.amount).toLocaleString()}</span></td>
                    </tr>
                    <tr>
                        <td><strong>Status:</strong></td>
                        <td><span class="badge bg-${getStatusClass(payment.status)}">${payment.status}</span></td>
                    </tr>
                    <tr>
                        <td><strong>Payment Method:</strong></td>
                        <td><span class="badge bg-info">${escapeHtml(payment.payment_method)}</span></td>
                    </tr>
                    <tr>
                        <td><strong>Created:</strong></td>
                        <td>${formatDate(payment.created_at)} ${formatTime(payment.created_at)}</td>
                    </tr>
                </table>
            </div>
            <div class="col-md-6">
                <h6 class="text-muted">User Details</h6>
                <table class="table table-sm">
                    <tr>
                        <td><strong>Name:</strong></td>
                        <td>${escapeHtml(payment.user_name || 'N/A')}</td>
                    </tr>
                    <tr>
                        <td><strong>Mobile:</strong></td>
                        <td>${escapeHtml(payment.user_mobile || 'N/A')}</td>
                    </tr>
                    <tr>
                        <td><strong>Appointment ID:</strong></td>
                        <td>${payment.appointment_id || 'N/A'}</td>
                    </tr>
                </table>
            </div>
        </div>
        ${payment.phonepe_response ? `
        <div class="mt-3">
            <h6 class="text-muted">Payment Gateway Response</h6>
            <pre class="bg-light p-3 rounded"><code>${escapeHtml(payment.phonepe_response)}</code></pre>
        </div>
        ` : ''}
    `;
    
    const modal = new bootstrap.Modal(document.getElementById('paymentDetailsModal'));
    modal.show();
}

function exportPayments() {
    const filters = currentFilters;
    const queryParams = new URLSearchParams(filters);
    window.open(`../api/export_payments.php?${queryParams.toString()}`, '_blank');
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showError(message) {
    const container = document.getElementById('payments-container');
    container.innerHTML = `
        <div class="text-center py-5">
            <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
            <p class="text-danger">${message}</p>
        </div>
    `;
}

// Clean up on page unload
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>
