<?php
/**
 * Payments Management Page
 * SSCI Office Platform
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('payments') . ' - ' . config('app.name');

if (!$auth->isAuthenticated() || !$auth->canAccessPage('payments')) {
    header('Location: ?page=login');
    exit();
}

require_once __DIR__ . '/../../layouts/header.php';

$_GET['page'] = 'payments';
?>

<div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-7xl pb-20 md:pb-8">
    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-3xl font-bold text-gray-800">
            <i class="fas fa-credit-card text-blue-600 mr-3"></i><?php echo trans('payments'); ?>
        </h1>
        <p class="text-gray-600 text-sm mt-1">Manage and track all payment transactions</p>
    </div>

    <!-- Filters Section -->
    <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                <select id="statusFilter" class="w-full border border-gray-300 rounded-lg px-3 py-2" onchange="loadPayments()">
                    <option value="">All Statuses</option>
                    <option value="Pending">Pending</option>
                    <option value="Confirmed">Confirmed</option>
                    <option value="Failed">Failed</option>
                    <option value="Cancelled">Cancelled</option>
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
                <select id="methodFilter" class="w-full border border-gray-300 rounded-lg px-3 py-2" onchange="loadPayments()">
                    <option value="">All Methods</option>
                    <option value="Manual">Manual</option>
                    <option value="Mobile Money">Mobile Money</option>
                    <option value="Bank Transfer">Bank Transfer</option>
                    <option value="Cheque">Cheque</option>
                    <option value="Cash">Cash</option>
                </select>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Date Range</label>
                <input type="date" id="dateFilter" class="w-full border border-gray-300 rounded-lg px-3 py-2" onchange="loadPayments()">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Search</label>
                <input type="text" id="searchFilter" placeholder="Invoice #, Phone..." class="w-full border border-gray-300 rounded-lg px-3 py-2" onchange="loadPayments()">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">&nbsp;</label>
                <button onclick="openRecordPaymentModal()" class="w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm font-medium">
                    <i class="fas fa-plus mr-2"></i>Record Payment
                </button>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-blue-500">
            <p class="text-gray-600 text-sm">Total Payments</p>
            <p class="text-3xl font-bold text-gray-900" id="totalCount">0</p>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-green-500">
            <p class="text-gray-600 text-sm">Total Amount</p>
            <p class="text-3xl font-bold text-green-600" id="totalAmount">0 FCFA</p>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-yellow-500">
            <p class="text-gray-600 text-sm">Pending Amount</p>
            <p class="text-3xl font-bold text-yellow-600" id="pendingAmount">0 FCFA</p>
        </div>

        <div class="bg-white rounded-lg shadow-sm p-4 border-l-4 border-purple-500">
            <p class="text-gray-600 text-sm">Avg Payment</p>
            <p class="text-3xl font-bold text-purple-600" id="avgAmount">0 FCFA</p>
        </div>
    </div>

    <!-- Payments Table -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">
                            <input type="checkbox" id="selectAllCheckbox" onchange="toggleSelectAll(this)" class="w-4 h-4 cursor-pointer">
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Payment ID</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Client</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Invoice</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Amount</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Method</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Date</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody id="paymentsTableBody" class="divide-y divide-gray-200">
                    <tr class="text-center py-8">
                        <td colspan="7" class="px-6 py-8 text-gray-500">
                            <i class="fas fa-spinner fa-spin mr-2"></i>Loading payments...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- Bulk Actions -->
        <div id="bulkActionsBar" class="hidden bg-blue-50 border-t border-gray-200 px-6 py-3 flex justify-between items-center">
            <div class="text-sm text-gray-700">
                <span id="selectedCount">0</span> payment(s) selected
            </div>
            <div class="flex gap-2">
                <select id="bulkStatusSelect" class="border border-gray-300 rounded-lg px-3 py-2 text-sm">
                    <option value="">-- Change Status --</option>
                    <option value="Pending">Pending</option>
                    <option value="Confirmed">Confirmed</option>
                    <option value="Failed">Failed</option>
                    <option value="Cancelled">Cancelled</option>
                </select>
                <button onclick="applyBulkStatusChange()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm">
                    <i class="fas fa-check mr-1"></i>Apply
                </button>
                <button onclick="clearBulkSelection()" class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg hover:bg-gray-400 text-sm">
                    <i class="fas fa-times mr-1"></i>Clear
                </button>
            </div>
        </div>

        <!-- Pagination -->
        <div class="bg-gray-50 border-t border-gray-200 px-6 py-3 flex justify-between items-center">
            <div class="text-sm text-gray-600">
                Showing <span id="showingCount">0</span> payments
            </div>
            <div class="flex gap-2">
                <button onclick="previousPage()" class="px-3 py-1 border border-gray-300 rounded text-sm hover:bg-gray-100" id="prevBtn">
                    <i class="fas fa-chevron-left mr-1"></i>Previous
                </button>
                <button onclick="nextPage()" class="px-3 py-1 border border-gray-300 rounded text-sm hover:bg-gray-100" id="nextBtn">
                    Next<i class="fas fa-chevron-right ml-1"></i>
                </button>
            </div>
        </div>
    </div>
</div>

    <!-- Record Payment Modal -->
    <div id="recordPaymentModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg max-w-2xl w-full">
            <div class="border-b border-gray-200 px-6 py-4 flex justify-between items-center">
                <h3 class="text-lg font-bold text-gray-900">Record Payment</h3>
                <button onclick="closeRecordPaymentModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>

            <div class="p-6">
                <!-- Invoice Summary -->
                <div class="bg-blue-50 p-4 rounded border border-blue-200 mb-6">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <p class="text-sm text-gray-600">Invoice Number:</p>
                            <p id="recordPaymentInvoiceNumber" class="text-lg font-bold text-gray-800">--</p>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">Total Amount:</p>
                            <p id="recordPaymentInvoiceTotal" class="text-lg font-bold text-gray-800">0 FCFA</p>
                        </div>
                    </div>
                </div>

                <!-- Payment Tabs -->
                <div class="flex border-b border-gray-200 mb-4">
                    <button class="record-payment-tab-btn flex-1 px-4 py-2 text-center font-semibold transition-all border-b-2 border-green-600 text-green-600 active" data-payment-tab="manual">
                        <i class="fas fa-hand-holding-usd mr-2"></i>Manual Payment
                    </button>
                    <button class="record-payment-tab-btn flex-1 px-4 py-2 text-center font-semibold transition-all border-b-2 border-transparent text-gray-600 hover:text-gray-900" data-payment-tab="mobile-money">
                        <i class="fas fa-mobile-alt mr-2"></i>Mobile Money
                    </button>
                </div>

                <!-- Manual Payment Tab -->
                <div class="record-payment-tab-content active" id="record-manual-payment-tab">
                    <form id="recordManualPaymentForm">
                        <div class="mb-4">
                            <label class="block text-sm font-semibold text-gray-800 mb-1">Client Invoice *</label>
                            <select id="recordInvoiceSelect" onchange="updateRecordInvoiceDisplay()" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500">
                                <option value="">Select an invoice...</option>
                                <?php 
                                $invoices = $db->fetchAll(
                                    "SELECT i.id, i.invoice_number, i.total_amount, u.name as client_name
                                     FROM invoices i
                                     LEFT JOIN users u ON i.owner_id = u.id
                                     WHERE i.status != 'Paid'
                                     ORDER BY i.invoice_date DESC
                                     LIMIT 100"
                                );
                                foreach ($invoices as $inv): 
                                ?>
                                    <option value="<?php echo $inv['id']; ?>" data-amount="<?php echo $inv['total_amount']; ?>" data-number="<?php echo $inv['invoice_number']; ?>" data-client="<?php echo $inv['client_name']; ?>">
                                        #<?php echo $inv['invoice_number']; ?> - <?php echo number_format($inv['total_amount'], 0, ',', ' '); ?> FCFA (<?php echo $inv['client_name']; ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-semibold text-gray-800 mb-1">Payment Method</label>
                            <select id="recordPaymentMethod" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500" required>
                                <option value="">Select payment method...</option>
                                <option value="Cash">Cash</option>
                                <option value="Bank Transfer">Bank Transfer</option>
                                <option value="Cheque">Cheque</option>
                                <option value="Check">Check</option>
                            </select>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-semibold text-gray-800 mb-1">Amount</label>
                            <input type="number" id="recordPaymentAmount" step="0.01" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500" placeholder="Enter amount" required>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-semibold text-gray-800 mb-1">Description/Reference</label>
                            <input type="text" id="recordPaymentDescription" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500" placeholder="e.g., Check #123 or Transfer Ref">
                        </div>

                        <button type="submit" class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700 transition font-semibold">
                            <i class="fas fa-check mr-2"></i>Record Payment
                        </button>
                    </form>
                </div>

                <!-- Mobile Money Payment Tab -->
                <div class="record-payment-tab-content hidden" id="record-mobile-money-payment-tab">
                    <form id="recordMobileMoneyPaymentForm">
                        <div class="mb-4">
                            <label class="block text-sm font-semibold text-gray-800 mb-1">Client Invoice *</label>
                            <select id="recordMobileInvoiceSelect" onchange="updateRecordMobileInvoiceDisplay()" required class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500">
                                <option value="">Select an invoice...</option>
                                <?php foreach ($invoices as $inv): ?>
                                    <option value="<?php echo $inv['id']; ?>" data-amount="<?php echo $inv['total_amount']; ?>" data-number="<?php echo $inv['invoice_number']; ?>" data-client="<?php echo $inv['client_name']; ?>">
                                        #<?php echo $inv['invoice_number']; ?> - <?php echo number_format($inv['total_amount'], 0, ',', ' '); ?> FCFA (<?php echo $inv['client_name']; ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-semibold text-gray-800 mb-1">Phone Number</label>
                            <input type="tel" id="recordMobilePhoneNumber" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500" placeholder="e.g., 237600000000" required>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-semibold text-gray-800 mb-1">Amount to Pay</label>
                            <input type="number" id="recordMobileAmount" step="0.01" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-green-500" placeholder="Enter amount" required>
                        </div>

                        <div class="mb-4 p-3 bg-amber-50 border border-amber-200 rounded">
                            <p class="text-sm text-gray-700"><strong>Amount with 3% Campay Fee:</strong></p>
                            <p class="text-lg font-bold text-amber-700" id="recordTotalWithFee">-</p>
                        </div>

                        <div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded hidden" id="recordUssdCodeDisplay">
                            <p class="text-sm text-gray-700"><strong>Operator:</strong></p>
                            <p class="text-md font-bold text-blue-700" id="recordOperatorCode">-</p>
                            
                            <p class="text-sm text-gray-700 mt-3"><strong>USSD Code:</strong></p>
                            <p class="text-lg font-bold text-blue-700 font-mono" id="recordUssdCode">-</p>
                            <p class="text-xs text-gray-600 mt-2">*Dial the code to complete payment</p>
                        </div>

                        <button type="submit" id="recordMobileMoneySubmitBtn" class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700 transition font-semibold">
                            <i class="fas fa-check mr-2"></i>Request Mobile Money Payment
                        </button>

                        <button type="button" id="recordCheckStatusBtn" class="w-full mt-2 bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition font-semibold hidden">
                            <i class="fas fa-sync mr-2"></i>Check Payment Status
                        </button>
                    </form>
                </div>
            </div>

            <div class="border-t border-gray-200 px-6 py-4 flex justify-end gap-2">
                <button onclick="closeRecordPaymentModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                    Cancel
                </button>
            </div>
        </div>
    </div>

    <!-- Payment Detail Modal -->
    <div id="detailModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg max-w-2xl w-full max-h-96 overflow-y-auto">
            <div class="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex justify-between items-center">
                <h3 class="text-lg font-bold text-gray-900">Payment Details</h3>
                <button onclick="closeDetailModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>

            <div id="detailContent" class="p-6">
                <!-- Content will be loaded here -->
            </div>

            <div class="border-t border-gray-200 px-6 py-4 flex justify-end gap-2">
                <button id="downloadReceiptBtn" onclick="downloadReceipt()" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 hidden">
                    <i class="fas fa-download mr-2"></i>Download Receipt
                </button>
                <button onclick="closeDetailModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                    Close
                </button>
            </div>
        </div>
    </div>

    <!-- Edit Payment Modal -->
    <div id="editModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg max-w-2xl w-full">
            <div class="sticky top-0 bg-white border-b border-gray-200 px-6 py-4 flex justify-between items-center">
                <h3 class="text-lg font-bold text-gray-900">Edit Payment</h3>
                <button onclick="closeEditModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>

            <div id="editContent" class="p-6 max-h-96 overflow-y-auto">
                <!-- Edit form will be loaded here -->
            </div>

            <div class="border-t border-gray-200 px-6 py-4 flex justify-end gap-2">
                <button onclick="savePaymentEdit()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    <i class="fas fa-save mr-2"></i>Save Changes
                </button>
                <button onclick="closeEditModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                    Cancel
                </button>
            </div>
        </div>
    </div>

    <!-- Export Modal -->
<div id="exportModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-lg max-w-md w-full">
        <div class="border-b border-gray-200 px-6 py-4">
            <h3 class="text-lg font-bold text-gray-900">Export Payments</h3>
        </div>

        <div class="p-6 space-y-3">
            <button onclick="exportCSV()" class="w-full bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
                <i class="fas fa-file-csv mr-2"></i>Export as CSV
            </button>
            <button onclick="exportPDF()" class="w-full bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition">
                <i class="fas fa-file-pdf mr-2"></i>Export as PDF
            </button>
        </div>

        <div class="border-t border-gray-200 px-6 py-4 flex justify-end">
            <button onclick="closeExportModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                Cancel
            </button>
        </div>
    </div>
</div>

<script>
    let currentPage = 0;
    const pageSize = 20;
    let allPayments = [];

    function normalizeCurrency(code) {
        if (code === 'FCF') return 'FCFA';
        return code || 'FCFA';
    }

    function getStatusBadge(status) {
        const badges = {
            'Pending': '<span class="px-3 py-1 bg-yellow-100 text-yellow-800 rounded-full text-sm font-medium"><i class="fas fa-hourglass-half mr-1"></i>Pending</span>',
            'Confirmed': '<span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-sm font-medium"><i class="fas fa-check-circle mr-1"></i>Confirmed</span>',
            'Failed': '<span class="px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm font-medium"><i class="fas fa-times-circle mr-1"></i>Failed</span>',
            'Cancelled': '<span class="px-3 py-1 bg-gray-100 text-gray-800 rounded-full text-sm font-medium"><i class="fas fa-ban mr-1"></i>Cancelled</span>'
        };
        return badges[status] || '<span class="px-3 py-1 bg-gray-100 text-gray-800 rounded-full text-sm font-medium">' + status + '</span>';
    }

    function getMethodIcon(method) {
        const icons = {
            'Mobile Money': '<i class="fas fa-mobile text-blue-600 mr-2"></i>',
            'Bank Transfer': '<i class="fas fa-university text-purple-600 mr-2"></i>',
            'Cheque': '<i class="fas fa-file-invoice text-orange-600 mr-2"></i>',
            'Cash': '<i class="fas fa-coins text-green-600 mr-2"></i>',
            'Manual': '<i class="fas fa-hand-holding-usd text-gray-600 mr-2"></i>'
        };
        return (icons[method] || '<i class="fas fa-money-bill mr-2"></i>') + method;
    }

    function loadPayments() {
        currentPage = 0;
        fetch('?page=api&endpoint=payments/list&limit=1000')
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    allPayments = data.payments || [];
                    filterAndDisplayPayments();
                } else {
                    Swal.fire('Error', 'Failed to load payments', 'error');
                }
            })
            .catch(err => {
                console.error('Error:', err);
                Swal.fire('Error', 'Failed to load payments', 'error');
            });
    }

    function filterAndDisplayPayments() {
        const status = document.getElementById('statusFilter').value;
        const method = document.getElementById('methodFilter').value;
        const date = document.getElementById('dateFilter').value;
        const search = document.getElementById('searchFilter').value.toLowerCase();

        let filtered = allPayments.filter(payment => {
            if (status && payment.status !== status) return false;
            if (method && payment.payment_method !== method) return false;
            if (date && !payment.payment_date.startsWith(date)) return false;
            if (search) {
                const searchStr = (
                    (payment.reference_number || '') +
                    (payment.phone_number || '') +
                    (payment.amount || '') +
                    (payment.invoice_id || '')
                ).toLowerCase();
                if (!searchStr.includes(search)) return false;
            }
            return true;
        });

        displayPayments(filtered);
        updateSummary(filtered);
    }

    function displayPayments(payments) {
        const tbody = document.getElementById('paymentsTableBody');
        const startIdx = currentPage * pageSize;
        const endIdx = startIdx + pageSize;
        const paginated = payments.slice(startIdx, endIdx);

        if (paginated.length === 0) {
            tbody.innerHTML = '<tr class="text-center py-8"><td colspan="7" class="px-6 py-8 text-gray-500">No payments found</td></tr>';
            document.getElementById('showingCount').textContent = '0';
            document.getElementById('prevBtn').disabled = true;
            document.getElementById('nextBtn').disabled = true;
            return;
        }

        tbody.innerHTML = paginated.map(payment => `
            <tr class="hover:bg-gray-50 transition">
                <td class="px-6 py-4 text-sm">
                    <input type="checkbox" class="payment-checkbox w-4 h-4 cursor-pointer" value="${payment.id}" onchange="updateBulkActionsBar()">
                </td>
                <td class="px-6 py-4 text-sm font-mono text-gray-900">${payment.id || '-'}</td>
                <td class="px-6 py-4 text-sm">${payment.post_name} (${payment.owner_name})</td>
                <td class="px-6 py-4 text-sm">
                    <a href="?page=invoices&action=view&id=${payment.invoice_id}" class="text-blue-600 hover:underline">
                        #${payment.invoice_number || payment.invoice_id}
                    </a>
                </td>
                <td class="px-6 py-4 text-sm font-semibold text-gray-900">${parseFloat(payment.amount).toLocaleString('fr-FR')} ${normalizeCurrency(payment.currency)}</td>
                <td class="px-6 py-4 text-sm">${getMethodIcon(payment.payment_method)}</td>
                <td class="px-6 py-4 text-sm">${getStatusBadge(payment.status)}</td>
                <td class="px-6 py-4 text-sm text-gray-600">${new Date(payment.payment_date).toLocaleDateString('fr-FR')}</td>
                <td class="px-6 py-4 text-sm space-x-2">
                    <button onclick="editPayment(${payment.id})" class="text-gray-600 hover:text-gray-800 transition" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button onclick="viewPaymentDetails(${payment.id})" class="text-blue-600 hover:text-blue-800 transition" title="View">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button onclick="deletePayment(${payment.id})" class="text-red-600 hover:text-red-800 transition" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `).join('');

        document.getElementById('showingCount').textContent = Math.min(endIdx, payments.length);

        // Update pagination buttons
        document.getElementById('prevBtn').disabled = currentPage === 0;
        document.getElementById('nextBtn').disabled = endIdx >= payments.length;
    }

    function updateSummary(payments) {
        const total = payments.length;
        const totalAmount = payments.reduce((sum, p) => sum + (parseFloat(p.amount) || 0), 0);
        const pendingAmount = payments
            .filter(p => p.status === 'Pending')
            .reduce((sum, p) => sum + (parseFloat(p.amount) || 0), 0);
        const avgAmount = total > 0 ? totalAmount / total : 0;

        document.getElementById('totalCount').textContent = total;
        document.getElementById('totalAmount').textContent = totalAmount.toLocaleString('fr-FR', { maximumFractionDigits: 2 }) + ' FCFA';
        document.getElementById('pendingAmount').textContent = pendingAmount.toLocaleString('fr-FR', { maximumFractionDigits: 2 }) + ' FCFA';
        document.getElementById('avgAmount').textContent = avgAmount.toLocaleString('fr-FR', { maximumFractionDigits: 2 }) + ' FCFA';
    }

    function viewPaymentDetails(paymentId) {
        const payment = allPayments.find(p => p.id == paymentId);
        if (!payment) return;

        const detailContent = document.getElementById('detailContent');
        detailContent.innerHTML = `
            <div class="space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <p class="text-gray-600 text-sm">Payment ID</p>
                        <p class="text-lg font-semibold text-gray-900">${payment.id}</p>
                    </div>
                    <div>
                        <p class="text-gray-600 text-sm">Reference</p>
                        <p class="text-lg font-semibold text-gray-900 font-mono">${payment.reference_number || '-'}</p>
                    </div>
                    <div>
                        <p class="text-gray-600 text-sm">Invoice</p>
                        <p class="text-lg font-semibold text-blue-600">
                            <a href="?page=invoices&action=view&id=${payment.invoice_id}" class="hover:underline">#${payment.invoice_id}</a>
                        </p>
                    </div>
                    <div>
                        <p class="text-gray-600 text-sm">Amount</p>
                        <p class="text-lg font-semibold text-gray-900">${parseFloat(payment.amount).toLocaleString('fr-FR')} ${normalizeCurrency(payment.currency)}</p>
                    </div>
                </div>

                <hr class="my-4">

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <p class="text-gray-600 text-sm">Status</p>
                        <p class="mt-1">${getStatusBadge(payment.status)}</p>
                    </div>
                    <div>
                        <p class="text-gray-600 text-sm">Payment Method</p>
                        <p class="text-lg font-semibold text-gray-900 mt-1">${getMethodIcon(payment.payment_method)}</p>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <p class="text-gray-600 text-sm">Payment Date</p>
                        <p class="text-lg font-semibold text-gray-900">${new Date(payment.payment_date).toLocaleDateString('fr-FR')}</p>
                    </div>
                    <div>
                        <p class="text-gray-600 text-sm">Recorded Date</p>
                        <p class="text-lg font-semibold text-gray-900">${new Date(payment.created_at).toLocaleString('fr-FR')}</p>
                    </div>
                </div>

                ${payment.phone_number ? `
                    <div>
                        <p class="text-gray-600 text-sm">Phone Number</p>
                        <p class="text-lg font-semibold text-gray-900">${payment.phone_number}</p>
                    </div>
                ` : ''}

                ${payment.operator ? `
                    <div>
                        <p class="text-gray-600 text-sm">Operator</p>
                        <p class="text-lg font-semibold text-gray-900">${(payment.operator || '').toUpperCase()}</p>
                    </div>
                ` : ''}

                ${payment.campay_reference ? `
                    <div>
                        <p class="text-gray-600 text-sm">Campay Reference</p>
                        <p class="text-sm font-mono text-gray-700 break-all">${payment.campay_reference}</p>
                    </div>
                ` : ''}

                ${payment.description ? `
                    <div>
                        <p class="text-gray-600 text-sm">Description</p>
                        <p class="text-gray-900">${payment.description}</p>
                    </div>
                ` : ''}
            </div>
        `;

        // Show Download Receipt button only for Confirmed status
        const downloadBtn = document.getElementById('downloadReceiptBtn');
        if (payment.status === 'Confirmed') {
            downloadBtn.classList.remove('hidden');
            downloadBtn.dataset.paymentId = payment.id;
        } else {
            downloadBtn.classList.add('hidden');
        }

        document.getElementById('detailModal').classList.remove('hidden');
    }

    function closeDetailModal() {
        document.getElementById('detailModal').classList.add('hidden');
    }

    function downloadReceipt() {
        const paymentId = document.getElementById('downloadReceiptBtn').dataset.paymentId;
        if (!paymentId) {
            alert('Payment ID not found');
            return;
        }
        window.location.href = `?page=api&endpoint=payments/receipt&id=${paymentId}`;
    }

    function openExportModal() {
        document.getElementById('exportModal').classList.remove('hidden');
    }

    function closeExportModal() {
        document.getElementById('exportModal').classList.add('hidden');
    }

    function exportCSV() {
        const headers = ['ID', 'Invoice', 'Amount', 'Currency', 'Method', 'Status', 'Date', 'Reference', 'Phone', 'Operator'];
        const rows = allPayments.map(p => [
            p.id,
            p.invoice_id,
            p.amount,
            p.currency,
            p.payment_method,
            p.status,
            p.payment_date,
            p.reference_number,
            p.phone_number || '',
            p.operator || ''
        ]);

        let csv = headers.join(',') + '\n';
        rows.forEach(row => {
            csv += row.map(cell => `"${cell || ''}"`).join(',') + '\n';
        });

        const blob = new Blob([csv], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `payments_${new Date().toISOString().split('T')[0]}.csv`;
        a.click();
        window.URL.revokeObjectURL(url);

        closeExportModal();
        Swal.fire('Success', 'Payments exported as CSV', 'success');
    }

    function exportPDF() {
        Swal.fire('Info', 'PDF export coming soon', 'info');
        closeExportModal();
    }

    function nextPage() {
        if ((currentPage + 1) * pageSize < allPayments.length) {
            currentPage++;
            filterAndDisplayPayments();
            document.querySelector('table').scrollIntoView({ behavior: 'smooth' });
        }
    }

    function previousPage() {
        if (currentPage > 0) {
            currentPage--;
            filterAndDisplayPayments();
            document.querySelector('table').scrollIntoView({ behavior: 'smooth' });
        }
    }

    // Bulk Selection Functions
    let currentEditPaymentId = null;

    function toggleSelectAll(checkbox) {
        const checkboxes = document.querySelectorAll('.payment-checkbox');
        checkboxes.forEach(cb => {
            cb.checked = checkbox.checked;
        });
        updateBulkActionsBar();
    }

    function updateBulkActionsBar() {
        const checkboxes = document.querySelectorAll('.payment-checkbox');
        const selectedCount = Array.from(checkboxes).filter(cb => cb.checked).length;
        const bulkBar = document.getElementById('bulkActionsBar');
        const selectAllCheckbox = document.getElementById('selectAllCheckbox');

        if (selectedCount > 0) {
            bulkBar.classList.remove('hidden');
            document.getElementById('selectedCount').textContent = selectedCount;
        } else {
            bulkBar.classList.add('hidden');
            selectAllCheckbox.checked = false;
        }
    }

    function clearBulkSelection() {
        document.querySelectorAll('.payment-checkbox').forEach(cb => cb.checked = false);
        document.getElementById('selectAllCheckbox').checked = false;
        document.getElementById('bulkStatusSelect').value = '';
        updateBulkActionsBar();
    }

    function getSelectedPaymentIds() {
        const checkboxes = document.querySelectorAll('.payment-checkbox:checked');
        return Array.from(checkboxes).map(cb => parseInt(cb.value));
    }

    function applyBulkStatusChange() {
        const selectedIds = getSelectedPaymentIds();
        const newStatus = document.getElementById('bulkStatusSelect').value;

        if (!newStatus) {
            Swal.fire('Warning', 'Please select a status', 'warning');
            return;
        }

        if (selectedIds.length === 0) {
            Swal.fire('Warning', 'Please select at least one payment', 'warning');
            return;
        }

        Swal.fire({
            title: 'Confirm Bulk Status Change',
            text: `Update status to "${newStatus}" for ${selectedIds.length} payment(s)?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Update',
            cancelButtonText: 'Cancel'
        }).then(result => {
            if (result.isConfirmed) {
                updatePaymentsStatus(selectedIds, newStatus);
            }
        });
    }

    function updatePaymentsStatus(paymentIds, newStatus) {
        const promises = paymentIds.map(paymentId => {
            return fetch('?page=api&endpoint=payments/update-status', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    payment_id: paymentId,
                    status: newStatus
                })
            }).then(r => r.json());
        });

        Promise.all(promises)
            .then(results => {
                if (results.every(r => r.success)) {
                    Swal.fire('Success', `Updated ${paymentIds.length} payment(s) status`, 'success');
                    clearBulkSelection();
                    loadPayments();
                } else {
                    Swal.fire('Error', 'Failed to update some payments', 'error');
                    loadPayments();
                }
            })
            .catch(err => {
                console.error('Error:', err);
                Swal.fire('Error', 'Failed to update payments', 'error');
            });
    }

    // Edit Functions
    function editPayment(paymentId) {
        const payment = allPayments.find(p => p.id == paymentId);
        if (!payment) return;

        currentEditPaymentId = paymentId;
        const editContent = document.getElementById('editContent');

        editContent.innerHTML = `
            <div class="space-y-4">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Payment ID (Read-only)</label>
                        <input type="text" value="${payment.id}" disabled class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100" readonly>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Invoice ID (Read-only)</label>
                        <input type="text" value="${payment.invoice_id}" disabled class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100" readonly>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Amount (Read-only)</label>
                        <input type="text" value="${parseFloat(payment.amount).toLocaleString('fr-FR')} ${normalizeCurrency(payment.currency)}" disabled class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100" readonly>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Payment Method (Read-only)</label>
                        <input type="text" value="${payment.payment_method}" disabled class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100" readonly>
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                    <select id="editStatus" class="w-full border border-gray-300 rounded-lg px-3 py-2">\n                        <option value="Pending" ${payment.status === 'Pending' ? 'selected' : ''}>Pending</option>
                        <option value="Confirmed" ${payment.status === 'Confirmed' ? 'selected' : ''}>Confirmed</option>
                        <option value="Failed" ${payment.status === 'Failed' ? 'selected' : ''}>Failed</option>
                        <option value="Cancelled" ${payment.status === 'Cancelled' ? 'selected' : ''}>Cancelled</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Reference Number</label>
                    <input type="text" id="editReference" value="${payment.reference_number || ''}" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                    <textarea id="editDescription" class="w-full border border-gray-300 rounded-lg px-3 py-2 h-20">${payment.description || ''}</textarea>
                </div>

                ${payment.phone_number ? `
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Phone Number (Read-only)</label>
                        <input type="text" value="${payment.phone_number}" disabled class="w-full border border-gray-300 rounded-lg px-3 py-2 bg-gray-100" readonly>
                    </div>
                ` : ''}

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Payment Date</label>
                    <input type="date" id="editPaymentDate" value="${payment.payment_date.split('T')[0]}" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                </div>
            </div>
        `;

        document.getElementById('editModal').classList.remove('hidden');
    }

    function closeEditModal() {
        document.getElementById('editModal').classList.add('hidden');
        currentEditPaymentId = null;
    }

    function savePaymentEdit() {
        if (!currentEditPaymentId) return;

        const status = document.getElementById('editStatus').value;
        const reference = document.getElementById('editReference').value;
        const description = document.getElementById('editDescription').value;
        const paymentDate = document.getElementById('editPaymentDate').value;

        fetch('?page=api&endpoint=payments/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                payment_id: currentEditPaymentId,
                status: status,
                reference_number: reference,
                description: description,
                payment_date: paymentDate
            })
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                Swal.fire('Success', 'Payment updated successfully', 'success');
                closeEditModal();
                loadPayments();
            } else {
                Swal.fire('Error', data.message || 'Failed to update payment', 'error');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            Swal.fire('Error', 'Failed to update payment', 'error');
        });
    }

    function deletePayment(paymentId) {
        Swal.fire({
            title: 'Delete Payment?',
            text: 'This action cannot be undone. All associated records will remain intact.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#6b7280',
            confirmButtonText: '<i class="fas fa-trash mr-2"></i>Delete',
            cancelButtonText: '<i class="fas fa-times mr-2"></i>Cancel'
        }).then(result => {
            if (result.isConfirmed) {
                fetch('?page=api&endpoint=payments/delete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        payment_id: paymentId
                    })
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire('Deleted!', 'Payment has been deleted.', 'success');
                        loadPayments();
                    } else {
                        Swal.fire('Error', data.message || 'Failed to delete payment', 'error');
                    }
                })
                .catch(err => {
                    console.error('Error:', err);
                    Swal.fire('Error', 'Failed to delete payment', 'error');
                });
            }
        });
    }

    // Load payments on page load
    window.addEventListener('load', loadPayments);

    // Record Payment Modal Functions
    function openRecordPaymentModal() {
        document.getElementById('recordPaymentModal').classList.remove('hidden');
        setupRecordPaymentTabs();
    }

    function closeRecordPaymentModal() {
        document.getElementById('recordPaymentModal').classList.add('hidden');
    }

    function setupRecordPaymentTabs() {
        document.querySelectorAll('.record-payment-tab-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const tabName = this.getAttribute('data-payment-tab');
                
                // Hide all tabs
                document.querySelectorAll('.record-payment-tab-content').forEach(el => {
                    el.classList.add('hidden');
                });
                
                // Show selected tab
                document.getElementById('record-' + tabName + '-payment-tab').classList.remove('hidden');
                
                // Update button styles
                document.querySelectorAll('.record-payment-tab-btn').forEach(b => {
                    b.classList.remove('border-b-2', 'border-green-600', 'text-green-600');
                    b.classList.add('border-b-2', 'border-transparent', 'text-gray-600', 'hover:text-gray-900');
                });
                
                this.classList.remove('border-b-2', 'border-transparent', 'text-gray-600', 'hover:text-gray-900');
                this.classList.add('border-b-2', 'border-green-600', 'text-green-600');
            });
        });
    }

    function updateRecordInvoiceDisplay() {
        const select = document.getElementById('recordInvoiceSelect');
        const option = select.options[select.selectedIndex];
        
        if (option && option.value) {
            document.getElementById('recordPaymentInvoiceNumber').textContent = option.getAttribute('data-number');
            document.getElementById('recordPaymentInvoiceTotal').textContent = Number(option.getAttribute('data-amount')).toLocaleString() + ' FCFA';
        }
    }

    function updateRecordMobileInvoiceDisplay() {
        const select = document.getElementById('recordMobileInvoiceSelect');
        const option = select.options[select.selectedIndex];
        
        if (option && option.value) {
            document.getElementById('recordPaymentInvoiceNumber').textContent = option.getAttribute('data-number');
            document.getElementById('recordPaymentInvoiceTotal').textContent = Number(option.getAttribute('data-amount')).toLocaleString() + ' FCFA';
        }
    }

    function updateRecordMobileMoneyFee() {
        const amount = parseFloat(document.getElementById('recordMobileAmount').value) || 0;
        const fee = amount * 0.03;
        const total = amount + fee;
        
        document.getElementById('recordTotalWithFee').textContent = total.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' FCFA';
    }

    document.getElementById('recordMobileAmount')?.addEventListener('input', updateRecordMobileMoneyFee);

    // Manual payment form submission
    document.getElementById('recordManualPaymentForm')?.addEventListener('submit', function(e) {
        e.preventDefault();
        submitRecordManualPayment();
    });

    // Mobile money payment form submission
    document.getElementById('recordMobileMoneyPaymentForm')?.addEventListener('submit', function(e) {
        e.preventDefault();
        submitRecordMobileMoneyPayment();
    });

    function submitRecordManualPayment() {
        const invoiceId = document.getElementById('recordInvoiceSelect').value;
        const method = document.getElementById('recordPaymentMethod').value;
        const amount = parseFloat(document.getElementById('recordPaymentAmount').value);
        const description = document.getElementById('recordPaymentDescription').value;

        if (!invoiceId || !method || !amount) {
            Swal.fire('error', 'Please fill in all required fields', 'error');
            return;
        }

        const data = {
            invoice_id: invoiceId,
            payment_method: method,
            amount: amount,
            description: description
        };

        fetch('?page=api&endpoint=payments/record-payment', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(result => {
            if (result.success) {
                Swal.fire('Success', 'Payment recorded successfully!', 'success');
                closeRecordPaymentModal();
                loadPayments();
            } else {
                Swal.fire('error', result.error || 'Failed to record payment', 'error');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            Swal.fire('error', 'An error occurred', 'error');
        });
    }

    function submitRecordMobileMoneyPayment() {
        const invoiceId = document.getElementById('recordMobileInvoiceSelect').value;
        const phone = document.getElementById('recordMobilePhoneNumber').value;
        const amount = parseFloat(document.getElementById('recordMobileAmount').value);

        if (!invoiceId || !phone || !amount) {
            Swal.fire('error', 'Please fill in all required fields', 'error');
            return;
        }

        const data = {
            invoice_id: invoiceId,
            phone_number: phone,
            amount: amount,
            payment_method: 'Mobile Money'
        };

        fetch('?page=api&endpoint=payments/request-mobile-money', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(result => {
            if (result.success) {
                Swal.fire('Success', 'Mobile money request submitted!', 'success');
                // Show USSD code if provided
                if (result.ussd_code) {
                    document.getElementById('recordUssdCode').textContent = result.ussd_code;
                    document.getElementById('recordOperatorCode').textContent = result.operator || 'Orange/MTN/Camtel';
                    document.getElementById('recordUssdCodeDisplay').classList.remove('hidden');
                    
                    // Show check status button
                    document.getElementById('recordCheckStatusBtn').classList.remove('hidden');
                }
                // Reload after a delay
                setTimeout(() => {
                    closeRecordPaymentModal();
                    loadPayments();
                }, 2000);
            } else {
                Swal.fire('error', result.error || 'Failed to request payment', 'error');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            Swal.fire('error', 'An error occurred', 'error');
        });
    }

</script>

<?php
require_once __DIR__ . '/../../layouts/footer.php';
?>

