/**
 * RiMax Enterprise Clinical Dispensing Engine
 * 3-Tier Workflow: Unbilled -> Billed -> Dispensed
 * Real-Time DOM Reactivity.
 */

let systemLocations = [];
let systemDrugs = [];
let systemFrequencies = [];
let patientPrescriptions = [];
let currentTab = 'unbilled'; 
let activeFinancials = { strict_prepay: 0, unpaid_balance: 0, patient_type: '', dispense_locked: false };

const API_URL = '/rimax/application/dripend/includes/dispensary/processDrugDispense.php';

$(document).ready(function() {
    if ($('.select2-modal').length) {
        $('.select2-modal').select2({ dropdownParent: $('#addRxModal'), theme: 'bootstrap-5' });
    }

    if ($('.select2-search').length) {
        $('.select2-search').select2({
            placeholder: 'Search patient by Name or ID...',
            ajax: {
                url: API_URL, type: 'GET', dataType: 'json', delay: 250,
                data: function (params) { return { action: 'search_patient', term: params.term }; },
                processResults: function (data) { return { results: data.results }; }
            }
        }).on('select2:select', function (e) {
            window.location.href = 'drugDispense.php?visit_id=' + e.params.data.id;
        });
    }

    initEngine();
});

async function initEngine() {
    try {
        const fData = new FormData(); fData.append('action', 'fetch_dependencies');
        const res = await fetch(API_URL, { method: 'POST', body: fData });
        const json = await res.json();
        
        systemLocations = json.locations || [];
        systemDrugs = json.drugs || [];
        systemFrequencies = json.frequencies || [];

        const locSelect = document.getElementById('active_dispensary');
        if (locSelect) {
            locSelect.innerHTML = '';
            systemLocations.forEach(loc => {
                let sel = (loc.location_name.includes('Cash & Carry') || loc.location_name.includes('Main')) ? 'selected' : '';
                locSelect.insertAdjacentHTML('beforeend', `<option value="${loc.id}" ${sel}>${loc.location_name}</option>`);
            });
            locSelect.addEventListener('change', loadPrescriptions);
        }

        const filterLoc = document.getElementById('dispensary_filter');
        if (filterLoc) {
            filterLoc.innerHTML = '<option value="ALL">All Dispensaries</option>';
            systemLocations.forEach(loc => { filterLoc.insertAdjacentHTML('beforeend', `<option value="${loc.id}">${loc.location_name}</option>`); });
        }

        const drugSelect = document.getElementById('add_rx_drug');
        if (drugSelect) {
            drugSelect.innerHTML = '<option value="">-- Select Medication --</option>';
            systemDrugs.forEach(d => { drugSelect.insertAdjacentHTML('beforeend', `<option value="${d.id}" data-form="${d.form}" data-str="${d.str}">${d.name} ${d.str} ${d.form}</option>`); });
            
            // CRITICAL FIX: Ensure inputs actually exist before trying to update them to prevent JS crash
            $('#add_rx_drug').on('change', function() {
                let opt = $(this).find(':selected');
                let formEl = document.getElementById('add_rx_formulation');
                let strEl = document.getElementById('add_rx_base_str');
                if (formEl) formEl.value = opt.data('form') || '';
                if (strEl) strEl.value = opt.data('str') || '';
            });
        }

        let fOptions = '<option value="">-- Frequency --</option>';
        systemFrequencies.forEach(f => { fOptions += `<option value="${f.freq_code}">${f.description} (${f.freq_code})</option>`; });
        if (document.getElementById('add_rx_freq')) document.getElementById('add_rx_freq').innerHTML = fOptions;
        if (document.getElementById('edit_rx_freq')) document.getElementById('edit_rx_freq').innerHTML = fOptions;

        if (typeof TARGET_VISIT_ID !== 'undefined' && TARGET_VISIT_ID > 0) {
            loadPrescriptions();
        } else if (document.getElementById('tblPendingRx')) {
            applyFilters(); 
        }

    } catch(e) { 
        console.error("Engine Init Failed: ", e);
    }
}

