<?php
/**
 * Invoicing System Page
 * SSCI Office Platform
 */

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

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

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

$action = $_GET['action'] ?? null;
$invoiceId = $_GET['id'] ?? null;
?>

<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><?php echo trans('invoices'); ?>
        </h1>
        <p class="text-gray-600 text-sm mt-1"><?php echo trans('manage_invoices_and_billing'); ?></p>
    </div>

    <!-- Tabs Navigation -->
    <div class="bg-white rounded-lg shadow mb-6 overflow-hidden">
        <div class="flex border-b border-gray-200 overflow-x-auto">
            <button class="tab-btn flex-1 min-w-max px-6 py-4 text-center font-semibold transition-all active" data-tab="invoices">
                <i class="fas fa-list mr-2"></i><?php echo trans('all_invoices'); ?>
            </button>
            <button class="tab-btn flex-1 min-w-max px-6 py-4 text-center font-semibold transition-all text-gray-600 hover:text-gray-900" data-tab="generate">
                <i class="fas fa-plus mr-2"></i><?php echo trans('generate_invoices'); ?>
            </button>
            <button class="tab-btn flex-1 min-w-max px-6 py-4 text-center font-semibold transition-all text-gray-600 hover:text-gray-900" data-tab="settings">
                <i class="fas fa-cog mr-2"></i><?php echo trans('billing_settings'); ?>
            </button>
        </div>
    </div>

    <!-- Invoices Tab -->
    <div class="tab-content active" id="invoices-content">
        <div class="bg-white rounded-lg shadow">
            <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 class="flex-1">
                        <h2 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-file-invoice text-blue-600 mr-2"></i><?php echo trans('all_invoices'); ?>
                        </h2>
                    </div>
                    <div class="flex gap-2 w-full sm:w-auto">
                        <button onclick="openCreateInvoiceModal()" class="flex-1 sm:flex-none bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center gap-2">
                            <i class="fas fa-plus"></i><?php echo trans('new_invoice'); ?>
                        </button>
                    </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="Partial">Partial</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 or client..." class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 text-sm">
                </div>
                
                <!-- Bulk Actions Bar -->
                <div id="bulkActionsContainer" class="hidden flex flex-wrap gap-2 items-center p-3 bg-blue-50 border border-blue-200 rounded-lg">
                    <span class="text-sm font-semibold text-blue-900" id="selectedCount"></span>
                    <select id="bulkStatusSelect" class="px-3 py-1 border border-gray-300 rounded text-sm focus:outline-none focus:border-blue-500">
                        <option value="">Change Status To...</option>
                        <option value="Draft">Draft</option>
                        <option value="Sent">Sent</option>
                        <option value="Partial">Partial</option>
                        <option value="Paid">Paid</option>
                        <option value="Overdue">Overdue</option>
                        <option value="Cancelled">Cancelled</option>
                    </select>
                    <button type="button" onclick="applyBulkStatusChange()" class="px-3 py-1 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 transition">Apply</button>
                    <button type="button" onclick="sendSelectedInvoices()" class="px-3 py-1 bg-green-600 text-white rounded text-sm hover:bg-green-700 transition" title="Coming soon">Send Now</button>
                    <button type="button" onclick="clearBulkSelection()" class="px-3 py-1 bg-gray-400 text-white rounded text-sm hover:bg-gray-500 transition ml-auto">Clear Selection</button>
                </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">
                                <input type="checkbox" id="selectAllInvoices" onchange="toggleSelectAll(this)" class="rounded border-gray-300 cursor-pointer">
                            </th>
                            <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">Client</th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-700 uppercase">Post</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">Month</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"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Generate Invoices Tab -->
    <div class="tab-content hidden" id="generate-content">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Generation Form -->
            <div class="lg:col-span-2 bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-6">
                    <i class="fas fa-magic text-blue-600 mr-2"></i><?php echo trans('generate_monthly_invoices'); ?>
                </h2>

                <form id="generateInvoicesForm" class="space-y-6">
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-calendar text-blue-600 mr-2"></i><?php echo trans('billing_month'); ?>
                        </label>
                        <input type="month" id="billingMonth" name="billing_month" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required>
                    </div>

                    <div>
                        <label class="block text-gray-700 font-semibold mb-3">
                            <i class="fas fa-building text-blue-600 mr-2"></i>Select Posts/Facilities
                        </label>
                        <div class="space-y-2 max-h-64 overflow-y-auto border border-gray-300 rounded-lg p-3">
                            <div class="flex items-center gap-2 mb-2">
                                <input type="checkbox" id="selectAllPosts" class="w-5 h-5 rounded border-gray-300" onchange="toggleAllPosts(this)">
                                <label for="selectAllPosts" class="text-gray-700 font-semibold cursor-pointer">Select All Active Posts</label>
                            </div>
                            <div id="postsList" class="space-y-2">
                                <!-- Populated by JS -->
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-sticky-note text-blue-600 mr-2"></i>Invoice Note (Optional)
                        </label>
                        <textarea name="invoice_note" id="invoiceNote" rows="3" placeholder="Add any notes to include in the invoices..." class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"></textarea>
                    </div>

                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <p class="text-sm text-blue-800">
                            <i class="fas fa-info-circle mr-2"></i>
                            <?php echo trans('invoice_generation_info'); ?>
                        </p>
                    </div>

                    <div class="flex gap-3">
                        <button type="submit" class="flex-1 bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition font-semibold flex items-center justify-center gap-2">
                            <i class="fas fa-cogs"></i><?php echo trans('generate_invoices'); ?>
                        </button>
                        <button type="button" id="scheduleAutoGenerate" class="flex-1 bg-green-600 text-white py-3 rounded-lg hover:bg-green-700 transition font-semibold flex items-center justify-center gap-2">
                            <i class="fas fa-clock"></i><?php echo trans('schedule_auto_generate'); ?>
                        </button>
                    </div>
                </form>
            </div>

            <!-- Statistics Card -->
            <div class="space-y-6">
                <div class="bg-white rounded-lg shadow p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4">
                        <i class="fas fa-chart-bar text-blue-600 mr-2"></i><?php echo trans('billing_stats'); ?>
                    </h3>
                    <div class="space-y-4">
                        <div>
                            <p class="text-gray-600 text-sm">Active Clients</p>
                            <p class="text-3xl font-bold text-blue-600" id="activeClientsCount">-</p>
                        </div>
                        <div>
                            <p class="text-gray-600 text-sm">Expected Revenue</p>
                            <p class="text-3xl font-bold text-green-600" id="expectedRevenue">-</p>
                        </div>
                        <div>
                            <p class="text-gray-600 text-sm">Unpaid Invoices</p>
                            <p class="text-3xl font-bold text-orange-600" id="unpaidCount">-</p>
                        </div>
                    </div>
                </div>

                <div class="bg-amber-50 border border-amber-200 rounded-lg p-4">
                    <h4 class="font-semibold text-amber-900 mb-2">
                        <i class="fas fa-lightbulb mr-2"></i>Tip
                    </h4>
                    <p class="text-sm text-amber-800">
                        <?php echo trans('auto_generate_tip'); ?>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Settings Tab -->
    <div class="tab-content hidden" id="settings-content">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Billing Settings -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-6">
                    <i class="fas fa-cog text-blue-600 mr-2"></i><?php echo trans('billing_settings'); ?>
                </h2>

                <form id="billingSettingsForm" class="space-y-4">
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-hashtag text-blue-600 mr-2"></i>Invoice Number Prefix
                        </label>
                        <input type="text" name="invoice_prefix" placeholder="INV-" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" value="INV-">
                    </div>

                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-percent text-blue-600 mr-2"></i>Tax Rate (%)
                        </label>
                        <input type="number" name="tax_rate" step="0.01" placeholder="0.00" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" value="0.00">
                    </div>

                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-calendar-alt text-blue-600 mr-2"></i>Invoice Due Days
                        </label>
                        <input type="number" name="due_days" placeholder="30" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" value="30">
                    </div>

                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-envelope text-blue-600 mr-2"></i>Auto-send Invoice Email
                        </label>
                        <label class="flex items-center gap-3 cursor-pointer p-2 hover:bg-gray-50 rounded transition">
                            <input type="checkbox" name="auto_send_email" class="w-5 h-5 rounded border-gray-300" checked>
                            <span class="text-gray-700">Send invoice emails automatically</span>
                        </label>
                    </div>

                    <button type="submit" class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700 transition font-semibold">
                        <?php echo trans('save_settings'); ?>
                    </button>
                </form>
            </div>

            <!-- Auto-generate Cron Settings -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-6">
                    <i class="fas fa-clock text-green-600 mr-2"></i><?php echo trans('auto_generate_settings'); ?>
                </h2>

                <form id="cronSettingsForm" class="space-y-4">
                    <div>
                        <label class="flex items-center gap-3 cursor-pointer p-2 hover:bg-gray-50 rounded transition">
                            <input type="checkbox" id="enableAutoGenerate" name="enable_auto_generate" class="w-5 h-5 rounded border-gray-300">
                            <span class="text-gray-700 font-semibold">Enable Monthly Auto-Generation</span>
                        </label>
                        <p class="text-xs text-gray-500 mt-1 ml-8">Invoices will be generated automatically on the selected day each month</p>
                    </div>

                    <div id="cronSettings" class="hidden space-y-4 pt-4 border-t border-gray-200">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-calendar-day text-blue-600 mr-2"></i>Generation Day of Month
                            </label>
                            <div class="flex gap-2">
                                <select name="auto_generate_day" id="autoGenerateDaySelect" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500">
                                    <option value="">Custom</option>
                                    <option value="1">1st (First day)</option>
                                    <option value="5">5th</option>
                                    <option value="10">10th</option>
                                    <option value="15" selected>15th (Mid-month)</option>
                                    <option value="20">20th</option>
                                    <option value="28">28th (Safe for all months)</option>
                                </select>
                                <input type="number" name="auto_generate_day_custom" id="autoGenerateDayCustom" min="1" max="31" placeholder="Day" class="w-20 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 hidden" required>
                            </div>
                        </div>

                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-clock text-blue-600 mr-2"></i>Generation Time
                            </label>
                            <input type="time" name="auto_generate_time" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" value="02:00">
                            <p class="text-xs text-gray-500 mt-1">Server will generate invoices at this time</p>
                        </div>

                        <div class="bg-green-50 border border-green-200 rounded-lg p-3">
                            <p class="text-sm text-green-800">
                                <i class="fas fa-check-circle mr-2"></i>
                                Status: <span id="cronStatus">Not Configured</span>
                            </p>
                        </div>
                    </div>

                    <button type="submit" class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700 transition font-semibold">
                        <?php echo trans('save_settings'); ?>
                    </button>
                </form>
            </div>

            <!-- Payment Gateway Settings -->
            <div class="bg-white rounded-lg shadow p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-6">
                    <i class="fas fa-credit-card text-purple-600 mr-2"></i>Payment Gateway Settings
                </h2>

                <form id="paymentGatewayForm" class="space-y-4">
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-mobile-alt text-purple-600 mr-2"></i>Campay API Token (JWT)
                        </label>
                        <textarea name="campay_api_token" id="campayApiToken" placeholder="Paste your Campay JWT token here..." class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-purple-500 font-mono text-sm" rows="4"></textarea>
                        <p class="text-xs text-gray-500 mt-2">
                            <i class="fas fa-info-circle mr-1"></i>
                            Get your API token from <a href="https://campay.net" target="_blank" class="text-purple-600 hover:text-purple-700 underline">campay.net</a>
                        </p>
                    </div>

                    <div class="bg-purple-50 border border-purple-200 rounded-lg p-3">
                        <p class="text-sm text-purple-800">
                            <i class="fas fa-info-circle mr-2"></i>
                            <strong>Campay Charges:</strong> 3% fee (borne by client)
                        </p>
                    </div>

                    <button type="submit" class="w-full bg-purple-600 text-white py-2 rounded-lg hover:bg-purple-700 transition font-semibold">
                        Save Payment Settings
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Load current settings
function loadPaymentSettings() {
    fetch('?page=api&endpoint=invoices/settings&action=get')
        .then(r => r.json())
        .then(data => {
            if (data.success && data.settings) {
                document.getElementById('campayApiToken').value = data.settings.campay_api_token || '';
            }
        })
        .catch(err => console.error('Error loading settings:', err));
}

