<?php
/**
 * Client - My Invoices (View/Download/Pay)
 * SSCI Office Platform - Client Invoice Management
 */

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

// Check authentication
if (!$auth->isAuthenticated() || $_SESSION['role'] !== 'client') {
    header('Location: ?page=login');
    exit();
}

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">
    <div class="mb-6">
        <h1 class="text-2xl sm:text-3xl font-bold text-gray-800">
            <i class="fas fa-file-invoice-dollar text-blue-600 mr-3"></i>My Invoices
        </h1>
        <p class="text-gray-600 text-sm mt-1">View, download, and pay your invoices</p>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-2 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 Invoices</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">Outstanding</p>
            <p class="text-3xl font-bold text-yellow-600" id="outstandingAmount">0 FCFA</p>
        </div>

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

    <!-- Main Content -->
    <div class="bg-white rounded-lg shadow">
        <!-- Header with Filters -->
        <div class="p-6 border-b border-gray-200">
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <div>
                    <h2 class="text-xl font-bold text-gray-800">
                        <i class="fas fa-list mr-2"></i>All Invoices
                    </h2>
                </div>
            </div>
        </div>

        <!-- Filters -->
        <div class="p-4 bg-gray-50 border-b border-gray-200 space-y-3">
            <div class="flex flex-col sm:flex-row gap-2">
                <select id="statusFilter" onchange="filterInvoices()" class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 text-sm">
                    <option value="">All Status</option>
                    <option value="Draft">Draft</option>
                    <option value="Sent">Sent</option>
                    <option value="Viewed">Viewed</option>
                    <option value="Partially Paid">Partially Paid</option>
                    <option value="Paid">Paid</option>
                    <option value="Overdue">Overdue</option>
                    <option value="Cancelled">Cancelled</option>
                </select>
                <input type="month" id="monthFilter" onchange="filterInvoices()" class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 text-sm" placeholder="Filter by month">
                <input type="text" id="searchInvoice" onkeyup="filterInvoices()" placeholder="Search by invoice number..." class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 text-sm">
            </div>
        </div>

        <!-- Invoices Table -->
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="px-3 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Invoice #</th>
                        <th class="px-3 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Post/Facility</th>
                        <th class="px-3 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Invoice Date</th>
                        <th class="px-3 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Due Date</th>
                        <th class="px-3 py-3 text-right text-xs font-semibold text-gray-700 uppercase">Amount</th>
                        <th class="px-3 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Status</th>
                        <th class="px-3 py-3 text-center text-xs font-semibold text-gray-700 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200" id="invoicesTableBody">
                    <tr>
                        <td colspan="7" class="px-6 py-8 text-center text-gray-500">
                            <i class="fas fa-spinner animate-spin mr-2"></i>Loading invoices...
                        </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="showingStart">0</span>-<span id="showingEnd">0</span> of <span id="totalInvoices">0</span>
            </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>
                <span id="pageInfo" class="px-3 py-1 text-sm text-gray-600">Page 1</span>
                <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>

<!-- View Invoice Modal -->
<div id="viewInvoiceModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center p-4 z-50 overflow-y-auto">
    <div class="bg-white rounded-lg shadow-lg max-w-3xl w-full my-8 animate__animated animate__slideInDown">
        <div class="flex justify-between items-center p-6 border-b border-gray-200 sticky top-0 bg-white">
            <h2 class="text-xl font-bold text-gray-800">
                <i class="fas fa-file-pdf text-red-600 mr-2"></i>Invoice <span id="viewInvoiceNumber"></span>
            </h2>
            <button onclick="closeViewInvoiceModal()" class="text-gray-500 hover:text-gray-700 text-2xl">×</button>
        </div>

        <div id="invoiceDetailContent" class="p-6 max-h-96 overflow-y-auto">
            <!-- Invoice content will be loaded here -->
        </div>

        <div class="p-6 border-t border-gray-200 flex gap-3 bg-gray-50">
            <button onclick="printInvoice()" class="flex-1 bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center gap-2">
                <i class="fas fa-print"></i>Print
            </button>
            <button onclick="downloadInvoicePDF()" class="flex-1 bg-red-600 text-white py-2 rounded-lg hover:bg-red-700 transition font-semibold flex items-center justify-center gap-2">
                <i class="fas fa-download"></i>Download PDF
            </button>
            <button id="payNowBtn" class="flex-1 bg-green-600 text-white py-2 rounded-lg hover:bg-green-700 transition font-semibold flex items-center justify-center gap-2">
                <i class="fas fa-credit-card"></i>Pay Now
            </button>
        </div>
    </div>