window.toggleQueueView = function(viewType) {
    if(viewType === 'list') {
        document.getElementById('viewContainer_list').classList.remove('d-none');
        document.getElementById('viewContainer_tile').classList.add('d-none');
        document.getElementById('btnListView').classList.add('active');
        document.getElementById('btnListView').classList.replace('btn-outline-primary', 'btn-primary');
        document.getElementById('btnTileView').classList.remove('active');
        document.getElementById('btnTileView').classList.replace('btn-primary', 'btn-outline-primary');
    } else {
        document.getElementById('viewContainer_list').classList.add('d-none');
        document.getElementById('viewContainer_tile').classList.remove('d-none');
        document.getElementById('btnTileView').classList.add('active');
        document.getElementById('btnTileView').classList.replace('btn-outline-primary', 'btn-primary');
        document.getElementById('btnListView').classList.remove('active');
        document.getElementById('btnListView').classList.replace('btn-primary', 'btn-outline-primary');
    }
};

window.applyFilters = async function() {
    const tbody = document.querySelector('#tblPendingRx tbody');
    const tileContainer = document.getElementById('viewContainer_tile');
    if (!tbody) return;
    
    tbody.innerHTML = '<tr><td colspan="6" class="text-center py-5"><i class="fa fa-spinner fa-spin fa-2x text-primary"></i></td></tr>';
    tileContainer.innerHTML = '<div class="text-center py-5"><i class="fa fa-spinner fa-spin fa-2x text-primary"></i></div>';
    
    let fd = new FormData();
    fd.append('action', 'fetch_pending_queue');
    fd.append('location_id', document.getElementById('dispensary_filter').value);
    fd.append('start_date', document.getElementById('flt_start').value);
    fd.append('end_date', document.getElementById('flt_end').value);
    if(document.getElementById('flt_insurance')) fd.append('insurance', document.getElementById('flt_insurance').value);
    if(document.getElementById('flt_type')) fd.append('patient_type', document.getElementById('flt_type').value);

    try {
        const res = await fetch(API_URL, { method: 'POST', body: fd });
        const json = await res.json();
        
        if (json.data && json.data.length > 0) {
            let listHtml = ''; let tileHtml = '';
            json.data.forEach((row, i) => {
                let badgeIns = row.insurance === 'Cash' ? 'bg-success' : 'bg-primary';
                listHtml += `<tr>
                    <td class="fw-bold text-muted">${i+1}</td>
                    <td>${row.req_time_fmt}</td>
                    <td><span class="badge bg-light text-secondary border">${row.origin}</span></td>
                    <td><div class="fw-bold text-dark">${row.patient_name}</div><div class="small text-muted">${row.patient_no} | <span class="text-success fw-bold">${row.insurance}</span></div></td>
                    <td><span class="badge bg-dark rounded-pill px-3">${row.total_drugs} Items</span></td>
                    <td class="text-end"><a href="drugDispense.php?visit_id=${row.visit_id}" class="btn btn-sm btn-primary fw-bold px-3 shadow-sm">Open Desk <i class="fa-solid fa-arrow-right ms-1"></i></a></td>
                </tr>`;

                tileHtml += `<div class="col-md-4"><div class="rx-tile">
                    <div class="d-flex justify-content-between mb-2">
                        <span class="badge bg-light text-secondary border">${row.origin}</span>
                        <span class="badge ${badgeIns}">${row.insurance}</span>
                    </div>
                    <h5 class="fw-bold text-dark mb-1">${row.patient_name}</h5>
                    <div class="small text-muted mb-3"><i class="fa-solid fa-id-card me-1"></i> ${row.patient_no}</div>
                    <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
                        <span class="fw-bold text-dark"><i class="fa-solid fa-pills text-warning"></i> ${row.total_drugs} Items Pending</span>
                        <a href="drugDispense.php?visit_id=${row.visit_id}" class="btn btn-sm btn-outline-primary fw-bold px-3">Open</a>
                    </div>
                </div></div>`;
            });
            tbody.innerHTML = listHtml;
            tileContainer.innerHTML = tileHtml;
        } else {
            let emptyMsg = '<td colspan="6" class="text-center py-5 text-muted"><i class="fa-solid fa-check-circle fa-3x mb-3 opacity-25"></i><br>No pending prescriptions found.</td>';
            tbody.innerHTML = `<tr>${emptyMsg}</tr>`;
            tileContainer.innerHTML = `<div class="col-12 text-center py-5 text-muted">${emptyMsg}</div>`;
        }
    } catch(e) {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-danger"><i class="fa-solid fa-triangle-exclamation"></i> Sync Failed.</td></tr>';
    }
}