// Payment Gateway Form Handler
document.getElementById('paymentGatewayForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const data = Object.fromEntries(formData);
    
    fetch('?page=api&endpoint=invoices/settings', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            Swal.fire('Success', 'Payment settings saved', 'success');
        } else {
            Swal.fire('Error', data.message || 'Error saving settings', 'error');
        }
    })
    .catch(err => Swal.fire('Error', 'Error saving settings', 'error'));
});

// Load settings when tab is clicked
document.querySelectorAll('.tab-btn').forEach(btn => {
    if (btn.getAttribute('data-tab') === 'settings') {
        btn.addEventListener('click', () => {
            setTimeout(loadPaymentSettings, 100);
        });
    }
});

// Load on page load
window.addEventListener('load', () => {
    if (document.getElementById('campayApiToken')) {
        loadPaymentSettings();
    }
});
</script>

<!-- Create/Edit Invoice Modal -->
<div id="invoiceModal" class="fixed inset-0 bg-black bg-opacity-50 hidden flex items-center justify-center p-2 sm:p-4 z-50 overflow-y-auto">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[95vh] flex flex-col animate__animated animate__slideInDown">
        <div class="flex justify-between items-center p-4 sm:p-6 border-b border-gray-200 sticky top-0 bg-white z-10">
            <h2 class="text-lg sm:text-xl font-bold text-gray-800" id="invoiceModalTitle"><?php echo trans('new_invoice'); ?></h2>
            <button onclick="closeInvoiceModal()" class="text-gray-500 hover:text-gray-700 text-2xl flex-shrink-0 ml-2">×</button>
        </div>

        <form id="invoiceForm" class="overflow-y-auto flex-1 p-4 sm:p-6 space-y-4">
            <input type="hidden" name="id" id="invoiceId">
            <input type="hidden" name="services" id="invoiceServices">

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-user text-blue-600 mr-2"></i><?php echo trans('facility_owner'); ?> *
                    </label>
                    <select name="owner_id" id="invoiceOwnerId" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required onchange="filterPostsByOwner();loadServicesFromPost()">
                        <option value="">Select Facility Owner</option>
                    </select>
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-building text-blue-600 mr-2"></i><?php echo trans('post'); ?>
                    </label>
                    <select name="post_id" id="invoicePostId" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" onchange="loadServicesFromPost()">
                        <option value="">Select Post (Optional)</option>
                    </select>
                </div>
            </div>

            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-calendar-alt text-blue-600 mr-2"></i><?php echo trans('billing_month'); ?>
                </label>
                <input type="month" name="invoice_month" id="invoiceMonth" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500">
                <p class="text-xs text-gray-500 mt-1">Optional: Specify the billing month for this invoice</p>
            </div>

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-calendar text-blue-600 mr-2"></i><?php echo trans('invoice_date'); ?> *
                    </label>
                    <input type="date" name="invoice_date" id="invoiceDateInput" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" required>
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-hourglass-end text-blue-600 mr-2"></i><?php echo trans('due_date'); ?>
                    </label>
                    <input type="date" name="due_date" id="invoiceDueDate" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500">
                </div>
            </div>

            <!-- Services Editor -->
            <div class="border-t pt-4">
                <div class="flex justify-between items-center mb-3">
                    <label class="block text-gray-700 font-semibold">
                        <i class="fas fa-list text-blue-600 mr-2"></i>Services
                    </label>
                    <button type="button" onclick="addServiceRow()" class="text-sm bg-green-600 text-white px-3 py-1 rounded hover:bg-green-700 transition">
                        <i class="fas fa-plus mr-1"></i>Add Service
                    </button>
                </div>
                <div id="servicesContainer" class="space-y-2 max-h-40 overflow-y-auto bg-gray-50 p-3 rounded">
                    <!-- Service rows will be added here -->
                </div>
            </div>

            <!-- Grand Total Display -->
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div class="grid grid-cols-2 gap-4 mb-3">
                    <div>
                        <p class="text-xs text-gray-600">Subtotal</p>
                        <p class="text-lg font-semibold text-gray-900" id="invoiceSubtotal">0.00</p>
                    </div>
                    <div>
                        <p class="text-xs text-gray-600">Tax</p>
                        <p class="text-lg font-semibold text-gray-900" id="invoiceTax">0.00</p>
                    </div>
                </div>
                <div class="border-t border-blue-200 pt-3">
                    <p class="text-xs text-gray-600 mb-1">Grand Total</p>
                    <p class="text-2xl font-bold text-blue-600 mb-2" id="invoiceGrandTotal">0.00</p>
                    <p class="text-sm text-gray-700 bg-white p-2 rounded" id="invoiceAmountInWords">Zero</p>
                </div>
            </div>

            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-sticky-note text-blue-600 mr-2"></i><?php echo trans('notes'); ?>
                </label>
                <textarea name="notes" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500" rows="2" placeholder="Invoice notes..."></textarea>
            </div>

            <div class="flex gap-3 pt-4 border-t border-gray-200">
                <button type="submit" 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-save"></i><?php echo trans('save'); ?>
                </button>
                <button type="button" onclick="closeInvoiceModal()" class="flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">
                    <?php echo trans('cancel'); ?>
                </button>
            </div>
        </form>
    </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">
            <!-- 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><?php echo trans('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><?php echo trans('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><?php echo trans('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">
            <!-- Invoice Summary -->
            <div class="bg-blue-50 p-4 rounded border border-blue-200 mb-6">
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <p class="text-sm text-gray-600">Invoice Number:</p>
                        <p 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>
// 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;
}

// Store all posts for filtering
let allPosts = [];

// Filter posts by selected owner
function filterPostsByOwner() {
    const ownerId = document.getElementById('invoiceOwnerId').value;
    const postSelect = document.getElementById('invoicePostId');
    
    if (!ownerId) {
        // Reset to all posts if no owner selected
        postSelect.innerHTML = '<option value="">Select Post (Optional)</option>' + allPosts.map(post => `
            <option value="${post.id}">${post.name}</option>
        `).join('');
        return;
    }
    
    // Filter posts by owner_id
    const filteredPosts = allPosts.filter(post => post.owner_id == ownerId);
    postSelect.innerHTML = '<option value="">Select Post (Optional)</option>' + filteredPosts.map(post => `
        <option value="${post.id}">${post.name}</option>
    `).join('');
}

// Load services from selected post
function loadServicesFromPost() {
    const postId = document.getElementById('invoicePostId').value;
    const container = document.getElementById('servicesContainer');
    
    if (!postId) {
        container.innerHTML = '';
        updateInvoiceTotals();
        return;
    }
    
    // Fetch post data to get services
    fetch(`?page=api&endpoint=posts/get&id=${postId}`)
        .then(r => r.json())
        .then(data => {
            if (data.success && data.post && data.post.services) {
                const services = typeof data.post.services === 'string' ? JSON.parse(data.post.services) : data.post.services;
                container.innerHTML = '';
                services.forEach((service, index) => {
                    addServiceRow(service.name, service.qty, service.unit_cost);
                });
                updateInvoiceTotals();
            }
        })
        .catch(err => console.error('Error loading services:', err));
}

// Add a service row to the editor
function addServiceRow(name = '', qty = 1, unitCost = 0) {
    const container = document.getElementById('servicesContainer');
    const rowIndex = container.querySelectorAll('.service-row').length;
    
    const row = document.createElement('div');
    row.className = 'service-row grid grid-cols-4 gap-2 mb-2 p-2 bg-white rounded border border-gray-200';
    row.innerHTML = `
        <input type="text" class="service-name px-2 py-1 border border-gray-300 rounded text-sm" placeholder="Service name" value="${name}" onchange="updateInvoiceTotals()">
        <input type="number" class="service-qty px-2 py-1 border border-gray-300 rounded text-sm" placeholder="Qty" value="${qty}" step="any" onchange="updateInvoiceTotals()">
        <input type="number" class="service-unit-cost px-2 py-1 border border-gray-300 rounded text-sm" placeholder="Unit cost" value="${unitCost}" step="any" onchange="updateInvoiceTotals()">
        <button type="button" onclick="this.closest('.service-row').remove(); updateInvoiceTotals();" class="text-red-600 hover:text-red-700 text-sm font-semibold">
            <i class="fas fa-trash"></i>
        </button>
    `;
    container.appendChild(row);
}

// Calculate and update invoice totals
function updateInvoiceTotals() {
    let subtotal = 0;
    
    // Calculate subtotal from services
    document.querySelectorAll('#servicesContainer .service-row').forEach(row => {
        const qty = parseFloat(row.querySelector('.service-qty').value) || 0;
        const unitCost = parseFloat(row.querySelector('.service-unit-cost').value) || 0;
        subtotal += (qty * unitCost);
    });
    
    const tax = 0; // TODO: Get tax rate from settings
    const total = subtotal + tax;
    
    // Update display
    document.getElementById('invoiceSubtotal').textContent = subtotal.toFixed(2);
    document.getElementById('invoiceTax').textContent = tax.toFixed(2);
    document.getElementById('invoiceGrandTotal').textContent = total.toFixed(2);
    document.getElementById('invoiceAmountInWords').textContent = numberToWords(total) + ' FCFA';
}

// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        const tabName = this.getAttribute('data-tab');
        
        document.querySelectorAll('.tab-btn').forEach(b => {
            b.classList.add('text-gray-600', 'hover:text-gray-900');
            b.classList.remove('text-blue-600', 'border-b-2', 'border-blue-600');
        });
        
        this.classList.remove('text-gray-600', 'hover:text-gray-900');
        this.classList.add('text-blue-600', 'border-b-2', 'border-blue-600');
        
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });
        
        document.getElementById(tabName + '-content').classList.remove('hidden');
        
        if (tabName === 'invoices') {
            loadInvoices();
        } else if (tabName === 'generate') {
            loadGenerateInvoicesTab();
        }
    });
});

