<?php
/**
 * Client - Payments (Create/Manage)
 * Record and manage payments to invoices
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];

// Get current user
$user = $db->fetch("SELECT id, name FROM users WHERE id = ? AND role = 'client'", [$_SESSION['user_id'] ?? 0]);
if (!$user) {
    header('Location: ?page=login');
    exit();
}

// Get outstanding invoices for user
$invoices = $db->fetchAll(
    "SELECT i.id, i.invoice_number, i.total_amount, i.status, i.invoice_date
     FROM invoices i
     WHERE i.owner_id = ?
     ORDER BY i.invoice_date DESC",
    [$_SESSION['user_id']]
);

// Get payment history
$payments = $db->fetchAll(
    "SELECT p.id, p.amount, p.payment_method, p.status, p.payment_date, p.reference_number,
            p.description, i.invoice_number, i.id as invoice_id
     FROM payments p
     LEFT JOIN invoices i ON p.related_id = i.id
     WHERE p.payment_type = 'Client_Income' AND i.owner_id = ?
     ORDER BY p.payment_date DESC
     LIMIT 50",
    [$_SESSION['user_id']]
);

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

<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-green-600 mr-3"></i>Payments
        </h1>
        <p class="text-gray-600 text-sm mt-1">Record payments and view your payment history</p>
    </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">Outstanding</p>
            <p class="text-3xl font-bold text-gray-900" id="outstandingTotal">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">Total Payments</p>
            <p class="text-3xl font-bold text-yellow-600" id="totalPayments">0 FCFA</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">Pending Payments</p>
            <p class="text-3xl font-bold text-green-600" id="pendingPayments">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">Confirmed Payments</p>
            <p class="text-3xl font-bold text-purple-600" id="confirmedPayments">0 FCFA</p>
        </div>
    </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-4 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 text-sm" onchange="loadPayments()">
                    <option value="">All Statuses</option>
                    <option value="Pending">Pending</option>
                    <option value="Confirmed">Confirmed</option>
                    <option value="Failed">Failed</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 text-sm" onchange="loadPayments()">
                    <option value="">All Methods</option>
                    <option value="Bank Transfer">Bank Transfer</option>
                    <option value="Mobile Money">Mobile Money</option>
                    <option value="Check">Check</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 text-sm" onchange="loadPayments()">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">&nbsp;</label>
                <button onclick="openRecordModal()" 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>

    <!-- 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">Payment ID</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>

        <!-- 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="recordModal" 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="closeRecordModal()" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>

        <div class="p-6">
            <!-- Payment Processing - Countdown Section (Hidden by default) -->
            <div id="paymentCountdownSection" class="hidden mb-6 text-center">
                <div class="bg-gradient-to-r from-blue-50 to-blue-100 p-8 rounded-lg border border-blue-300">
                    <p class="text-gray-700 font-semibold mb-4">Processing your payment...</p>
                    
                    <!-- Countdown Timer with Animation -->
                    <div class="inline-block">
                        <div id="countdownCircle" class="w-32 h-32 rounded-full bg-white border-4 border-blue-500 flex items-center justify-center relative shadow-lg animate-pulse">
                            <span class="text-5xl font-bold text-blue-600" id="countdownTimer">30</span>
                            <p class="absolute bottom-2 text-xs text-gray-600">seconds</p>
                        </div>
                    </div>
                    
                    <p class="text-sm text-gray-600 mt-4">Checking payment status...</p>
                </div>
            </div>

            <!-- Payment Result Message Section (Hidden by default) -->
            <div id="paymentResultSection" class="hidden mb-6">
                <div id="resultMessageBox" class="p-6 rounded-lg border-2 text-center">
                    <i id="resultIcon" class="text-6xl mb-3 block"></i>
                    <h3 id="resultTitle" class="text-2xl font-bold mb-2"></h3>
                    <p id="resultMessage" class="text-gray-700 mb-4"></p>
                    <button id="repeatCheckBtn" type="button" class="hidden mt-4 bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition font-semibold">
                        <i class="fas fa-sync mr-2"></i>Check Status Again
                    </button>
                </div>
                
                <!-- Auto-close countdown for success/failure -->
                <div id="autoCloseNotice" class="hidden mt-3 p-3 bg-gray-100 rounded text-center text-sm text-gray-600">
                    Modal will close in <span id="closeCountdown">10</span> seconds...
                </div>
            </div>

            <!-- Invoice Summary -->
            <div id="invoiceSummarySection" 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="paymentInvoiceNumber" class="text-lg font-bold text-gray-800">--</p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Total Amount:</p>
                        <p id="paymentInvoiceTotal" 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="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="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="payment-tab-content active" id="manual-payment-tab">
                <form id="manualPaymentForm">
                    <div class="mb-4">
                        <label class="block text-sm font-semibold text-gray-800 mb-1">Invoice *</label>
                        <select id="invoiceSelect" onchange="updateInvoiceDisplay()" 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']; ?>">
                                    #<?php echo $inv['invoice_number']; ?> - <?php echo number_format($inv['total_amount'], 0, ',', ' '); ?> FCFA
                                </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="manualPaymentMethod" 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="manualPaymentAmount" 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="manualPaymentDescription" 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="payment-tab-content hidden" id="mobile-money-payment-tab">
                <form id="mobileMoneyPaymentForm">
                    <div class="mb-4">
                        <label class="block text-sm font-semibold text-gray-800 mb-1">Invoice *</label>
                        <select id="mobileInvoiceSelect" onchange="updateMobileInvoiceDisplay()" 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']; ?>">
                                    #<?php echo $inv['invoice_number']; ?> - <?php echo number_format($inv['total_amount'], 0, ',', ' '); ?> FCFA
                                </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="mobileMoneyPhone" 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="mobileMoneyAmount" 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="totalWithFee">-</p>
                    </div>

                    <div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded hidden" id="ussdCodeDisplay">
                        <p class="text-sm text-gray-700"><strong>Operator:</strong></p>
                        <p class="text-md font-bold text-blue-700" id="operatorCode">-</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="ussdCode">-</p>
                        <p class="text-xs text-gray-600 mt-2">*Dial the code above to complete payment</p>
                    </div>

                    <button type="submit" id="mobileMoneySubmitBtn" 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="checkStatusBtn" 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="closeRecordModal()" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                Cancel
            </button>
        </div>
    </div>
</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 loaded via JS -->
        </div>

        <div class="border-t border-gray-200 px-6 py-4 flex justify-end gap-2">
            <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>

<script>
let currentPage = 1;
const itemsPerPage = 20;
let allPayments = [];

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    loadPayments();
    calculateSummary();
});

// Also run immediately in case page is already loaded
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        loadPayments();
        calculateSummary();
    });
} else {
    loadPayments();
    calculateSummary();
}

// Load payments from API or use PHP data
function loadPayments() {
    const statusFilter = document.getElementById('statusFilter').value;
    const methodFilter = document.getElementById('methodFilter').value;
    const dateFilter = document.getElementById('dateFilter').value;

    // Fetch from API or use existing payments data
    fetch('?page=api&endpoint=clients/payments-list', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            status: statusFilter,
            method: methodFilter,
            date: dateFilter
        })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            allPayments = data.payments || [];
            displayPayments();
        }
    })
    .catch(err => console.error('Error loading payments:', err));
}

function displayPayments() {
    const start = (currentPage - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    const paymentsToShow = allPayments.slice(start, end);

    const tbody = document.getElementById('paymentsTableBody');
    tbody.innerHTML = '';

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

    paymentsToShow.forEach(payment => {
        const statusColor = {
            'Pending': 'text-yellow-600 bg-yellow-50',
            'Confirmed': 'text-green-600 bg-green-50',
            'Failed': 'text-red-600 bg-red-50'
        };

        let actions = `<button onclick="viewPaymentDetail(${payment.id})" class="text-blue-600 hover:text-blue-700 font-medium"><i class="fas fa-eye mr-1"></i>View</button>`;
        
        if (payment.status === 'Confirmed') {
            actions += ` <button onclick="downloadReceipt(${payment.id})" class="text-green-600 hover:text-green-700 font-medium ml-2">
                <i class="fas fa-receipt mr-1"></i>Receipt
            </button>`;
        } else if (payment.status === 'Pending' && payment.payment_method === 'Mobile Money') {
            actions += ` <button onclick="refreshPaymentStatus(${payment.id})" class="text-orange-600 hover:text-orange-700 font-medium ml-2 animate-pulse">
                <i class="fas fa-sync mr-1"></i>Check Status
            </button>`;
        }

        const row = `<tr class="hover:bg-gray-50">
            <td class="px-6 py-4 text-sm text-gray-600">#${payment.id}</td>
            <td class="px-6 py-4 text-sm font-medium text-gray-900">${payment.invoice_number}</td>
            <td class="px-6 py-4 text-sm font-semibold text-gray-900">${Number(payment.amount).toLocaleString()} FCFA</td>
            <td class="px-6 py-4 text-sm text-gray-600">${payment.payment_method}</td>
            <td class="px-6 py-4 text-sm">
                <span class="px-3 py-1 rounded-full text-xs font-semibold ${statusColor[payment.status] || 'text-gray-600 bg-gray-50'}">
                    ${payment.status}
                </span>
            </td>
            <td class="px-6 py-4 text-sm text-gray-600">${new Date(payment.payment_date).toLocaleDateString()}</td>
            <td class="px-6 py-4 text-sm flex">
                ${actions}
            </td>
        </tr>`;
        tbody.innerHTML += row;
    });

    document.getElementById('showingCount').textContent = paymentsToShow.length;
    document.getElementById('prevBtn').disabled = currentPage === 1;
    document.getElementById('nextBtn').disabled = end >= allPayments.length;
}

// close detals modal
function closeDetailModal() {
    document.getElementById('detailModal').classList.add('hidden');
}


function nextPage() {
    if ((currentPage * itemsPerPage) < allPayments.length) {
        currentPage++;
        displayPayments();
        window.scrollTo(0, 0);
    }
}

function previousPage() {
    if (currentPage > 1) {
        currentPage--;
        displayPayments();
        window.scrollTo(0, 0);
    }
}

function openRecordModal() {
    document.getElementById('recordModal').classList.remove('hidden');
    // Set up tab switching
    setupPaymentTabs();
}

function closeRecordModal() {
    document.getElementById('recordModal').classList.add('hidden');
}

function setupPaymentTabs() {
    document.querySelectorAll('.payment-tab-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const tabName = this.getAttribute('data-payment-tab');
            
            // Hide all tabs
            document.querySelectorAll('.payment-tab-content').forEach(el => {
                el.classList.add('hidden');
            });
            
            // Show selected tab
            document.getElementById(tabName + '-payment-tab').classList.remove('hidden');
            
            // Update button styles
            document.querySelectorAll('.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 updateInvoiceDisplay() {
    const select = document.getElementById('invoiceSelect');
    const option = select.options[select.selectedIndex];
    
    if (option && option.value) {
        document.getElementById('paymentInvoiceNumber').textContent = option.getAttribute('data-number');
        document.getElementById('paymentInvoiceTotal').textContent = Number(option.getAttribute('data-amount')).toLocaleString() + ' FCFA';
    }
}

function updateMobileInvoiceDisplay() {
    const select = document.getElementById('mobileInvoiceSelect');
    const option = select.options[select.selectedIndex];
    
    if (option && option.value) {
        document.getElementById('paymentInvoiceNumber').textContent = option.getAttribute('data-number');
        document.getElementById('paymentInvoiceTotal').textContent = Number(option.getAttribute('data-amount')).toLocaleString() + ' FCFA';
    }
}

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

document.getElementById('mobileMoneyAmount')?.addEventListener('input', updateMobileMoneyFee);

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

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

function submitManualPayment() {
    const invoiceId = document.getElementById('invoiceSelect').value;
    const method = document.getElementById('manualPaymentMethod').value;
    const amount = parseFloat(document.getElementById('manualPaymentAmount').value);
    const description = document.getElementById('manualPaymentDescription').value;

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

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

    // Disable submit button during processing
    const submitBtn = document.querySelector('#manualPaymentForm button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';

    fetch('?page=api&endpoint=clients/record-payment', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(res => res.json())
    .then(result => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Record Payment';
        
        if (result.success) {
            // Manual payments are recorded directly - no need for countdown or status checking
            showToast('success', 'Payment recorded successfully!');
            loadPayments(); // Reload payment list
            closeRecordModal(); // Close modal
        } else {
            showToast('error', result.error || 'Failed to record payment');
        }
    })
    .catch(err => {
        console.error('Error:', err);
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Record Payment';
        showToast('error', 'An error occurred');
    });
}

function submitMobileMoneyPayment() {
    const invoiceId = document.getElementById('mobileInvoiceSelect').value;
    const phone = document.getElementById('mobileMoneyPhone').value;
    const amount = parseFloat(document.getElementById('mobileMoneyAmount').value);

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

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

    // Disable submit button during processing
    const submitBtn = document.querySelector('#mobileMoneyPaymentForm button[type="submit"]');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Processing...';

    fetch('?page=api&endpoint=clients/request-mobile-money', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    })
    .then(res => res.json())
    .then(result => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Request Mobile Money Payment';
        
        if (result.success) {
            // Store payment ID for status checking
            window.currentPaymentId = result.payment_id;
            
            // Show USSD code
            if (result.ussd_code) {
                document.getElementById('ussdCode').textContent = result.ussd_code;
                document.getElementById('operatorCode').textContent = result.operator || 'Orange/MTN/Camtel';
                document.getElementById('ussdCodeDisplay').classList.remove('hidden');
            }
            
            // Hide form sections and show countdown
            document.getElementById('invoiceSummarySection').classList.add('hidden');
            document.querySelectorAll('.payment-tab-content').forEach(el => el.classList.add('hidden'));
            document.querySelectorAll('.payment-tab-btn').forEach(el => el.disabled = true);
            document.getElementById('paymentCountdownSection').classList.remove('hidden');
            
            // Start 30 second countdown
            startPaymentCountdown(30, () => {
                // After countdown, check status
                checkPaymentStatus();
            });
        } else {
            showToast('error', result.error || 'Failed to request payment');
        }
    })
    .catch(err => {
        console.error('Error:', err);
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Request Mobile Money Payment';
        showToast('error', 'An error occurred');
    });
}

/**
 * Start countdown timer with animation
 * @param {number} seconds - Number of seconds to countdown from
 * @param {function} onComplete - Callback when countdown finishes
 */
