/**
 * RiMax Enterprise Procurement Engine
 * Module: Purchase Order Management
 */
const PO_API = "/rimax/application/dripend/systemSetup/procurement/fetchPurchaseOrder.php";
const PO_POST = "/rimax/application/dripend/systemSetup/procurement/processPurchaseOrder.php";

const showPoMsg = (id, text, type) => {
    const box = document.getElementById(id); if(!box) return;
    box.className = `alert alert-${type} shadow-sm mb-4 rounded-3 border-0 d-block`;
    box.innerHTML = `<i class="fa-solid fa-${type==='success'?'check-circle':'triangle-exclamation'} me-2"></i> ${text}`;
    window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 1. ADD & UPDATE ENGINE
window.initPOForm = async function(isUpdate = false) {
    window.PoCatalog = {}; 
    let rowCounter = 0;
    let globalOptionsHTML = '<option value="" selected disabled>-- Select Catalog Item --</option>';

    try {
        const res = await fetch(`${PO_API}?action=get_lookups`);
        const j = await res.json();
        
        if (j.status === 'success') {
            const buildOpts = (id, arr, lbl) => {
                const el = document.getElementById(id); if(!el) return;
                el.innerHTML = `<option value="">-- ${lbl} --</option>`;
                arr.forEach(x => el.insertAdjacentHTML('beforeend', `<option value="${x.id}">${x.name || x.requisition_no}</option>`));
            };
            buildOpts('po_store_id', j.stores, 'Select Store');
            buildOpts('po_supplier_id', j.suppliers, 'Select Supplier');
            buildOpts('po_requisition_id', j.prs, 'Select Approved Requisition');
            
            if(j.products) {
                j.products.forEach(p => {
                    window.PoCatalog[p.id] = p.est_price || 0;
                    globalOptionsHTML += `<option value="${p.id}">${p.name}</option>`;
                });
            }

            if (!isUpdate) {
                window.addPoRow(); // Add empty row for new form
            } else {
                window.loadUpdateData(); // Load existing data if update
            }
        } else throw new Error(j.message);
    } catch(err) { showPoMsg(isUpdate ? 'updPoMessage' : 'poMessage', err.message, 'danger'); }

    // Toggle PR vs Direct
    document.querySelectorAll('input[name="po_type"]').forEach(radio => {
        radio.addEventListener('change', function() {
            const isPR = this.value === 'pr';
            document.getElementById('pr_selector_div').classList.toggle('d-none', !isPR);
            document.getElementById('po_requisition_id').value = '';
            document.getElementById('poItemsBody').innerHTML = '';
            document.getElementById('btnAddRow').disabled = isPR;
            if(!isPR) window.addPoRow();
            window.calcPoTotals();
        });
    });

    // Auto-fetch PR Items
    document.getElementById('po_requisition_id')?.addEventListener('change', async function() {
        if(!this.value) { document.getElementById('poItemsBody').innerHTML = ''; window.calcPoTotals(); return; }
        try {
            const res = await fetch(`${PO_API}?action=get_pr_items&pr_id=${this.value}`);
            const j = await res.json();
            if(j.status === 'success') {
                document.getElementById('poItemsBody').innerHTML = '';
                j.items.forEach(i => window.addPoRow(i.service_id, i.requested_quantity, i.estimated_unit_cost));
                window.calcPoTotals();
            }
        } catch(e) { showPoMsg('poMessage', "Error fetching Requisition Items", "danger"); }
    });

    window.addPoRow = function(pid='', qty='1', cost='0') {
        const tb = document.getElementById('poItemsBody'); if(!tb) return;
        rowCounter++;
        tb.insertAdjacentHTML('beforeend', `
            <tr id="row_${rowCounter}">
                <td><select name="product_id[]" id="sel_${rowCounter}" class="form-select form-select-sm" onchange="window.setPoPrice(this, ${rowCounter})" required>${globalOptionsHTML}</select></td>
                <td><input type="number" name="quantity[]" id="qty_${rowCounter}" value="${qty}" class="form-control form-control-sm text-center fw-bold" min="1" oninput="window.calcPoTotals()" required></td>
                <td><input type="number" step="0.01" name="unit_cost[]" id="cst_${rowCounter}" value="${cost}" class="form-control form-control-sm text-end" oninput="window.calcPoTotals()" required></td>
                <td><input type="text" name="line_total[]" id="lin_${rowCounter}" class="form-control form-control-sm text-end fw-bold bg-light" readonly tabindex="-1"></td>
                <td class="text-center"><button type="button" class="btn btn-sm btn-danger py-1 px-2" onclick="document.getElementById('row_${rowCounter}').remove(); window.calcPoTotals();"><i class="fa-solid fa-times"></i></button></td>
            </tr>
        `);
        if(pid) document.getElementById(`sel_${rowCounter}`).value = pid;
    };

    window.setPoPrice = function(el, idx) {
        if (el.value) {
            let count = 0; document.querySelectorAll('#poItemsBody select[name="product_id[]"]').forEach(s => { if(s.value === el.value) count++; });
            if (count > 1) {
                alert("This product is already in the list. Please adjust the quantity of the existing line.");
                el.value = ""; document.getElementById(`cst_${idx}`).value = ""; window.calcPoTotals(); return;
            }
        }
        document.getElementById(`cst_${idx}`).value = parseFloat(window.PoCatalog[el.value] || 0).toFixed(2);
        window.calcPoTotals();
    };

    window.calcPoTotals = function() {
        let sub = 0;
        document.querySelectorAll('#poItemsBody tr').forEach(tr => {
            const q = parseFloat(tr.querySelector('input[name="quantity[]"]').value)||0;
            const c = parseFloat(tr.querySelector('input[name="unit_cost[]"]').value)||0;
            const t = q * c; tr.querySelector('input[name="line_total[]"]').value = t.toFixed(2); sub += t;
        });
        const tax = parseFloat(document.getElementById('po_tax').value)||0;
        const disc = parseFloat(document.getElementById('po_disc').value)||0;
        const grand = (sub + tax) - disc;

        document.getElementById('lbl_subtotal').textContent = sub.toLocaleString(undefined,{minimumFractionDigits:2});
        document.getElementById('po_subtotal').value = sub.toFixed(2);
        document.getElementById('lbl_grand').textContent = grand.toLocaleString(undefined,{minimumFractionDigits:2});
        document.getElementById('po_grand').value = grand.toFixed(2);
    };

    // FORM SUBMISSION
    const frmId = isUpdate ? 'poUpdateForm' : 'poForm';
    const frm = document.getElementById(frmId);
    if(frm) {
        frm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const sels = Array.from(document.querySelectorAll('#poItemsBody select[name="product_id[]"]')).map(s=>s.value).filter(v=>v!=="");
            if(sels.length !== new Set(sels).size) return alert("Duplicate items detected. Combine them before submitting.");

            const btn = document.getElementById(isUpdate ? 'btnUpdatePo' : 'btnSubmitPo'); 
            const ogText = btn.innerHTML; btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';
            
            try {
                const res = await fetch(PO_POST, { method:'POST', body:new FormData(frm) });
                const j = await res.json();
                if(j.status === 'success') {
                    showPoMsg(isUpdate ? 'updPoMessage' : 'poMessage', j.message, 'success');
                    setTimeout(() => window.location.href = 'listPurchaseOrder.php', 1500);
                } else throw new Error(j.message);
            } catch(err) {
                showPoMsg(isUpdate ? 'updPoMessage' : 'poMessage', err.message, 'danger');
                btn.disabled = false; btn.innerHTML = ogText;
            }
        });
    }
};