window.switchTab = function(tabName) {
    currentTab = tabName;
    loadPrescriptions();
}

window.loadPrescriptions = async function() {
    if (typeof TARGET_VISIT_ID === 'undefined' || TARGET_VISIT_ID <= 0) return;
    const locId = document.getElementById('active_dispensary')?.value;
    const container = document.getElementById('rx_container');
    const footer = document.getElementById('action_footer');

    if(!container) return;

    container.innerHTML = '<div class="text-center py-5 mt-5"><i class="fa fa-spinner fa-spin fa-3x text-primary mb-3"></i><h5 class="fw-bold text-dark mt-3">Fetching Live Records...</h5></div>';
    if(footer) footer.style.display = 'none';

    try {
        const fd = new FormData();
        fd.append('action', 'fetch_patient_prescriptions');
        fd.append('visit_id', TARGET_VISIT_ID);
        fd.append('location_id', locId);
        fd.append('tab', currentTab);

        const res = await fetch(API_URL, { method: 'POST', body: fd });
        const json = await res.json();
        patientPrescriptions = json.prescriptions || [];
        activeFinancials = json.financials || {};
        renderAccordion(container, footer);
    } catch(e) {
        container.innerHTML = `<div class="alert alert-danger mx-3 mt-3 shadow-sm border-0">Engine failure. Cannot parse DB response.</div>`;
    }
};