function startPaymentCountdown(seconds, onComplete) {
    let remaining = seconds;
    const countdownTimer = document.getElementById('countdownTimer');
    const countdownCircle = document.getElementById('countdownCircle');
    
    // Remove pulse animation and start countdown
    countdownCircle.classList.remove('animate-pulse');
    countdownCircle.style.animation = 'none';
    
    const interval = setInterval(() => {
        countdownTimer.textContent = remaining;
        
        // Change color as time runs out
        if (remaining <= 10) {
            countdownCircle.classList.add('border-amber-500');
            countdownCircle.classList.remove('border-blue-500');
        }
        if (remaining <= 5) {
            countdownCircle.classList.add('border-red-500');
            countdownCircle.classList.remove('border-amber-500');
        }
        
        remaining--;
        
        if (remaining < 0) {
            clearInterval(interval);
            if (onComplete) {
                onComplete();
            }
        }
    }, 1000);
}

/**
 * Check payment status and display result
 */
function checkPaymentStatus() {
    if (!window.currentPaymentId) {
        showToast('error', 'Payment ID not found');
        closeRecordModal();
        return;
    }

    // Hide countdown section
    document.getElementById('paymentCountdownSection').classList.add('hidden');
    document.getElementById('paymentResultSection').classList.remove('hidden');

    // Fetch payment status
    fetch('?page=api&endpoint=clients/check-payment-status', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ payment_id: window.currentPaymentId })
    })
    .then(res => res.json())
    .then(data => {
        const status = data.status?.toUpperCase() || 'PENDING';
        const resultBox = document.getElementById('resultMessageBox');
        const resultIcon = document.getElementById('resultIcon');
        const resultTitle = document.getElementById('resultTitle');
        const resultMessage = document.getElementById('resultMessage');
        const repeatBtn = document.getElementById('repeatCheckBtn');
        const autoCloseNotice = document.getElementById('autoCloseNotice');

        // Reset button visibility
        repeatBtn.classList.add('hidden');
        autoCloseNotice.classList.add('hidden');

        if (status === 'SUCCESS' || status === 'CONFIRMED') {
            // Success message
            resultBox.className = 'p-6 rounded-lg border-2 text-center border-green-300 bg-green-50';
            resultIcon.className = 'fas fa-check-circle text-6xl mb-3 block text-green-600';
            resultTitle.className = 'text-2xl font-bold mb-2 text-green-600';
            resultTitle.textContent = '✓ Thank You!';
            resultMessage.textContent = 'Your payment has been successfully received and confirmed.';
            
            // Show auto-close notice
            autoCloseNotice.classList.remove('hidden');
            startAutoCloseModal(10);
        } else if (status === 'FAILED' || status === 'ERROR') {
            // Failure message
            resultBox.className = 'p-6 rounded-lg border-2 text-center border-red-300 bg-red-50';
            resultIcon.className = 'fas fa-times-circle text-6xl mb-3 block text-red-600';
            resultTitle.className = 'text-2xl font-bold mb-2 text-red-600';
            resultTitle.textContent = 'Sorry!';
            resultMessage.textContent = 'Payment processing failed. Please try again or contact support.';
            
            // Show auto-close notice
            autoCloseNotice.classList.remove('hidden');
            startAutoCloseModal(10);
        } else {
            // Still pending - show check again button
            resultBox.className = 'p-6 rounded-lg border-2 text-center border-amber-300 bg-amber-50';
            resultIcon.className = 'fas fa-hourglass-half text-6xl mb-3 block text-amber-600';
            resultTitle.className = 'text-2xl font-bold mb-2 text-amber-600';
            resultTitle.textContent = 'Still Processing...';
            resultMessage.textContent = 'Your payment is still being processed. Please check again in a moment.';
            
            // Show check again button
            repeatBtn.classList.remove('hidden');
            repeatBtn.onclick = () => {
                document.getElementById('paymentResultSection').classList.add('hidden');
                document.getElementById('paymentCountdownSection').classList.remove('hidden');
                startPaymentCountdown(30, () => {
                    checkPaymentStatus();
                });
            };
        }
    })
    .catch(err => {
        console.error('Error checking status:', err);
        const resultBox = document.getElementById('resultMessageBox');
        const resultIcon = document.getElementById('resultIcon');
        const resultTitle = document.getElementById('resultTitle');
        const resultMessage = document.getElementById('resultMessage');
        
        resultBox.className = 'p-6 rounded-lg border-2 text-center border-gray-300 bg-gray-50';
        resultIcon.className = 'fas fa-info-circle text-6xl mb-3 block text-gray-600';
        resultTitle.className = 'text-2xl font-bold mb-2 text-gray-600';
        resultTitle.textContent = 'Unable to Check Status';
        resultMessage.textContent = 'We could not retrieve your payment status. Please try again or contact support.';
    });
}