window.loadUpdateData = async function() {
    const id = new URLSearchParams(window.location.search).get('id'); if(!id) return;
    try {
        const res = await fetch(`${PO_API}?action=get_single&id=${id}`); const j = await res.json();
        if(j.status==='success') {
            const h = j.data.header;
            document.getElementById('upd_po_id').value = h.id;
            document.getElementById('upd_po_no').textContent = h.po_number;
            document.getElementById('po_req_date').value = h.order_date;
            document.getElementById('po_del_date').value = h.expected_delivery_date;
            document.getElementById('po_tax').value = h.tax_amount;
            document.getElementById('po_disc').value = h.discount_amount;
            
            setTimeout(() => {
                document.getElementById('po_store_id').value = h.store_id;
                document.getElementById('po_supplier_id').value = h.supplier_id;
            }, 50);

            document.getElementById('poItemsBody').innerHTML = '';
            j.data.items.forEach(i => window.addPoRow(i.product_id, i.ordered_quantity, i.unit_cost));
            window.calcPoTotals();
        }
    } catch(e) { showPoMsg('updPoMessage', 'Failed to load PO data.', 'danger'); }
};

// 2. LIST ENGINE
window.initListPO = async function() {
    const tb = document.getElementById('poGridBody'); if(!tb) return;
    try {
        const res = await fetch(`${PO_API}?action=get_list`); const j = await res.json();
        if(j.status==='success') {
            if(j.data.length === 0) return tb.innerHTML = `<tr><td colspan="8" class="text-center py-4 text-muted">No Purchase Orders Found.</td></tr>`;
            tb.innerHTML = '';
            j.data.forEach(i => {
                let bc = 'bg-secondary'; 
                if(i.status==='Approved') bc='bg-success'; 
                if(i.status==='Pending Approval') bc='bg-warning text-dark'; 
                if(['Cancelled','Rejected'].includes(i.status)) bc='bg-danger';
                
                let dis = !['Draft','Pending Approval'].includes(i.status) ? 'disabled' : '';

                tb.insertAdjacentHTML('beforeend', `
                    <tr class="bg-white">
                        <td class="text-muted ps-3">${i.order_date}</td>
                        <td class="font-monospace fw-bold text-primary">${i.po_number}</td>
                        <td class="fw-bold text-dark">${i.supplier_name}</td>
                        <td>${i.store_name}</td>
                        <td class="text-center fw-bold bg-light-subtle">${i.items_count}</td>
                        <td class="text-end fw-bold text-danger">${parseFloat(i.grand_total).toLocaleString(undefined,{minimumFractionDigits:2})}</td>
                        <td class="text-center"><span class="badge ${bc} px-2 text-uppercase">${i.status}</span></td>
                        <td class="text-center">
                            <a href="viewPurchaseOrder.php?id=${i.id}" class="btn btn-sm btn-outline-dark"><i class="fa-solid fa-eye"></i></a>
                            <a href="updatePurchaseOrder.php?id=${i.id}" class="btn btn-sm btn-outline-secondary ${dis}"><i class="fa-solid fa-pen"></i></a>
                            <a href="deletePurchaseOrder.php?id=${i.id}" class="btn btn-sm btn-outline-danger ${dis}"><i class="fa-solid fa-trash"></i></a>
                        </td>
                    </tr>
                `);
            });
        }
    } catch(e) { tb.innerHTML = `<tr><td colspan="8" class="text-danger text-center fw-bold py-4">API Error.</td></tr>`; }
};