function renderAccordion(container, footer) {
    if (patientPrescriptions.length === 0) {
        container.innerHTML = `<div class="text-center py-5 mt-5 text-muted"><i class="fa-solid fa-folder-open fa-4x mb-3 opacity-25"></i><h5 class="fw-bold text-dark">No records found</h5></div>`;
        return;
    }

    let prepayBanner = '';
    if (currentTab === 'dispense' && activeFinancials.dispense_locked) {
        prepayBanner = `<div class="prepay-lock-banner"><i class="fa-solid fa-lock fa-2x"></i><div><span class="d-block text-uppercase" style="font-size:12px;">Financial Rule Enforced (Out-Patient)</span><span style="font-size:15px;">Strict Pre-Pay Active: Patient owes GHS ${activeFinancials.unpaid_balance.toFixed(2)}. Dispensing is locked until cleared by Cashier.</span></div></div>`;
    }

    let html = prepayBanner + `<div class="accordion" id="rxAccordion">`;
    let subtotal = 0; let itemsFound = 0;

    patientPrescriptions.forEach((rx) => {
        let badgeClass = 'bg-secondary';
        let statusText = rx.status;
        
        if (rx.status === 'Pending Pharmacy') { badgeClass = 'bg-warning text-dark'; statusText = 'Unbilled (Review)'; itemsFound++; }
        else if (rx.status === 'Billed') { badgeClass = 'bg-info text-dark'; statusText = 'Pending Dispense'; itemsFound++; }
        else if (rx.status === 'Dispensed') { badgeClass = 'bg-success'; statusText = 'Issued & Deducted'; }
        else if (rx.status === 'Returned') { badgeClass = 'bg-dark'; statusText = 'Returned to Stock'; }
        
        let stockWarning = '';
        if (currentTab !== 'issued' && !rx.can_dispense) {
            stockWarning = `<span class="badge bg-danger ms-2"><i class="fa-solid fa-arrow-trend-down"></i> Low Stock (${rx.stock_available})</span>`;
        }

        let showCheckbox = (currentTab === 'unbilled' || currentTab === 'dispense');
        let chkHtml = showCheckbox ? `<input type="checkbox" class="custom-checkbox rx-select" value="${rx.rx_id}" onclick="event.stopPropagation();" onchange="calculateFooter()" checked>` : '';
        
        subtotal += parseFloat(rx.total_price);

        html += `
        <div class="accordion-item shadow-sm">
            <h2 class="accordion-header" id="head_${rx.rx_id}">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#col_${rx.rx_id}">
                    <div class="d-flex w-100 justify-content-between align-items-center me-3">
                        <div class="d-flex align-items-center">
                            ${chkHtml}
                            <div>
                                <h6 class="m-0 fw-bold text-dark">${rx.drug_name} ${rx.strength}</h6>
                                <div class="mt-1 d-flex align-items-center gap-2">
                                    <span class="rx-sig-badge">${rx.formulation}</span>
                                    ${stockWarning}
                                </div>
                            </div>
                        </div>
                        <div class="text-end">
                            <span class="badge ${badgeClass} mb-1 px-3 py-2 rounded-pill shadow-sm border border-white border-2">${statusText}</span>
                            <div class="text-dark fw-bold" style="font-size:15px;">GHS ${parseFloat(rx.total_price).toFixed(2)}</div>
                        </div>
                    </div>
                </button>
            </h2>
            <div id="col_${rx.rx_id}" class="accordion-collapse collapse" data-bs-parent="#rxAccordion">
                <div class="accordion-body">
                    <div class="row">
                        <div class="col-md-7">
                            <div class="bg-light p-3 rounded border mb-3">
                                <div class="fw-bold text-dark" style="font-size:16px;">Take ${rx.dose} ${rx.formulation}(s) ${rx.frequency} for ${rx.duration_days} Days <span class="ms-3 text-primary"><i class="fa-solid fa-pills"></i> Qty: ${rx.qty_prescribed}</span></div>
                                <div class="mt-2 small text-muted"><i class="fa-solid fa-clock"></i> Prescribed: ${rx.req_time_fmt}</div>
                            </div>
                            <label class="small fw-bold text-dark mb-1">Pharmacist Notes</label>
                            <div class="input-group">
                                <input type="text" class="form-control border-secondary bg-white" id="note_${rx.rx_id}" value="${rx.remarks || ''}" placeholder="Enter clinical notes...">
                                <button type="button" class="btn btn-dark fw-bold px-3" onclick="saveNote(${rx.rx_id}, this, event)"><i class="fa-solid fa-save"></i> Save Note</button>
                            </div>
                        </div>
                        <div class="col-md-5 d-flex flex-column justify-content-center align-items-end border-start ps-4">
                            <div class="text-end mb-3 w-100">
                                <span class="d-block small text-muted fw-bold text-uppercase mb-1">Unit Pricing</span>
                                <h4 class="m-0 fw-bold text-primary">GHS ${parseFloat(rx.unit_price).toFixed(2)}</h4>
                            </div>
                            <div class="d-flex gap-2 w-100 justify-content-end">
                                ${currentTab !== 'issued' ? `
                                    <button type="button" class="btn btn-sm btn-outline-danger fw-bold flex-grow-1" onclick="rejectItem(${rx.rx_id})"><i class="fa-solid fa-times"></i> Reject</button>
                                    <button type="button" class="btn btn-sm btn-outline-primary fw-bold flex-grow-1" onclick="openEditModal(${rx.rx_id})"><i class="fa-solid fa-pen"></i> Modify</button>
                                ` : `
                                    ${rx.status === 'Dispensed' ? `<button type="button" class="btn btn-sm btn-warning fw-bold flex-grow-1" onclick="returnDrug(${rx.rx_id})"><i class="fa-solid fa-rotate-left"></i> Return to Stock</button>` : '<button type="button" class="btn btn-sm btn-light border fw-bold flex-grow-1 text-muted" disabled><i class="fa-solid fa-check-double"></i> Item Fully Returned</button>'}
                                `}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>`;
    });
    
    html += `</div>`;
    container.innerHTML = html;

    if (itemsFound > 0 && footer && currentTab !== 'issued') {
        let btnText = currentTab === 'unbilled' ? "Save & Route to Cashier" : "Dispense Selected & Deduct Stock";
        let btnClass = currentTab === 'unbilled' ? "btn-primary" : "btn-success";
        let btnIcon = currentTab === 'unbilled' ? "fa-file-invoice-dollar" : "fa-hand-holding-medical";

        footer.innerHTML = `
        <div class="d-flex justify-content-between align-items-center">
            <div><span class="d-block text-muted small fw-bold text-uppercase">Total Selected Value</span><h3 class="m-0 fw-bold text-dark" id="disp_grand_total">GHS ${subtotal.toFixed(2)}</h3></div>
            <button class="btn ${btnClass} px-5 py-3 shadow-sm fw-bold fs-5" id="btnProcessBulk" onclick="processSelected()" ${activeFinancials.dispense_locked && currentTab === 'dispense' ? 'disabled' : ''}>
                <i class="fa-solid ${btnIcon} me-2"></i> ${btnText}
            </button>
        </div>`;
        footer.style.display = 'block';
        calculateFooter();
    }
}