</div>

<!-- Payment Modal -->
<div id="paymentModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center p-4 z-50 overflow-y-auto">
    <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full my-8 animate__animated animate__slideInDown">
        <div class="flex justify-between items-center p-6 border-b border-gray-200 sticky top-0 bg-white">
            <h2 class="text-xl font-bold text-gray-800">
                <i class="fas fa-money-bill text-green-600 mr-2"></i>Record Payment
            </h2>
            <button onclick="closePaymentModal()" class="text-gray-500 hover:text-gray-700 text-2xl">×</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 class="text-lg font-bold text-gray-800" id="paymentInvoiceNumber"></p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-600">Total Amount:</p>
                        <p class="text-lg font-bold text-gray-800" id="paymentInvoiceTotal"></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">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">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>

            <!-- Payment History -->
            <div class="mt-6 pt-6 border-t border-gray-200">
                <h3 class="text-lg font-bold text-gray-800 mb-3">Payment History</h3>
                <div id="paymentHistoryContainer" class="space-y-2 max-h-48 overflow-y-auto">
                    <p class="text-sm text-gray-600">No payments recorded yet</p>
                </div>
            </div>
        </div>

        <div class="p-6 border-t border-gray-200 flex gap-3 bg-gray-50">
            <button type="button" onclick="closePaymentModal()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">
                Close
            </button>
        </div>
    </div>
</div>

<script>
let currentPage = 0;
const pageSize = 10;
let allInvoices = [];
let filteredInvoices = [];
let currentInvoiceId = null;

// Get status badge
function getStatusBadge(status) {
    const badges = {
        'Draft': '<span class="px-3 py-1 bg-gray-100 text-gray-800 rounded-full text-sm font-medium"><i class="fas fa-file mr-1"></i>Draft</span>',
        'Sent': '<span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm font-medium"><i class="fas fa-envelope mr-1"></i>Sent</span>',
        'Viewed': '<span class="px-3 py-1 bg-purple-100 text-purple-800 rounded-full text-sm font-medium"><i class="fas fa-eye mr-1"></i>Viewed</span>',
        'Partially Paid': '<span class="px-3 py-1 bg-orange-100 text-orange-800 rounded-full text-sm font-medium"><i class="fas fa-hourglass-half mr-1"></i>Partial</span>',
        'Paid': '<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>Paid</span>',
        'Overdue': '<span class="px-3 py-1 bg-red-100 text-red-800 rounded-full text-sm font-medium"><i class="fas fa-exclamation-circle mr-1"></i>Overdue</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>';
}

// Convert number to words (e.g., 1234.56 -> "One Thousand Two Hundred Thirty-Four and 56/100")
function numberToWords(num) {
    const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
    const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
    const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
    const scales = ['', 'Thousand', 'Million', 'Billion', 'Trillion'];
    
    if (num === 0) return 'Zero';
    
    const parts = num.toString().split('.');
    const integer = parseInt(parts[0]);
    const decimal = parts[1] ? parseInt(parts[1].padEnd(2, '0')) : 0;
    
    let words = '';
    let scaleIndex = 0;
    let tempNum = integer;
    const groups = [];
    
    while (tempNum > 0) {
        groups.unshift(tempNum % 1000);
        tempNum = Math.floor(tempNum / 1000);
    }
    
    groups.forEach((group, index) => {
        if (group === 0) return;
        
        let groupWords = '';
        
        // Hundreds
        if (group >= 100) {
            groupWords += ones[Math.floor(group / 100)] + ' Hundred ';
        }
        
        // Tens and ones
        const remainder = group % 100;
        if (remainder >= 20) {
            groupWords += tens[Math.floor(remainder / 10)];
            if (remainder % 10 > 0) {
                groupWords += '-' + ones[remainder % 10];
            }
        } else if (remainder >= 10) {
            groupWords += teens[remainder - 10];
        } else if (remainder > 0) {
            groupWords += ones[remainder];
        }
        
        groupWords = groupWords.trim();
        if (groupWords) {
            const scaleIndex = groups.length - index - 1;
            if (scaleIndex > 0) {
                groupWords += ' ' + scales[scaleIndex];
            }
            words += groupWords + ' ';
        }
    });
    
    words = words.trim();
    if (decimal > 0) {
        words += ' and ' + String(decimal).padStart(2, '0') + '/100';
    }
    
    return words;
}

// Load invoices from API
function loadInvoices() {
    currentPage = 0;
    fetch('?page=api&endpoint=clients/my-invoices')
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                allInvoices = data.invoices || [];
                filterInvoices();
                updateSummary();
            } else {
                showToast('Error loading invoices', 'error');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('Error loading invoices', 'error');
        });
}