// Set today's date as default invoice date
function setDefaultDates() {
    const today = new Date();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const year = today.getFullYear();
    
    document.getElementById('invoiceDateInput').value = `${year}-${month}-${day}`;
    document.getElementById('invoiceMonth').value = `${year}-${month}`;
    
    // Set due date to 30 days later
    const dueDate = new Date(today);
    dueDate.setDate(dueDate.getDate() + 30);
    const dueDateString = dueDate.toISOString().split('T')[0];
    document.getElementById('invoiceDueDate').value = dueDateString;
}

// Load invoices list with optional filters
function loadInvoices(filters = {}) {
    const tbody = document.getElementById('invoicesTableBody');
    tbody.innerHTML = '<tr><td colspan="9" class="px-6 py-8 text-center text-gray-500"><i class="fas fa-spinner animate-spin mr-2"></i>Loading...</td></tr>';
    
    // Build query parameters
    const params = new URLSearchParams();
    if (filters.status) params.append('status', filters.status);
    if (filters.month) params.append('month', filters.month);
    if (filters.search) params.append('search', filters.search);
    
    const queryString = params.toString() ? '&' + params.toString() : '';
    
    fetch(`?page=api&endpoint=invoices/list${queryString}`)
        .then(r => {
            console.log('Invoice API response status:', r.status);
            return r.json();
        })
        .then(data => {
            console.log('Invoice API data:', data);
            if (data.success && data.invoices && data.invoices.length > 0) {
                tbody.innerHTML = data.invoices.map(inv => {
                    const monthDisplay = inv.invoice_month ? new Date(inv.invoice_month + '-01').toLocaleDateString('en-US', { year: 'numeric', month: 'short' }) : 'N/A';
                    const postName = inv.post_name || 'N/A';
                    return `
                    <tr class="hover:bg-gray-50 transition">
                        <td class="px-3 py-4">
                            <input type="checkbox" class="invoice-checkbox" data-invoice-id="${inv.id}" onchange="updateBulkActionsUI()" class="rounded border-gray-300 cursor-pointer">
                        </td>
                        <td class="px-3 py-4 font-semibold text-gray-900 text-sm">${inv.invoice_number}</td>
                        <td class="px-3 py-4 text-gray-600 text-sm">${inv.owner_name || 'N/A'}</td>
                        <td class="px-3 py-4 text-gray-600 text-sm">${postName}</td>
                        <td class="px-3 py-4 text-gray-600 text-sm">${new Date(inv.invoice_date).toLocaleDateString()}</td>
                        <td class="px-3 py-4 text-gray-600 text-sm">${monthDisplay}</td>
                        <td class="px-3 py-4 text-right font-semibold text-gray-900 text-sm">${formatCurrency(inv.total_amount)}</td>
                        <td class="px-3 py-4">
                            ${getStatusBadge(inv.status)}
                        </td>
                        <td class="px-3 py-4 text-center">
                            <div class="flex justify-center gap-2">
                                <button onclick="viewInvoice(${inv.id})" class="text-blue-600 hover:text-blue-900 font-semibold transition" title="View">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button onclick="editInvoice(${inv.id})" class="text-yellow-600 hover:text-yellow-900 font-semibold transition" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="deleteInvoice(${inv.id})" class="text-red-600 hover:text-red-900 font-semibold transition" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
                }).join('');
            } else {
                console.warn('No invoices or error:', data);
                tbody.innerHTML = '<tr><td colspan="9" class="px-6 py-8 text-center text-gray-500">No invoices found</td></tr>';
            }
        })
        .catch(err => {
            console.error('Error loading invoices:', err);
            tbody.innerHTML = '<tr><td colspan="9" class="px-6 py-8 text-center text-red-600"><i class="fas fa-exclamation-circle mr-2"></i>Error loading invoices</td></tr>';
        });
}

//load invoices on page load after brief anima
setTimeout(loadInvoices, 300);


// Load generate invoices tab
function loadGenerateInvoicesTab() {
    loadPosts();
    loadBillingStats();
}

// Load posts for bulk generation
function loadPosts() {
    fetch('?page=api&endpoint=posts/list')
        .then(r => r.json())
        .then(data => {
            console.log('Posts API response:', data);
            if (data.success && data.posts) {
                const postsList = document.getElementById('postsList');
                postsList.innerHTML = data.posts.map(post => `
                    <label class="flex items-center gap-2 cursor-pointer hover:bg-gray-100 p-2 rounded transition">
                        <input type="checkbox" name="selected_posts" value="${post.id}" class="w-5 h-5 rounded border-gray-300 post-checkbox">
                        <span class="text-gray-700">${post.name} (Owner: ${post.owner_name || 'No owner'})</span>
                    </label>
                `).join('');
            } else {
                console.warn('No posts found or invalid response:', data);
                document.getElementById('postsList').innerHTML = '<p class="text-red-500">Error loading posts</p>';
            }
        })
        .catch(err => {
            console.error('Error loading posts:', err);
            document.getElementById('postsList').innerHTML = '<p class="text-red-500">Error loading posts</p>';
        });
}

// Toggle all posts checkbox
function toggleAllPosts(checkbox) {
    const allCheckboxes = document.querySelectorAll('input[name="selected_posts"]');
    allCheckboxes.forEach(cb => cb.checked = checkbox.checked);
}

// Load posts/facilities for selection
function loadPostsSelect() {
    fetch('?page=api&endpoint=posts/list')
        .then(r => r.json())
        .then(data => {
            console.log('Posts API response:', data);
            if (data.success && data.posts) {
                // Store all posts globally for filtering
                allPosts = data.posts;
                
                const postSelect = document.getElementById('invoicePostId');
                if (postSelect) {
                    const currentValue = postSelect.value;
                    // Show owner name alongside post name
                    postSelect.innerHTML = '<option value="">Select Post (Optional)</option>' + data.posts.map(post => `
                        <option value="${post.id}" data-owner-id="${post.owner_id}">${post.name} (${post.owner_name || 'No owner'})</option>
                    `).join('');
                    if (currentValue) postSelect.value = currentValue;
                }
            } else {
                console.warn('No posts found or invalid response:', data);
            }
        })
        .catch(err => console.error('Error loading posts:', err));
}

// Load billing statistics
function loadBillingStats() {
    fetch('?page=api&endpoint=invoices/stats')
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                document.getElementById('activeClientsCount').textContent = data.active_clients || 0;
                document.getElementById('expectedRevenue').textContent = formatCurrency(data.expected_revenue || 0);
                document.getElementById('unpaidCount').textContent = data.unpaid_invoices || 0;
            }
        })
        .catch(err => console.error('Error loading stats:', err));
}

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

function formatCurrency(amount) {
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'XAF'
    }).format(amount);
}

// Status badge
function getStatusBadge(status) {
    const colors = {
        'Draft': 'bg-gray-100 text-gray-800',
        'Sent': 'bg-blue-100 text-blue-800',
        'Partial': 'bg-yellow-100 text-yellow-800',
        'Paid': 'bg-green-100 text-green-800',
        'Overdue': 'bg-red-100 text-red-800',
        'Cancelled': 'bg-gray-300 text-gray-700'
    };
    return `<span class="px-3 py-1 rounded-full text-sm font-semibold ${colors[status] || ''}">${status}</span>`;
}

// Modal functions
function openCreateInvoiceModal() {
    document.getElementById('invoiceForm').reset();
    document.getElementById('invoiceId').value = '';
    document.getElementById('invoiceModalTitle').textContent = '<?php echo trans('new_invoice'); ?>';
    document.getElementById('invoiceModal').classList.remove('hidden');
    setDefaultDates();
    
    // Set default invoice month to current month
    const today = new Date();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const year = today.getFullYear();
    document.getElementById('invoiceMonth').value = `${year}-${month}`;
    
    // Clear and add one empty service row
    const servicesContainer = document.getElementById('servicesContainer');
    servicesContainer.innerHTML = '';
    addServiceRow();
    
    // Update totals display
    updateInvoiceTotals();
    
    loadOwners();
    loadPostsSelect();
}

function closeInvoiceModal() {
    document.getElementById('invoiceModal').classList.add('hidden');
}

function closeViewInvoiceModal() {
    document.getElementById('viewInvoiceModal').classList.add('hidden');
}

// View invoice
function viewInvoice(invoiceId) {
    fetch(`?page=api&endpoint=invoices/get&id=${invoiceId}`)
        .then(r => r.json())
        .then(data => {
            if (data.success && data.invoice) {
                const inv = data.invoice;
                const services = data.services || []; // Get services from API response
                const company = data.company || {};
                
                document.getElementById('viewInvoiceNumber').textContent = inv.invoice_number;
                
                const invoiceDate = new Date(inv.invoice_date).toLocaleDateString();
                const monthDisplay = inv.invoice_month ? new Date(inv.invoice_month + '-01').toLocaleDateString('en-US', { year: 'numeric', month: 'long' }) : 'N/A';
                
                // Build letterhead HTML
                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>Billing Month:</strong> ${monthDisplay}</p>
                            <p class="text-sm"><strong>Currency:</strong> ${normalizeCurrency(inv.currency)}</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">
                `;
                
                // Display services from the post
                if (services && services.length > 0) {
                    services.forEach(svc => {
                        html += `
                        <tr>
                            <td class="px-4 py-2 text-sm">${svc.name || svc.description || 'Service'}</td>
                            <td class="px-4 py-2 text-right text-sm">${svc.qty || 1}</td>
                            <td class="px-4 py-2 text-right text-sm">${formatCurrency(svc.unit_cost || 0)}</td>
                            <td class="px-4 py-2 text-right text-sm font-semibold">${formatCurrency(svc.total || (svc.qty * svc.unit_cost))}</td>
                        </tr>
                        `;
                    });
                } else {
                    // Fallback: show invoice line items
                    html += `
                        <tr>
                            <td class="px-4 py-2 text-sm">Services for ${monthDisplay}</td>
                            <td class="px-4 py-2 text-right text-sm">1</td>
                            <td class="px-4 py-2 text-right text-sm">${formatCurrency(inv.subtotal)}</td>
                            <td class="px-4 py-2 text-right text-sm font-semibold">${formatCurrency(inv.subtotal)}</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">${formatCurrency(inv.subtotal)}</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">${formatCurrency(inv.tax_amount)}</span>
                            </div>
                            <div class="flex justify-between text-lg">
                                <span class="font-bold">Total:</span>
                                <span class="font-bold text-blue-600">${formatCurrency(inv.total_amount)}</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))} ${normalizeCurrency(inv.currency)}</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');
                
                // Store current invoice ID for PDF download
                window.currentInvoiceId = inv.id;
            }
        })
        .catch(err => {
            console.error('Error:', err);
            Swal.fire('Error', 'Error loading invoice', 'error');
        });
}

// Print invoice
function printInvoice() {
    const invoiceContent = document.getElementById('invoiceDetailContent');
    if (!invoiceContent) {
        Swal.fire('Error', 'No invoice loaded', 'error');
        return;
    }

    const printWindow = window.open('', '', 'width=800,height=600');
    const htmlContent = '<!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; } .border-b { border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 10px; }</style></head><body>' + invoiceContent.innerHTML + '</body></html>';
    
    printWindow.document.write(htmlContent);
    printWindow.document.close();
    
    setTimeout(() => {
        printWindow.print();
        printWindow.onafterprint = function() { printWindow.close(); }
    }, 250);
}

// Download invoice as PDF using TCPDF
function downloadInvoicePDF() {
    // Get the invoice number from the modal title
    const invoiceTitle = document.getElementById('viewInvoiceNumber').textContent;
    const invoiceId = document.querySelector('[data-current-invoice-id]')?.getAttribute('data-current-invoice-id');
    
    if (!invoiceId) {
        // Extract invoice ID from the modal - we'll store it when viewing
        const currentInvoiceId = window.currentInvoiceId;
        if (!currentInvoiceId) {
            Swal.fire('Error', 'Invoice ID not found', 'error');
            return;
        }
        window.location.href = `?page=api&endpoint=invoices/pdf&id=${currentInvoiceId}`;
    } else {
        window.location.href = `?page=api&endpoint=invoices/pdf&id=${invoiceId}`;
    }
}

// Generate invoices
document.getElementById('generateInvoicesForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const selectedPosts = Array.from(document.querySelectorAll('input[name="selected_posts"]:checked')).map(cb => cb.value);
    
    if (selectedPosts.length === 0) {
        Swal.fire('Warning', 'Please select at least one post', 'warning');
        return;
    }
    
    const payload = {
        billing_month: formData.get('billing_month'),
        post_ids: selectedPosts,
        invoice_note: formData.get('invoice_note') || ''
    };
    
    fetch('?page=api&endpoint=invoices/generate', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(data => {
        console.log('Generate response:', data);
        if (data.success) {
            Swal.fire('Success', `Generated ${data.generated_count || 0} invoices`, 'success');
            document.getElementById('generateInvoicesForm').reset();
            setDefaultDates();
            loadGenerateInvoicesTab();
        } else {
            Swal.fire('Error', data.message || 'Error generating invoices', 'error');
        }
    })
    .catch(err => {
        console.error('Generate error:', err);
        Swal.fire('Error', 'Error generating invoices', 'error');
    });
});

// Auto-generate settings
document.getElementById('enableAutoGenerate')?.addEventListener('change', function() {
    document.getElementById('cronSettings').classList.toggle('hidden', !this.checked);
});

// Billing settings form
document.getElementById('billingSettingsForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    const payload = {
        invoice_prefix: formData.get('invoice_prefix'),
        tax_rate: parseFloat(formData.get('tax_rate')) || 0,
        due_days: parseInt(formData.get('due_days')) || 30,
        auto_send_email: formData.get('auto_send_email') ? true : false
    };
    
    fetch('?page=api&endpoint=invoices/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(data => {
        console.log('Settings response:', data);
        if (data.success) {
            Swal.fire('Success', 'Billing settings saved', 'success');
        } else {
            Swal.fire('Error', data.message || 'Error saving settings', 'error');
        }
    })
    .catch(err => {
        console.error('Settings error:', err);
        Swal.fire('Error', 'Error saving settings', 'error');
    });
});

// Cron settings form
document.getElementById('cronSettingsForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    // Determine the day to use (custom or predefined)
    let autoGenerateDay = formData.get('auto_generate_day');
    if (!autoGenerateDay || autoGenerateDay === '') {
        autoGenerateDay = formData.get('auto_generate_day_custom');
    }
    
    const payload = {
        enable_auto_generate: formData.get('enable_auto_generate') ? true : false,
        auto_generate_day: autoGenerateDay,
        auto_generate_time: formData.get('auto_generate_time')
    };
    
    fetch('?page=api&endpoint=invoices/settings', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(data => {
        console.log('Cron response:', data);
        if (data.success) {
            Swal.fire('Success', 'Auto-generation settings saved', 'success');
        } else {
            Swal.fire('Error', data.message || 'Error saving settings', 'error');
        }
    })
    .catch(err => {
        console.error('Cron error:', err);
        Swal.fire('Error', 'Error saving settings', 'error');
    });
});

// Load facility owners for the modal
function loadOwners() {
    fetch('?page=api&endpoint=users/list&role=client')
        .then(r => r.json())
        .then(data => {
            const ownerSelect = document.getElementById('invoiceOwnerId');
            if (ownerSelect && data.success && data.users) {
                const currentValue = ownerSelect.value;
                ownerSelect.innerHTML = '<option value="">Select Facility Owner</option>' + data.users.map(user => `
                    <option value="${user.id}">${user.name}</option>
                `).join('');
                if (currentValue) ownerSelect.value = currentValue;
            }
        })
        .catch(err => console.error('Error loading owners:', err));
}

// Invoice form submission
document.getElementById('invoiceForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const invoiceId = document.getElementById('invoiceId').value;
    
    // Collect services from the form
    const services = [];
    document.querySelectorAll('#servicesContainer .service-row').forEach(row => {
        const name = row.querySelector('.service-name').value;
        const qty = row.querySelector('.service-qty').value;
        const unitCost = row.querySelector('.service-unit-cost').value;
        if (name && qty && unitCost) {
            services.push({
                ref: `SVC-${services.length + 1}`,
                name: name,
                qty: parseFloat(qty),
                unit_cost: parseFloat(unitCost),
                total: parseFloat(qty) * parseFloat(unitCost)
            });
        }
    });
    
    const payload = {
        owner_id: formData.get('owner_id'),
        post_id: formData.get('post_id') || null,
        invoice_date: formData.get('invoice_date'),
        invoice_month: formData.get('invoice_month') || null,
        due_date: formData.get('due_date') || null,
        notes: formData.get('notes') || '',
        services: services.length > 0 ? services : null
    };
    
    const method = invoiceId ? 'PUT' : 'POST';
    const endpoint = invoiceId ? `invoices/update&id=${invoiceId}` : 'invoices/create';
    
    fetch(`?page=api&endpoint=${endpoint}`, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            Swal.fire('Success', invoiceId ? 'Invoice updated' : 'Invoice created', 'success');
            closeInvoiceModal();
            loadInvoices();
        } else {
            Swal.fire('Error', data.error || 'Error saving invoice', 'error');
        }
    })
    .catch(err => {
        console.error('Error:', err);
        Swal.fire('Error', 'Error saving invoice', 'error');
    });
});

// Edit invoice
function editInvoice(invoiceId) {
    fetch(`?page=api&endpoint=invoices/get&id=${invoiceId}`)
        .then(r => r.json())
        .then(data => {
            if (data.success && data.invoice) {
                const invoice = data.invoice;
                document.getElementById('invoiceId').value = invoice.id;
                document.getElementById('invoiceOwnerId').value = invoice.owner_id;
                document.getElementById('invoicePostId').value = invoice.post_id || '';
                document.getElementById('invoiceDateInput').value = invoice.invoice_date;
                document.getElementById('invoiceDueDate').value = invoice.due_date || '';
                document.getElementById('invoiceMonth').value = invoice.invoice_month || '';
                document.getElementById('invoiceModalTitle').textContent = `Edit Invoice ${invoice.invoice_number}`;
                
                // Load services
                const servicesContainer = document.getElementById('servicesContainer');
                servicesContainer.innerHTML = '';
                if (data.services && Array.isArray(data.services)) {
                    data.services.forEach(service => {
                        addServiceRow(service.name, service.qty, service.unit_cost);
                    });
                } else if (invoice.post_id) {
                    // Load from post if no services in invoice
                    loadServicesFromPost();
                } else {
                    // No services loaded
                    servicesContainer.innerHTML = '<p class="text-gray-500 text-sm">No services yet. Select a post or add manually.</p>';
                }
                
                // Calculate and display totals
                updateInvoiceTotals();
                
                document.getElementById('invoiceModal').classList.remove('hidden');
            }
        })
        .catch(err => Swal.fire('Error', 'Error loading invoice', 'error'));
}

// Delete invoice
function deleteInvoice(invoiceId) {
    Swal.fire({
        title: 'Delete Invoice?',
        text: 'This action cannot be undone',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Delete'
    }).then(result => {
        if (result.isConfirmed) {
            fetch(`?page=api&endpoint=invoices/delete&id=${invoiceId}`, {
                method: 'DELETE'
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Deleted', 'Invoice deleted successfully', 'success');
                    loadInvoices();
                } else {
                    Swal.fire('Error', data.error || 'Error deleting invoice', 'error');
                }
            })
            .catch(err => Swal.fire('Error', 'Error deleting invoice', 'error'));
        }
    });
}

// Bulk selection functions
function toggleSelectAll(checkbox) {
    const invoiceCheckboxes = document.querySelectorAll('.invoice-checkbox');
    invoiceCheckboxes.forEach(cb => cb.checked = checkbox.checked);
    updateBulkActionsUI();
}

function updateBulkActionsUI() {
    const selected = document.querySelectorAll('.invoice-checkbox:checked').length;
    const bulkContainer = document.getElementById('bulkActionsContainer');
    const selectAllCheckbox = document.getElementById('selectAllInvoices');
    
    if (selected > 0) {
        bulkContainer.classList.remove('hidden');
        document.getElementById('selectedCount').textContent = `${selected} invoice${selected !== 1 ? 's' : ''} selected`;
        
        // Update select all checkbox state
        const totalCheckboxes = document.querySelectorAll('.invoice-checkbox').length;
        selectAllCheckbox.checked = selected === totalCheckboxes;
    } else {
        bulkContainer.classList.add('hidden');
        selectAllCheckbox.checked = false;
    }
}

function clearBulkSelection() {
    document.querySelectorAll('.invoice-checkbox').forEach(cb => cb.checked = false);
    document.getElementById('selectAllInvoices').checked = false;
    document.getElementById('bulkStatusSelect').value = '';
    updateBulkActionsUI();
}

function applyBulkStatusChange() {
    const status = document.getElementById('bulkStatusSelect').value;
    if (!status) {
        Swal.fire('Warning', 'Please select a status', 'warning');
        return;
    }
    
    const selectedIds = Array.from(document.querySelectorAll('.invoice-checkbox:checked')).map(cb => cb.dataset.invoiceId);
    if (selectedIds.length === 0) {
        Swal.fire('Warning', 'No invoices selected', 'warning');
        return;
    }
    
    Swal.fire({
        title: 'Update Status?',
        text: `Change status to "${status}" for ${selectedIds.length} invoice(s)?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update'
    }).then(result => {
        if (result.isConfirmed) {
            Promise.all(selectedIds.map(id =>
                fetch(`?page=api&endpoint=invoices/update&id=${id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ status: status })
                }).then(r => r.json())
            )).then(results => {
                if (results.every(r => r.success)) {
                    Swal.fire('Success', `Updated ${selectedIds.length} invoice(s)`, 'success');
                    clearBulkSelection();
                    loadInvoices();
                } else {
                    Swal.fire('Error', 'Some updates failed', 'error');
                }
            }).catch(err => {
                console.error('Error:', err);
                Swal.fire('Error', 'Error updating invoices', 'error');
            });
        }
    });
}

function sendSelectedInvoices() {
    const selectedIds = Array.from(document.querySelectorAll('.invoice-checkbox:checked')).map(cb => cb.dataset.invoiceId);
    if (selectedIds.length === 0) {
        Swal.fire('Warning', 'No invoices selected', 'warning');
        return;
    }
    
    Swal.fire('Coming Soon', `Send functionality for ${selectedIds.length} invoice(s) will be implemented soon`, 'info');
}

// Filter invoices via AJAX
function filterInvoices() {
    const status = document.getElementById('statusFilter').value;
    const month = document.getElementById('monthFilter').value;
    const search = document.getElementById('searchInvoice').value;
    
    // Call loadInvoices with filter parameters
    loadInvoices({
        status: status,
        month: month,
        search: search
    });
}

// Initialize
window.addEventListener('load', () => {
    setDefaultDates();
    loadOwners();
    
    // Handle custom day input visibility
    const daySelect = document.getElementById('autoGenerateDaySelect');
    if (daySelect) {
        daySelect.addEventListener('change', function() {
            const customInput = document.getElementById('autoGenerateDayCustom');
            if (this.value === '') {
                customInput.classList.remove('hidden');
                customInput.required = true;
            } else {
                customInput.classList.add('hidden');
                customInput.required = false;
            }
        });
    }

    // Payment modal event listeners
    document.getElementById('payNowBtn')?.addEventListener('click', openPaymentModal);
    
    // Payment tab switching
    document.querySelectorAll('.payment-tab-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const tabName = this.getAttribute('data-payment-tab');
            
            document.querySelectorAll('.payment-tab-btn').forEach(b => {
                b.classList.remove('border-green-600', 'text-green-600');
                b.classList.add('border-transparent', 'text-gray-600');
            });
            
            this.classList.add('border-green-600', 'text-green-600');
            this.classList.remove('border-transparent', 'text-gray-600');
            
            document.querySelectorAll('.payment-tab-content').forEach(content => {
                content.classList.add('hidden');
            });
            
            document.getElementById(tabName + '-payment-tab').classList.remove('hidden');
        });
    });
    
    // Manual payment form submission
    document.getElementById('manualPaymentForm')?.addEventListener('submit', submitManualPayment);
    
    // Mobile money payment form submission
    document.getElementById('mobileMoneyPaymentForm')?.addEventListener('submit', submitMobileMoneyPayment);
    
    // Mobile money amount change to show fee
    document.getElementById('mobileMoneyAmount')?.addEventListener('input', updateMobileMoneyFee);
});

// Payment modal functions
function openPaymentModal() {
    const invoiceNumber = document.getElementById('viewInvoiceNumber').textContent;
    const invoiceTotal = document.getElementById('invoiceDetailContent')?.querySelector('[data-invoice-total]')?.textContent;
    
    if (!invoiceNumber) {
        Swal.fire('Error', 'No invoice loaded', 'error');
        return;
    }
    
    document.getElementById('paymentInvoiceNumber').textContent = invoiceNumber;
    document.getElementById('paymentInvoiceTotal').textContent = invoiceTotal || '-';
    
    // Load payment history
    loadPaymentHistory();
    
    document.getElementById('paymentModal').classList.remove('hidden');
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.add('hidden');
    document.getElementById('manualPaymentForm').reset();
    document.getElementById('mobileMoneyPaymentForm').reset();
    document.getElementById('ussdCodeDisplay').classList.add('hidden');
    document.getElementById('checkStatusBtn').classList.add('hidden');
    document.getElementById('mobileMoneySubmitBtn').classList.remove('hidden');
    document.getElementById('mobileMoneySubmitBtn').disabled = false;
    document.getElementById('mobileMoneySubmitBtn').classList.remove('bg-blue-600', 'text-white', 'animate-pulse');
    document.getElementById('mobileMoneySubmitBtn').innerHTML = '<i class="fas fa-check mr-2"></i>Request Mobile Money Payment';
    document.getElementById('ussdCode').textContent = '-';
    document.getElementById('operatorCode').textContent = '-';
    document.getElementById('totalWithFee').textContent = '-';
    window.currentPaymentId = null;
}

function closeViewInvoiceModal() {
    document.getElementById('viewInvoiceModal').classList.add('hidden');
}

function updateMobileMoneyFee() {
    const amount = parseFloat(document.getElementById('mobileMoneyAmount').value) || 0;
    const fee = amount * 0.03;
    const total = amount + fee;
    
    document.getElementById('totalWithFee').textContent = `${(total).toFixed(2)} FCFA (Fee: ${fee.toFixed(2)} FCFA)`;
}

function submitManualPayment(e) {
    e.preventDefault();
    
    const invoiceNumber = document.getElementById('viewInvoiceNumber').textContent;
    const currentInvoiceId = window.currentInvoiceId;
    
    if (!currentInvoiceId) {
        Swal.fire('Error', 'Invoice ID not found', 'error');
        return;
    }
    
    const amount = parseFloat(document.getElementById('manualPaymentAmount').value);
    const method = document.getElementById('manualPaymentMethod').value;
    const description = document.getElementById('manualPaymentDescription').value;
    
    if (!amount || !method) {
        Swal.fire('Error', 'Please fill all required fields', 'error');
        return;
    }
    
    fetch('?page=api&endpoint=payments/record', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            invoice_id: currentInvoiceId,
            amount: amount,
            payment_method: method,
            description: description
        })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            Swal.fire('Success', 'Payment recorded successfully', 'success');
            document.getElementById('manualPaymentForm').reset();
            loadPaymentHistory();
            // Reload invoice to update status
            loadInvoices();
        } else {
            Swal.fire('Error', data.message || 'Error recording payment', 'error');
        }
    })
    .catch(err => {
        console.error('Error:', err);
        Swal.fire('Error', 'Error recording payment', 'error');
    });
}

function submitMobileMoneyPayment(e) {
    e.preventDefault();
    
    const invoiceNumber = document.getElementById('viewInvoiceNumber').textContent;
    const currentInvoiceId = window.currentInvoiceId;
    
    if (!currentInvoiceId) {
        Swal.fire('Error', 'Invoice ID not found', 'error');
        return;
    }
    
    const amount = parseFloat(document.getElementById('mobileMoneyAmount').value);
    const phone = document.getElementById('mobileMoneyPhone').value;
    
    if (!amount || !phone) {
        Swal.fire('Error', 'Please fill all required fields', 'error');
        return;
    }
    
    // Show loading state
    document.getElementById('mobileMoneySubmitBtn').disabled = true;
    document.getElementById('mobileMoneySubmitBtn').innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Requesting payment...';
    
    fetch('?page=api&endpoint=payments/request-mobile-money', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            invoice_id: currentInvoiceId,
            phone_number: phone,
            amount: amount
        })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            Swal.fire('Success', 'Payment request sent to ' + phone, 'success');
            
            // Show USSD code
            document.getElementById('ussdCode').textContent = data.ussd_code || 'N/A';
            document.getElementById('operatorCode').textContent = (data.operator || 'unknown').toUpperCase();
            document.getElementById('ussdCodeDisplay').classList.remove('hidden');
            
            // Hide submit button and show status check button
            document.getElementById('mobileMoneySubmitBtn').classList.add('hidden');
            document.getElementById('checkStatusBtn').classList.remove('hidden');
            
            // Store payment ID and start countdown
            window.currentPaymentId = data.payment_id;
            startPaymentCountdown(30);
        } else {
            document.getElementById('mobileMoneySubmitBtn').disabled = false;
            document.getElementById('mobileMoneySubmitBtn').innerHTML = '<i class="fas fa-check mr-2"></i>Request Mobile Money Payment';
            Swal.fire('Error', data.message || 'Error requesting payment', 'error');
        }
    })
    .catch(err => {
        document.getElementById('mobileMoneySubmitBtn').disabled = false;
        document.getElementById('mobileMoneySubmitBtn').innerHTML = '<i class="fas fa-check mr-2"></i>Request Mobile Money Payment';
        console.error('Error:', err);
        Swal.fire('Error', 'Error requesting payment', 'error');
    });
}

function startPaymentCountdown(seconds) {
    const btn = document.getElementById('checkStatusBtn');
    let remaining = seconds;
    
    // Show countdown timer
    btn.classList.add('bg-blue-600', 'text-white', 'animate-pulse');
    btn.innerHTML = `<i class="fas fa-clock mr-2"></i>Auto-checking in ${remaining}s...`;
    
    const countdownInterval = setInterval(() => {
        remaining--;
        btn.innerHTML = `<i class="fas fa-clock mr-2"></i>Auto-checking in ${remaining}s...`;
        
        if (remaining <= 0) {
            clearInterval(countdownInterval);
            btn.classList.remove('animate-pulse');
            btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Verifying payment...';
            checkPaymentStatus();
        }
    }, 1000);
}

function checkPaymentStatus() {
    const paymentId = window.currentPaymentId;
    if (!paymentId) return;
    
    const btn = document.getElementById('checkStatusBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Checking...';
    
    fetch('?page=api&endpoint=payments/check-mobile-money-status', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            payment_id: paymentId
        })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            if (data.status === 'SUCCESS' || data.status === 'COMPLETED' || data.status === 'Confirmed') {
                btn.classList.remove('animate-pulse', 'bg-blue-600', 'text-white');
                btn.innerHTML = '<i class="fas fa-check-circle text-green-600 mr-2"></i>Payment Confirmed!';
                btn.disabled = false;
                btn.classList.add('hidden');
                
                Swal.fire('Success', 'Payment confirmed!', 'success');
                loadPaymentHistory();
                loadInvoices();
            } else if (data.status === 'PENDING') {
                // Still pending, retry after 5 seconds
                btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Still processing...';
                setTimeout(() => checkPaymentStatus(), 5000);
            } else if (data.status === 'FAILED' || data.status === 'CANCELLED') {
                btn.classList.remove('animate-pulse', 'bg-blue-600', 'text-white');
                btn.innerHTML = '<i class="fas fa-times-circle text-red-600 mr-2"></i>Payment Failed';
                btn.disabled = false;
                Swal.fire('Failed', 'Payment failed or was cancelled', 'error');
            }
        } else {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-sync mr-2"></i>Check Payment Status';
            Swal.fire('Error', data.message || 'Error checking status', 'error');
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-sync mr-2"></i>Check Payment Status';
        console.error('Error:', err);
        Swal.fire('Error', 'Error checking status', 'error');
    });
}

function loadPaymentHistory() {
    const currentInvoiceId = window.currentInvoiceId;
    if (!currentInvoiceId) return;
    
    fetch(`?page=api&endpoint=payments/list&invoice_id=${currentInvoiceId}`)
        .then(r => r.json())
        .then(data => {
            if (data.success && data.payments && data.payments.length > 0) {
                const html = data.payments.map(payment => `
                    <div class="p-3 bg-gray-50 rounded border border-gray-200">
                        <div class="flex justify-between items-start">
                            <div>
                                <p class="text-sm font-semibold text-gray-800">${payment.payment_method}</p>
                                <p class="text-xs text-gray-600">${new Date(payment.payment_date).toLocaleDateString()} ${payment.payment_date}</p>
                            </div>
                            <div class="text-right">
                                <p class="text-sm font-bold text-green-600">${payment.amount.toFixed(2)} FCFA</p>
                                <span class="inline-block px-2 py-1 text-xs font-semibold rounded ${payment.status === 'Confirmed' ? 'bg-green-100 text-green-800' : payment.status === 'Pending' ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100 text-gray-800'}">
                                    ${payment.status}
                                </span>
                            </div>
                        </div>
                        ${payment.description ? `<p class="text-xs text-gray-600 mt-2">${payment.description}</p>` : ''}
                        ${payment.campay_reference ? `<p class="text-xs text-gray-600">Ref: ${payment.campay_reference}</p>` : ''}
                    </div>
                `).join('');
                
                document.getElementById('paymentHistoryContainer').innerHTML = html;
            } else {
                document.getElementById('paymentHistoryContainer').innerHTML = '<p class="text-sm text-gray-600">No payments recorded yet</p>';
            }
        })
        .catch(err => {
            console.error('Error loading payment history:', err);
            document.getElementById('paymentHistoryContainer').innerHTML = '<p class="text-sm text-red-600">Error loading payment history</p>';
        });
}

</script>

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