// 3. VIEW ENGINE
window.initViewPO = async function() {
    const id = new URLSearchParams(window.location.search).get('id'); if(!id) return;
    try {
        const res = await fetch(`${PO_API}?action=get_single&id=${id}`); const j = await res.json();
        if(j.status==='success') {
            const h = j.data.header;
            ['po_number','supplier_name','store_name','order_date','expected_delivery_date','requisition_no'].forEach(k => {
                if(document.getElementById('v_'+k)) document.getElementById('v_'+k).textContent = h[k] || 'N/A';
            });
            document.getElementById('v_sub').textContent = parseFloat(h.subtotal).toLocaleString(undefined,{minimumFractionDigits:2});
            document.getElementById('v_tax').textContent = parseFloat(h.tax_amount).toLocaleString(undefined,{minimumFractionDigits:2});
            document.getElementById('v_disc').textContent = parseFloat(h.discount_amount).toLocaleString(undefined,{minimumFractionDigits:2});
            document.getElementById('v_grand').textContent = parseFloat(h.grand_total).toLocaleString(undefined,{minimumFractionDigits:2});
            
            let bc = 'bg-secondary'; if(h.status==='Approved') bc='bg-success'; if(h.status==='Pending Approval') bc='bg-warning text-dark'; if(['Cancelled','Rejected'].includes(h.status)) bc='bg-danger';
            document.getElementById('v_status').innerHTML = `<span class="badge ${bc} fs-5 px-3 py-2 shadow-sm">${h.status}</span>`;

            const tb = document.getElementById('v_itemsBody'); tb.innerHTML='';
            j.data.items.forEach(i => {
                tb.insertAdjacentHTML('beforeend', `<tr><td class="fw-bold text-primary">${i.name}</td><td class="text-center fw-bold">${i.ordered_quantity}</td><td class="text-end">${parseFloat(i.unit_cost).toFixed(2)}</td><td class="text-end bg-light fw-bold">${parseFloat(i.line_total).toFixed(2)}</td></tr>`);
            });
        }
    } catch(e) { showPoMsg('poViewMsg', e.message, 'danger'); }
};

// 4. DELETE ENGINE
window.initDeletePO = async function() {
    const id = new URLSearchParams(window.location.search).get('id'); if(!id) return;
    try {
        const res = await fetch(`${PO_API}?action=get_single&id=${id}`); const j = await res.json();
        if(j.status==='success') {
            document.getElementById('del_po_id').value = id;
            document.getElementById('del_po_no').textContent = j.data.header.po_number;
        }
    } catch(e) { document.getElementById('btnConfirmDelete').disabled = true; }

    const frm = document.getElementById('poDeleteForm');
    if(frm) frm.addEventListener('submit', async e => {
        e.preventDefault(); const btn = document.getElementById('btnConfirmDelete'); btn.disabled=true; btn.innerHTML='Deleting...';
        try {
            const res = await fetch(PO_POST, {method:'POST', body:new FormData(frm)}); const j = await res.json();
            if(j.status==='success') { showPoMsg('delMsg', j.message, 'success'); setTimeout(()=>window.location.href='listPurchaseOrder.php',1500); }
            else throw new Error(j.message);
        } catch(e) { showPoMsg('delMsg', e.message, 'danger'); btn.disabled=false; btn.innerHTML='Yes, Delete Record'; }
    });
};

document.addEventListener("DOMContentLoaded", () => {
    if(document.getElementById('poForm')) window.initPOForm(false);
    if(document.getElementById('poUpdateForm')) window.initPOForm(true);
    if(document.getElementById('poGridBody')) window.initListPO();
    if(document.getElementById('v_po_number')) window.initViewPO();
    if(document.getElementById('poDeleteForm')) window.initDeletePO();
});