/**
 * Start auto-close countdown and fade out modal
 * @param {number} seconds - Seconds to wait before closing
 */
function startAutoCloseModal(seconds) {
    let remaining = seconds;
    const closeCountdown = document.getElementById('closeCountdown');
    
    const interval = setInterval(() => {
        closeCountdown.textContent = remaining;
        remaining--;
        
        if (remaining < 0) {
            clearInterval(interval);
            
            // Fade out animation
            const modal = document.getElementById('recordModal');
            modal.style.transition = 'opacity 1s ease-out';
            modal.style.opacity = '0';
            
            setTimeout(() => {
                closeRecordModal();
                modal.style.opacity = '1'; // Reset for next use
                modal.style.transition = 'none';
                loadPayments(); // Reload payment list
            }, 1000);
        }
    }, 1000);
}

function updateInvoiceAmount() {
    const select = document.getElementById('invoiceSelect');
    const amount = select.options[select.selectedIndex].dataset.amount;
    const number = select.options[select.selectedIndex].dataset.number;
    
    if (amount) {
        document.getElementById('invoiceAmountText').textContent = `Invoice Total: ${Number(amount).toLocaleString()} FCFA`;
        document.getElementById('paymentAmount').max = amount;
    }
}

function submitRecordPayment() {
    // This function is not used - the form submissions are handled by the tab forms above
    showToast('error', 'Please use the payment tabs to submit payments');
}