// Filter invoices
function filterInvoices() {
    const status = document.getElementById('statusFilter').value;
    const month = document.getElementById('monthFilter').value;
    const search = document.getElementById('searchInvoice').value.toLowerCase();

    filteredInvoices = allInvoices.filter(invoice => {
        if (status && invoice.status !== status) return false;
        if (month && !invoice.invoice_date.startsWith(month)) return false;
        if (search) {
            const searchStr = (invoice.invoice_number || '').toLowerCase();
            if (!searchStr.includes(search)) return false;
        }
        return true;
    });

    currentPage = 0;
    displayInvoices();
}

// Display invoices table
function displayInvoices() {
    const tbody = document.getElementById('invoicesTableBody');
    const startIdx = currentPage * pageSize;
    const endIdx = startIdx + pageSize;
    const paginated = filteredInvoices.slice(startIdx, endIdx);

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

    tbody.innerHTML = paginated.map(invoice => {
        const isPaid = invoice.status === 'Paid';
        const isPartial = invoice.status === 'Partially Paid';
        const canPay = !isPaid;
        
        return `
        <tr class="hover:bg-gray-50 transition">
            <td class="px-3 py-3 text-sm font-mono text-gray-900">#${invoice.invoice_number}</td>
            <td class="px-3 py-3 text-sm text-gray-700">${invoice.post_name || 'N/A'}</td>
            <td class="px-3 py-3 text-sm text-gray-600">${new Date(invoice.invoice_date).toLocaleDateString('en-GB')}</td>
            <td class="px-3 py-3 text-sm text-gray-600">${new Date(invoice.due_date).toLocaleDateString('en-GB')}</td>
            <td class="px-3 py-3 text-sm font-semibold text-gray-900 text-right">${parseFloat(invoice.total_amount).toLocaleString('en-US')} FCFA</td>
            <td class="px-3 py-3 text-sm">${getStatusBadge(invoice.status)}</td>
            <td class="px-3 py-3 text-sm space-x-1 text-center">
                <button onclick="viewInvoice(${invoice.id})" class="text-blue-600 hover:text-blue-800 transition" title="View">
                    <i class="fas fa-eye"></i>
                </button>
                ${canPay ? `<button onclick="openPaymentModal(${invoice.id})" class="text-green-600 hover:text-green-800 transition" title="Pay Now">
                    <i class="fas fa-credit-card"></i>
                </button>` : ''}
            </td>
        </tr>
    `;
    }).join('');

    const total = filteredInvoices.length;
    document.getElementById('showingStart').textContent = startIdx + 1;
    document.getElementById('showingEnd').textContent = Math.min(endIdx, total);
    document.getElementById('totalInvoices').textContent = total;
    document.getElementById('pageInfo').textContent = 'Page ' + (currentPage + 1);
    document.getElementById('prevBtn').disabled = currentPage === 0;
    document.getElementById('nextBtn').disabled = endIdx >= total;
}

