/**
 * RiMax Universal Dynamic Receipt Renderer
 * Fetches database records and injects them into the fluid print DOM.
 */

$(document).ready(function() {
    
    if (!TARGET_INVOICE_ID) {
        alert("Fatal Error: Missing Invoice Reference.");
        return;
    }

    fetchReceiptData(TARGET_INVOICE_ID);

});

async function fetchReceiptData(invoiceNo) {
    try {
        const response = await fetch(`/rimax/application/dripend/includes/account/api_print_receipt.php?invoice_no=${encodeURIComponent(invoiceNo)}`);
        const json = await response.json();

        if (json.status === 'error') {
            document.getElementById('loader_overlay').innerHTML = `<h3 style="color:red;">Error</h3><p>${json.message}</p>`;
            return;
        }

        const fac = json.facility;
        const pat = json.patient;
        const inv = json.invoice;
        const sys = json.system;
        const payments = json.payments;
        const items = json.items;

        // 1. Inject Facility (Hospital) Data
        $('#ui_hosp_name').text(fac.hospital_name || 'Hospital Name Not Configured');
        $('#ui_hosp_address').text((fac.address || '') + (fac.postal_address ? ' | ' + fac.postal_address : ''));
        $('#ui_hosp_email').text(fac.primary_email || 'N/A');
        $('#ui_hosp_phone').text(fac.primary_phone || (fac.secondary_phone || 'N/A'));
        $('#ui_footer_hosp').text(fac.hospital_name || 'our facility');

        if (fac.primary_hex) {
            document.documentElement.style.setProperty('--theme-color', fac.primary_hex);
        }

        // 2. Inject Patient & Invoice Meta Data
        $('#ui_pat_name').text(pat.name);
        $('#ui_pat_id').text(pat.patient_no);
        $('#ui_inv_no').text(inv.invoice_no);
        $('#ui_inv_date').text(inv.date_fmt);
        $('#ui_inv_dept').text(inv.department_origin || 'General');

        // 3. Render the Specific Line Items Paid For
        const itemBody = document.getElementById('ui_items_tbody');
        itemBody.innerHTML = '';
        
        items.forEach(item => {
            let uPrice = parseFloat(item.unit_price).toFixed(2);
            let tPrice = parseFloat(item.total_price).toFixed(2);
            
            // The class 'hide-thermal' removes the columns on 58mm/80mm printers to prevent squishing
            itemBody.insertAdjacentHTML('beforeend', `
                <tr>
                    <td><strong>${item.item_name}</strong></td>
                    <td class="text-center hide-thermal">${item.qty}</td>
                    <td class="text-right hide-thermal">${uPrice}</td>
                    <td class="text-right">${tPrice}</td>
                </tr>
            `);
        });

        // 4. Render Payments Ledger
        if (payments.length > 0) {
            $('#payment_history_section').show();
            const payBody = document.getElementById('ui_payments_tbody');
            payBody.innerHTML = '';
            
            // Set the "Served By" to the cashier who processed the latest payment
            $('#ui_served_by').text(payments[payments.length - 1].cashier);

            payments.forEach(p => {
                let ref = p.transaction_ref ? ` (Ref: ${p.transaction_ref})` : '';
                payBody.insertAdjacentHTML('beforeend', `
                    <tr>
                        <td width="40%">${p.date_fmt}</td>
                        <td width="30%">${p.payment_method}${ref}</td>
                        <td width="30%" class="text-right">${sys.currency} ${parseFloat(p.amount_paid).toFixed(2)}</td>
                    </tr>
                `);
            });
        }

        // 5. Financial Totals
        $('#ui_tot_billed').text(`${sys.currency} ${parseFloat(inv.total_amount).toFixed(2)}`);
        $('#ui_tot_paid').text(`${sys.currency} ${parseFloat(inv.total_amount - inv.balance_due).toFixed(2)}`);
        
        let bal = parseFloat(inv.balance_due);
        $('#ui_tot_bal').text(`${sys.currency} ${bal.toFixed(2)}`);
        
        if (bal <= 0) {
            $('#ui_tot_bal').parent().css('color', '#10b981'); // Make green if fully paid
        }

        // 6. Hide Loader, Reveal Receipt
        $('#loader_overlay').fadeOut(200);

        // Auto-Trigger Print Menu (Slight delay ensures CSS mapping is complete)
        setTimeout(() => {
            window.print();
        }, 800);

    } catch (error) {
        console.error("API Fetch Error:", error);
        document.getElementById('loader_overlay').innerHTML = `<h3 style="color:red;">Connection Error</h3><p>Failed to fetch receipt data.</p>`;
    }
}