function viewPaymentDetail(paymentId) {
    fetch(`?page=api&endpoint=clients/payment-detail&id=${paymentId}`)
    .then(res => res.json())
    .then(data => {
        if (data.success && data.payment) {
            const p = data.payment;
            const html = `
                <div class="space-y-3">
                    <div class="flex justify-between">
                        <span class="text-gray-600">Payment ID:</span>
                        <span class="font-semibold">#${p.id}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Invoice:</span>
                        <span class="font-semibold">${p.invoice_number}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Amount:</span>
                        <span class="font-bold text-green-600">${Number(p.amount).toLocaleString()} FCFA</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Method:</span>
                        <span class="font-semibold">${p.payment_method}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Status:</span>
                        <span class="font-semibold">${p.status}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-gray-600">Date:</span>
                        <span class="font-semibold">${new Date(p.payment_date).toLocaleDateString()}</span>
                    </div>
                    ${p.reference_number ? `<div class="flex justify-between">
                        <span class="text-gray-600">Reference:</span>
                        <span class="font-mono text-sm">${p.reference_number}</span>
                    </div>` : ''}
                    ${p.phone_number ? `<div class="flex justify-between">
                        <span class="text-gray-600">Phone:</span>
                        <span class="font-semibold">${p.phone_number}</span>
                    </div>` : ''}
                    ${p.notes ? `<div class="border-t pt-3">
                        <p class="text-gray-600 text-sm mb-1">Notes:</p>
                        <p class="text-sm">${p.notes}</p>
                    </div>` : ''}
                </div>
            `;
            document.getElementById('detailContent').innerHTML = html;
            document.getElementById('detailModal').classList.remove('hidden');
        }
    })
    .catch(err => showToast('error', 'Error loading payment details'));
}