// Update summary stats
function updateSummary(invoices = allInvoices) {
    const total = invoices.length;
    const totalAmount = invoices.reduce((sum, i) => sum + (parseFloat(i.total_amount) || 0), 0);
    const outstandingAmount = invoices
        .filter(i => i.status !== 'Paid' && i.status !== 'Cancelled')
        .reduce((sum, i) => sum + (parseFloat(i.total_amount) || 0), 0);
    const paidAmount = invoices
        .filter(i => i.status === 'Paid')
        .reduce((sum, i) => sum + (parseFloat(i.total_amount) || 0), 0);

    document.getElementById('totalCount').textContent = total;
    document.getElementById('totalAmount').textContent = totalAmount.toLocaleString('en-US', { maximumFractionDigits: 0 }) + ' FCFA';
    document.getElementById('outstandingAmount').textContent = outstandingAmount.toLocaleString('en-US', { maximumFractionDigits: 0 }) + ' FCFA';
    document.getElementById('paidAmount').textContent = paidAmount.toLocaleString('en-US', { maximumFractionDigits: 0 }) + ' FCFA';
}

// View invoice
function viewInvoice(invoiceId) {
    fetch(`?page=api&endpoint=clients/my-invoice&id=${invoiceId}`)
        .then(r => r.json())
        .then(data => {
            if (data.success && data.invoice) {
                const inv = data.invoice;
                const company = data.company || {};
                currentInvoiceId = inv.id;
                document.getElementById('viewInvoiceNumber').textContent = inv.invoice_number;
                
                const invoiceDate = new Date(inv.invoice_date).toLocaleDateString('en-US');
                const dueDate = new Date(inv.due_date).toLocaleDateString('en-US');
                
                // Build letterhead HTML (same as admin)
                let letterheadHtml = '';
                if (company.letterhead) {
                    letterheadHtml = `
                        <div class="mb-8 pb-8 border-b border-gray-300">
                            <div class="flex items-center justify-center mb-4">
                                <img src="${company.letterhead}" alt="Letterhead" style="width: 100%; object-fit: contain;">
                            </div>
                        </div>
                    `;
                } else if (company.logo) {
                    letterheadHtml = `
                        <div class="mb-8 pb-8 border-b border-gray-300">
                            <div class="text-center">
                                <img src="${company.logo}" alt="Logo" style="max-height: 80px; display: inline-block; margin-bottom: 0.5rem;">
                                <h1 class="text-xl font-bold text-gray-900">${company.site_name || 'SHEPHERD SECURITY AND CONSULTANCY INTERNATIONAL'}</h1>
                                <p class="text-sm text-gray-600">${company.site_acronym || 'SSCI'}</p>
                            </div>
                        </div>
                    `;
                } else {
                    letterheadHtml = `
                        <div class="mb-8 pb-8 border-b border-gray-300">
                            <div class="text-center">
                                <h1 class="text-2xl font-bold text-gray-900">${company.site_name || 'SHEPHERD SECURITY AND CONSULTANCY INTERNATIONAL'}</h1>
                                <p class="text-sm text-gray-600">${company.site_acronym || 'SSCI'}</p>
                            </div>
                        </div>
                    `;
                }
                
                let html = letterheadHtml + `
                    <div class="grid grid-cols-2 gap-6 mb-8">
                        <div>
                            <h3 class="text-sm text-gray-600 font-semibold">Invoice Number</h3>
                            <p class="text-2xl font-bold text-gray-900">${inv.invoice_number}</p>
                        </div>
                        <div class="text-right">
                            <h3 class="text-sm text-gray-600 font-semibold">Status</h3>
                            <p>${getStatusBadge(inv.status)}</p>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-6 mb-8 pb-8 border-b border-gray-200">
                        <div>
                            <h4 class="text-sm text-gray-600 font-semibold mb-2">Bill To</h4>
                            <p class="font-semibold text-gray-900">${inv.owner_name || 'N/A'}</p>
                            <p class="text-sm text-gray-600">${inv.owner_email || ''}</p>
                        </div>
                        <div class="text-right">
                            <p class="text-sm"><strong>Invoice Date:</strong> ${invoiceDate}</p>
                            <p class="text-sm"><strong>Due Date:</strong> ${dueDate}</p>
                            <p class="text-sm"><strong>Post/Facility:</strong> ${inv.post_name || 'N/A'}</p>
                            <p class="text-sm"><strong>Currency:</strong> ${inv.currency || 'FCFA'}</p>
                        </div>
                    </div>
                    
                    <table class="w-full mb-8">
                        <thead class="bg-gray-50 border-y border-gray-200">
                            <tr>
                                <th class="px-4 py-2 text-left text-sm font-semibold text-gray-700">Description</th>
                                <th class="px-4 py-2 text-right text-sm font-semibold text-gray-700">Quantity</th>
                                <th class="px-4 py-2 text-right text-sm font-semibold text-gray-700">Unit Price</th>
                                <th class="px-4 py-2 text-right text-sm font-semibold text-gray-700">Total</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                `;
                
                if (data.services && data.services.length > 0) {
                    data.services.forEach(svc => {
                        const quantity = parseFloat(svc.quantity) || 1;
                        const unitCost = parseFloat(svc.unit_cost) || 0;
                        const serviceTotal = quantity * unitCost;
                        html += `
                            <tr>
                                <td class="px-4 py-2 text-sm">${svc.service_name || 'Service'}</td>
                                <td class="px-4 py-2 text-right text-sm">${quantity}</td>
                                <td class="px-4 py-2 text-right text-sm">${parseFloat(unitCost).toLocaleString('en-US')} FCFA</td>
                                <td class="px-4 py-2 text-right text-sm font-semibold">${serviceTotal.toLocaleString('en-US')} FCFA</td>
                            </tr>
                        `;
                    });
                }
                
                html += `
                        </tbody>
                    </table>
                    
                    <div class="flex justify-end mb-8">
                        <div class="w-full md:w-1/3">
                            <div class="flex justify-between mb-2">
                                <span class="text-gray-600">Subtotal:</span>
                                <span class="font-semibold">${parseFloat(inv.subtotal || 0).toLocaleString('en-US')} FCFA</span>
                            </div>
                            <div class="flex justify-between mb-2 pb-2 border-b border-gray-200">
                                <span class="text-gray-600">Tax:</span>
                                <span class="font-semibold">${parseFloat(inv.tax_amount || 0).toLocaleString('en-US')} FCFA</span>
                            </div>
                            <div class="flex justify-between text-lg">
                                <span class="font-bold">Total:</span>
                                <span class="font-bold text-blue-600">${parseFloat(inv.total_amount || 0).toLocaleString('en-US')} FCFA</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 p-4 rounded border border-gray-200 mb-4">
                        <p class="text-sm text-gray-700"><strong>Amount in Words:</strong></p>
                        <p class="text-sm font-semibold text-gray-900">${numberToWords(parseFloat(inv.total_amount))} FCFA</p>
                    </div>
                    
                    ${inv.notes ? `<div class="bg-gray-50 p-4 rounded border border-gray-200"><strong>Notes:</strong><br>${inv.notes}</div>` : ''}
                `;
                
                document.getElementById('invoiceDetailContent').innerHTML = html;
                document.getElementById('viewInvoiceModal').classList.remove('hidden');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('Error loading invoice details', 'error');
        });
}

// Close view invoice modal
function closeViewInvoiceModal() {
    document.getElementById('viewInvoiceModal').classList.add('hidden');
}

// Print invoice
function printInvoice() {
    const content = document.getElementById('invoiceDetailContent');
    if (!content) return;

    const printWindow = window.open('', '', 'width=800,height=600');
    const html = `<!DOCTYPE html>
    <html>
    <head>
        <title>Invoice Print</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 20px; }
            table { width: 100%; border-collapse: collapse; margin: 20px 0; }
            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; }
            .text-right { text-align: right; }
            .font-bold { font-weight: bold; }
            h3 { color: #333; }
        </style>
    </head>
    <body>${content.innerHTML}</body>
    </html>`;
    
    printWindow.document.write(html);
    printWindow.document.close();
    
    setTimeout(() => {
        printWindow.print();
        printWindow.onafterprint = function() { printWindow.close(); }
    }, 250);
}

// Download PDF
function downloadInvoicePDF() {
    if (currentInvoiceId) {
        window.location.href = `?page=api&endpoint=clients/invoice-pdf&id=${currentInvoiceId}`;
    }
}

// Payment modal functions
document.getElementById('payNowBtn')?.addEventListener('click', function() {
    if (currentInvoiceId) {
        openPaymentModal(currentInvoiceId);
    }
});

function openPaymentModal(invoiceId) {
    const invoice = allInvoices.find(i => i.id == invoiceId);
    if (!invoice) return;

    document.getElementById('paymentInvoiceNumber').textContent = invoice.invoice_number;
    document.getElementById('paymentInvoiceTotal').textContent = parseFloat(invoice.total_amount).toLocaleString('en-US') + ' FCFA';
    
    currentInvoiceId = invoiceId;
    setupPaymentTabs();
    document.getElementById('paymentModal').classList.remove('hidden');
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.add('hidden');
}

// Setup payment tabs
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(tab => {
                tab.classList.add('hidden');
            });
            
            // Reset button styles
            document.querySelectorAll('.payment-tab-btn').forEach(b => {
                b.classList.remove('border-green-600', 'text-green-600', 'active');
                b.classList.add('border-transparent', 'text-gray-600');
            });
            
            // Show selected tab
            document.getElementById(tabName + '-payment-tab').classList.remove('hidden');
            
            // Update button style
            this.classList.remove('border-transparent', 'text-gray-600');
            this.classList.add('border-green-600', 'text-green-600', 'active');
        });
    });
}

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

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

