$(document).ready(function() {
    // Initial load on page ready
    loadDashboardData();

    // Live search as user types (with debounce effect)
    let searchTimer;
    $('#flt_search').on('keyup', function() {
        clearTimeout(searchTimer);
        searchTimer = setTimeout(function() {
            loadDashboardData();
        }, 300);
    });

    // Clear search button
    $('#btnClearSearch').on('click', function() {
        $('#flt_search').val('');
        loadDashboardData();
    });

    // Refresh button click
    $('#btnRefresh').on('click', function() {
        $('#flt_search').val('');
        loadDashboardData();
    });
});

window.loadDashboardData = function() {
    const tbody = $('#billingTbody');
    
    // Show spinners in KPI cards and table
    $('#kpi_pending_count, #kpi_expected_cash, #kpi_collected_cash').html('<i class="fa fa-spinner fa-spin fs-4"></i>');
    tbody.html('<tr><td colspan="6" class="text-center py-5 text-primary"><i class="fa fa-spinner fa-spin fa-3x mb-3"></i><br>Fetching live database records...</td></tr>');

    const formData = new FormData();
    formData.append('action', 'fetch_dashboard');
    formData.append('start_date', $('#flt_start').val());
    formData.append('end_date', $('#flt_end').val());
    formData.append('search', $('#flt_search').val());

    fetch('/rimax/application/dripend/includes/account/api_patient_billing.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'error') {
            tbody.html(`<tr><td colspan="6" class="text-center py-4 text-danger"><i class="fa-solid fa-triangle-exclamation mb-2 fa-2x"></i><br>${data.message}</td></tr>`);
            return;
        }

        const curr = data.currency || 'GHS';
        const kpis = data.kpis;

        // Populate KPIs with live database metrics
        $('#kpi_pending_count').text(kpis.pending_count);
        $('#kpi_expected_cash').html(`<span class="fs-6 opacity-50">${curr}</span> ` + formatMoney(kpis.expected_cash));
        $('#kpi_collected_cash').html(`<span class="fs-6 opacity-50">${curr}</span> ` + formatMoney(kpis.collected_cash));

        tbody.empty();
        
        if (data.table_data.length === 0) {
            tbody.html('<tr><td colspan="6" class="text-center py-5 text-muted"><i class="fa-solid fa-folder-open fa-3x mb-3 opacity-25"></i><br>No billing records found matching your search.</td></tr>');
            return;
        }

        // Render table rows dynamically
        data.table_data.forEach(row => {
            let badgeClass = 'badge bg-success bg-opacity-10 text-success border border-success';
            if (row.status === 'UNPAID') badgeClass = 'badge bg-danger bg-opacity-10 text-danger border border-danger';
            else if (row.status === 'PARTIAL') badgeClass = 'badge bg-warning bg-opacity-10 text-warning border border-warning';

            let patDetails = row.patient_no !== 'WALK-IN' 
                ? `<div class="fw-bold text-dark">${row.patient_name}</div><span class="small text-primary">#${row.patient_no}</span>` 
                : `<div class="fw-bold text-dark">Walk-In Client</div><span class="small text-muted">No ID Registered</span>`;

            // Action button: Make Payment if balance due > 0, else View Receipt
            let actionBtn = `<a href="processPayment.php?invoice_id=${row.invoice_no}" class="btn btn-sm btn-success fw-bold shadow-sm px-3"><i class="fa-solid fa-cash-register me-1"></i> Make Payment</a>`;
            if (row.status === 'PAID') {
                actionBtn = `<a href="print_payment.php?invoice_id=${row.invoice_no}" target="_blank" class="btn btn-sm btn-dark fw-bold shadow-sm px-3"><i class="fa-solid fa-print me-1"></i> Receipt</a>`;
            }

            let html = `
                <tr>
                    <td class="ps-4">
                        <div class="fw-bold text-dark">${row.invoice_no}</div>
                        <div class="small text-muted">${row.date_formatted}</div>
                    </td>
                    <td>${patDetails}</td>
                    <td><span class="${badgeClass} px-2 py-1">${row.status}</span></td>
                    <td class="text-end fw-bold text-dark">${curr} ${row.total_amount_fmt}</td>
                    <td class="text-end fw-bold ${row.balance_due > 0 ? 'text-danger' : 'text-success'}">${curr} ${row.balance_due_fmt}</td>
                    <td class="text-center pe-4">${actionBtn}</td>
                </tr>
            `;
            tbody.append(html);
        });

    })
    .catch(error => {
        console.error('AJAX Error:', error);
        tbody.html('<tr><td colspan="6" class="text-center py-4 text-danger"><i class="fa-solid fa-wifi mb-2 fa-2x"></i><br>Network or Database Connection Error.</td></tr>');
    });
}

function formatMoney(amount) {
    return parseFloat(amount || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}