function calculateSummary() {
    // Calculate summary totals from payments
    let outstanding = 0;
    let totalPaid = 0;
    let pending = 0;
    let confirmed = 0;

    <?php foreach ($invoices as $inv): ?>
        outstanding += <?php echo $inv['total_amount']; ?>;
    <?php endforeach; ?>

    <?php foreach ($payments as $pay): ?>
        totalPaid += <?php echo $pay['amount']; ?>;
        if ('<?php echo $pay['status']; ?>' === 'Pending') pending += <?php echo $pay['amount']; ?>;
        if ('<?php echo $pay['status']; ?>' === 'Confirmed') confirmed += <?php echo $pay['amount']; ?>;
    <?php endforeach; ?>

    document.getElementById('outstandingTotal').textContent = Number(outstanding).toLocaleString() + ' FCFA';
    document.getElementById('totalPayments').textContent = Number(totalPaid).toLocaleString() + ' FCFA';
    document.getElementById('pendingPayments').textContent = Number(pending).toLocaleString() + ' FCFA';
    document.getElementById('confirmedPayments').textContent = Number(confirmed).toLocaleString() + ' FCFA';
}

function downloadReceipt(paymentId) {
    // Open receipt PDF in new window
    window.open(`?page=api&endpoint=clients/payment-receipt&id=${paymentId}`, '_blank');
}

function refreshPaymentStatus(paymentId) {
    const btn = event.target.closest('button');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Checking...';
    
    fetch('?page=api&endpoint=clients/check-mobile-money-status', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ payment_id: paymentId })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showToast('success', `Payment status: ${data.status}`);
            // Reload payments after a short delay
            setTimeout(() => {
                loadPayments();
            }, 1000);
        } else {
            showToast('error', data.message || 'Failed to check status');
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-sync mr-1"></i>Check Status';
        }
    })
    .catch(err => {
        console.error('Error:', err);
        showToast('error', 'An error occurred');
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-sync mr-1"></i>Check Status';
    });
}

// Toast notification helper
function showToast(type, message) {
    Swal.fire({
        icon: type === 'success' ? 'success' : type === 'error' ? 'error' : 'info',
        title: type === 'success' ? 'Success' : type === 'error' ? 'Error' : 'Info',
        text: message,
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000
    });
}
</script>

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