window.calculateFooter = function() {
    if (currentTab === 'issued') return;
    let total = 0; let checkedCount = 0;

    document.querySelectorAll('.rx-select:checked').forEach(chk => {
        let rx = patientPrescriptions.find(p => p.rx_id == chk.value);
        if (rx) { total += parseFloat(rx.total_price); checkedCount++; }
    });

    const gt = document.getElementById('disp_grand_total');
    if (gt) gt.innerText = "GHS " + total.toFixed(2);

    const btn = document.getElementById('btnProcessBulk');
    if (btn) {
        if (checkedCount === 0) {
            btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-ban me-2"></i> Select Items'; btn.className = 'btn btn-secondary px-5 py-3 shadow-sm fw-bold fs-5';
        } else if (currentTab === 'unbilled') {
            btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-file-invoice-dollar me-2"></i> Save & Route to Cashier'; btn.className = 'btn btn-primary px-5 py-3 shadow-sm fw-bold fs-5';
        } else if (currentTab === 'dispense') {
            if (activeFinancials.dispense_locked) {
                btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-lock me-2"></i> Locked: Unpaid Balance'; btn.className = 'btn btn-secondary px-5 py-3 shadow-sm fw-bold fs-5';
            } else {
                btn.disabled = false; btn.innerHTML = '<i class="fa-solid fa-hand-holding-medical me-2"></i> Dispense & Deduct Stock'; btn.className = 'btn btn-success px-5 py-3 shadow-sm fw-bold fs-5';
            }
        }
    }
}

window.processSelected = async function() {
    const selected = Array.from(document.querySelectorAll('.rx-select:checked')).map(el => el.value);
    if(selected.length === 0) return;

    let payload = new FormData();
    payload.append('visit_id', TARGET_VISIT_ID);
    payload.append('location_id', document.getElementById('active_dispensary').value);

    selected.forEach(id => {
        let rx = patientPrescriptions.find(p => p.rx_id == id);
        payload.append('rx_id[]', id);
        payload.append(`dispense_qty[${id}]`, rx.qty_prescribed);
        payload.append(`unit_price[${id}]`, rx.unit_price);
        payload.append(`service_id[${id}]`, rx.service_id);
    });

    payload.append('action', (currentTab === 'unbilled') ? 'bill_prescriptions' : 'process_dispense');

    const btn = document.getElementById('btnProcessBulk');
    btn.disabled = true; btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';

    try {
        const res = await fetch(API_URL, { method: 'POST', body: payload });
        const json = await res.json();
        if(json.status === 'success') {
            if (currentTab === 'unbilled') currentTab = 'dispense';
            else if (currentTab === 'dispense') currentTab = 'issued';
            $('.nav-tabs .nav-link').removeClass('active');
            document.getElementById('tab-' + currentTab).classList.add('active');
            loadPrescriptions();
        } else throw new Error(json.message);
    } catch(e) {
        alert("Error: " + e.message); calculateFooter();
    }
}

window.returnDrug = async function(rx_id) {
    if(!confirm("Are you sure you want to RETURN this medication to stock? This will reverse the dispensing action.")) return;
    let fd = new FormData(); fd.append('action', 'return_drug'); fd.append('rx_id', rx_id); fd.append('location_id', document.getElementById('active_dispensary').value);
    try {
        const res = await fetch(API_URL, { method: 'POST', body: fd });
        const json = await res.json();
        if(json.status === 'success') loadPrescriptions(); else alert(json.message);
    } catch(e) { alert("Network error."); }
}