// Submit manual payment
document.getElementById('manualPaymentForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const method = document.getElementById('manualPaymentMethod').value;
    const amount = document.getElementById('manualPaymentAmount').value;
    const description = document.getElementById('manualPaymentDescription').value;
    
    if (!method || !amount) {
        showToast('Please fill all required fields', 'warning');
        return;
    }
    
    const payload = {
        invoice_id: currentInvoiceId,
        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(payload)
    })
    .then(r => r.json())
    .then(data => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Record Payment';
        
        if (data.success) {
            // Manual payments are recorded directly - no need for countdown or status checking
            showToast('Payment recorded successfully!', 'success');
            closePaymentModal(); // Close modal
            loadInvoices(); // Reload invoices
        } else {
            showToast(data.message || 'Error recording payment', 'error');
        }
    })
    .catch(err => {
        console.error('Error:', err);
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Record Payment';
        showToast('Error recording payment', 'error');
    });
});

// Submit mobile money payment
document.getElementById('mobileMoneyPaymentForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const phone = document.getElementById('mobileMoneyPhone').value;
    const amount = document.getElementById('mobileMoneyAmount').value;
    
    if (!phone || !amount) {
        showToast('Please fill all required fields', 'warning');
        return;
    }
    
    const payload = {
        invoice_id: currentInvoiceId,
        phone: phone,
        amount: amount
    };

    // 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(payload)
    })
    .then(r => r.json())
    .then(data => {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-check mr-2"></i>Request Mobile Money Payment';
        
        if (data.success) {
            // Store payment ID for status checking
            window.currentPaymentId = data.payment_id;
            
            // Show USSD code
            if (data.ussd_code) {
                document.getElementById('operatorCode').textContent = data.operator || 'Campay';
                document.getElementById('ussdCode').textContent = data.ussd_code || '*126#';
                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(data.message || 'Error requesting payment', 'error');
        }
    })
    .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 requesting payment', 'error');
    });
});

            
// Pagination
function nextPage() {
    if ((currentPage + 1) * pageSize < filteredInvoices.length) {
        currentPage++;
        displayInvoices();
    }
}

function previousPage() {
    if (currentPage > 0) {
        currentPage--;
        displayInvoices();
    }
}

/**
 * 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('Payment ID not found', 'error');
        closePaymentModal();
        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('paymentModal');
            modal.style.transition = 'opacity 1s ease-out';
            modal.style.opacity = '0';
            
            setTimeout(() => {
                closePaymentModal();
                modal.style.opacity = '1'; // Reset for next use
                modal.style.transition = 'none';
                loadInvoices(); // Reload invoice list
            }, 1000);
        }
    }, 1000);
}

// Initialize on page load
window.addEventListener('load', function() {
    loadInvoices();
});
</script>

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