window.saveNote = async function(rx_id, btnObj, e) {
    if(e) e.stopPropagation();
    const note = document.getElementById('note_' + rx_id).value;
    const originalText = btnObj.innerHTML;
    btnObj.innerHTML = '<i class="fa fa-spinner fa-spin"></i>'; btnObj.disabled = true;

    try {
        let fd = new FormData(); fd.append('action', 'save_pharmacist_note'); fd.append('rx_id', rx_id); fd.append('notes', note);
        const res = await fetch(API_URL, { method: 'POST', body: fd });
        const json = await res.json();
        btnObj.innerHTML = '<i class="fa-solid fa-check"></i> Saved';
        btnObj.classList.replace('btn-dark', 'btn-success');
        setTimeout(() => { btnObj.innerHTML = originalText; btnObj.disabled = false; btnObj.classList.replace('btn-success', 'btn-dark'); }, 2000);
    } catch(e) {
        btnObj.innerHTML = '<i class="fa-solid fa-times"></i> Error';
        btnObj.classList.replace('btn-dark', 'btn-danger');
        setTimeout(() => { btnObj.innerHTML = originalText; btnObj.disabled = false; btnObj.classList.replace('btn-danger', 'btn-dark'); }, 2000);
    }
}

window.openAddRxModal = function() {
    document.getElementById('frmAddRx').reset();
    document.getElementById('add_rx_loc_id').value = document.getElementById('active_dispensary').value;
    if ($('#add_rx_drug').length) { $('#add_rx_drug').val(null).trigger('change'); }
    new bootstrap.Modal(document.getElementById('addRxModal')).show();
}

window.openEditModal = function(rx_id) {
    const rx = patientPrescriptions.find(p => p.rx_id == rx_id);
    if(!rx) return;
    document.getElementById('edit_rx_id').value = rx.rx_id;
    document.getElementById('edit_lbl_drug').innerText = rx.drug_name;
    document.getElementById('edit_rx_dose').value = rx.dose;
    document.getElementById('edit_rx_freq').value = rx.frequency;
    document.getElementById('edit_rx_dur').value = rx.duration_days;
    document.getElementById('edit_rx_qty').value = rx.qty_prescribed;
    document.getElementById('edit_rx_remarks').value = rx.remarks || '';
    new bootstrap.Modal(document.getElementById('editRxModal')).show();
}

window.rejectItem = async function(rx_id) {
    if(!confirm("Are you sure you want to completely reject this item from the queue?")) return;
    let fd = new FormData(); fd.append('action', 'reject_prescription'); fd.append('rx_id', rx_id);
    const res = await fetch(API_URL, { method: 'POST', body: fd });
    const json = await res.json();
    if(json.status === 'success') loadPrescriptions();
    else alert(json.message);
}

if (document.getElementById('frmAddRx')) {
    document.getElementById('frmAddRx').addEventListener('submit', async function(e) {
        e.preventDefault();
        const btn = document.getElementById('btnAddRxSubmit'); btn.disabled = true;
        try {
            const res = await fetch(API_URL, { method: 'POST', body: new FormData(this) });
            const json = await res.json();
            if(json.status === 'success') {
                bootstrap.Modal.getInstance(document.getElementById('addRxModal')).hide();
                loadPrescriptions();
            } else throw new Error(json.message);
        } catch(err) { alert(err.message); }
        finally { btn.disabled = false; }
    });
}

if (document.getElementById('frmEditRx')) {
    document.getElementById('frmEditRx').addEventListener('submit', async function(e) {
        e.preventDefault();
        const btn = document.getElementById('btnEditRxSubmit'); btn.disabled = true;
        try {
            const res = await fetch(API_URL, { method: 'POST', body: new FormData(this) });
            const json = await res.json();
            if(json.status === 'success') {
                bootstrap.Modal.getInstance(document.getElementById('editRxModal')).hide();
                loadPrescriptions();
            } else throw new Error(json.message);
        } catch(err) { alert(err.message); }
        finally { btn.disabled = false; }
    });
}