/**
 * RiMax Enterprise Procurement Engine
 * Module: Purchase Requisitions (List, Add, View, Update, Delete)
 */

const PR_API_PATH = "/rimax/application/dripend/systemSetup/procurement/fetchPurchaseRequisition.php";
const PR_POST_PATH = "/rimax/application/dripend/systemSetup/procurement/processPurchaseRequisition.php";

// ==========================================
// 1. ADD REQUISITION ENGINE
// ==========================================
window.initAddPurchaseRequisition = function() {
    window.MasterCatalog = []; 
    let rowCounter = 0;

    const reqDate = document.getElementById('pr_request_date');
    const reqByDate = document.getElementById('pr_required_date');
    if (reqDate) reqDate.value = new Date().toISOString().split('T')[0];
    if (reqByDate) {
        const d = new Date(); d.setDate(d.getDate() + 7);
        reqByDate.value = d.toISOString().split('T')[0];
    }

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

    fetch(`${PR_API_PATH}?action=get_lookups`)
        .then(res => res.json())
        .then(json => {
            if (json.status === 'success') {
                const storeSelect = document.getElementById('pr_store_id');
                if (storeSelect) {
                    storeSelect.innerHTML = '<option value="" selected disabled>-- Select Requesting Store --</option>';
                    json.stores.forEach(s => storeSelect.insertAdjacentHTML('beforeend', `<option value="${s.id}">${s.name}</option>`));
                }
                const prioSelect = document.getElementById('pr_priority');
                if (prioSelect) {
                    prioSelect.innerHTML = '';
                    json.priorities.forEach(p => prioSelect.insertAdjacentHTML('beforeend', `<option value="${p}">${p}</option>`));
                }
                window.MasterCatalog = json.products || [];
                window.addPrRow(); 
            } else { showMsg(json.message, 'danger'); }
        }).catch(err => showMsg("Database connection failed.", 'danger'));

    window.addPrRow = function() {
        const tbody = document.getElementById('prItemsBody');
        if (!tbody) return;
        rowCounter++;
        let opts = '<option value="" selected disabled>-- Select Catalog Item --</option>';
        window.MasterCatalog.forEach(p => opts += `<option value="${p.id}" data-price="${p.est_price || 0}">${p.name}</option>`);

        tbody.insertAdjacentHTML('beforeend', `
            <tr id="pr_row_${rowCounter}">
                <td><select name="service_id[]" class="form-select form-select-sm" onchange="window.setPrice(this, ${rowCounter})" required>${opts}</select></td>
                <td><input type="number" name="quantity[]" id="qty_${rowCounter}" class="form-control form-control-sm text-center fw-bold" min="1" value="1" oninput="window.calcPrTotals()" required></td>
                <td><input type="number" step="0.01" name="unit_cost[]" id="cost_${rowCounter}" class="form-control form-control-sm text-end" oninput="window.calcPrTotals()" required></td>
                <td><input type="text" id="line_total_${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('pr_row_${rowCounter}').remove(); window.calcPrTotals();"><i class="fa-solid fa-times"></i></button></td>
            </tr>
        `);
    };

    window.setPrice = function(el, idx) {
        const selectedVal = el.value;

        // --- LAYER 1: REAL-TIME DUPLICATE DETECTION ENGINE ---
        if (selectedVal) {
            let occurrenceCount = 0;
            const allSelects = document.querySelectorAll('#prItemsBody select[name="service_id[]"]');
            
            allSelects.forEach(sel => {
                if (sel.value === selectedVal) occurrenceCount++;
            });

            if (occurrenceCount > 1) {
                showMsg("This product is already in the requisition. Please adjust the quantity of the existing line.", "danger");
                el.value = ""; // Instantly reset the dropdown
                document.getElementById(`cost_${idx}`).value = ""; // Clear the unit cost
                window.calcPrTotals();
                return; // Stop execution
            }
        }
        // ------------------------------------------------------

        // Set valid price
        document.getElementById(`cost_${idx}`).value = parseFloat(el.options[el.selectedIndex].dataset.price || 0).toFixed(2);
        window.calcPrTotals();
    };

    window.calcPrTotals = function() {
        let total = 0;
        document.querySelectorAll('input[name="quantity[]"]').forEach((qtyEl, i) => {
            const costEl = document.querySelectorAll('input[name="unit_cost[]"]')[i];
            const line = (parseFloat(qtyEl.value)||0) * (parseFloat(costEl.value)||0);
            qtyEl.closest('tr').querySelector('input[id^="line_total_"]').value = line.toFixed(2);
            total += line;
        });
        document.getElementById('pr_summary_total').textContent = total.toLocaleString(undefined, {minimumFractionDigits: 2});
        document.getElementById('pr_hidden_total').value = total.toFixed(2);
    };

    const formEl = document.getElementById('purchaseRequisitionForm');
    if (formEl) {
        formEl.addEventListener('submit', async function(e) {
            e.preventDefault();

            // --- LAYER 2: PRE-FLIGHT DUPLICATE CHECK ---
            const selects = Array.from(document.querySelectorAll('#prItemsBody select[name="service_id[]"]')).map(s => s.value).filter(v => v !== "");
            const uniqueSelects = new Set(selects);
            if (selects.length !== uniqueSelects.size) {
                showMsg("Duplicate items detected in the list. Please combine them into a single row before submitting.", "danger");
                return;
            }
            // -------------------------------------------

            const btn = document.getElementById('btnPostPr');
            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Processing...';
            try {
                const res = await fetch(PR_POST_PATH, { method: 'POST', body: new FormData(formEl) });
                const json = await res.json();
                if (json.status === 'success') {
                    showMsg(json.message, 'success');
                    formEl.reset(); document.getElementById('prItemsBody').innerHTML = ''; window.addPrRow(); window.calcPrTotals();
                } else throw new Error(json.message);
            } catch (err) {
                showMsg(err.message, 'danger');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fa-solid fa-paper-plane me-2"></i> Submit for Approval';
            }
        });
    }
};

// ==========================================
// 2. LIST & DELETE REQUISITIONS ENGINE
// ==========================================
window.initListPurchaseRequisition = function() {
    const today = new Date(); const lastMonth = new Date(); lastMonth.setDate(today.getDate() - 30);
    if(document.getElementById('filter_start')) document.getElementById('filter_start').value = lastMonth.toISOString().split('T')[0];
    if(document.getElementById('filter_end')) document.getElementById('filter_end').value = today.toISOString().split('T')[0];

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

    if (document.getElementById('prFilterForm')) {
        document.getElementById('prFilterForm').addEventListener('submit', e => { e.preventDefault(); window.fetchGridData(); });
    }

    // Modal Based Delete Handler
    let deleteTargetId = null;
    let deleteModalInstance = null;

    window.confirmDeletePr = function(id, pr_no) {
        deleteTargetId = id;
        document.getElementById('deletePrNoText').textContent = pr_no;
        const modalEl = document.getElementById('deleteConfirmModal');
        deleteModalInstance = new bootstrap.Modal(modalEl);
        deleteModalInstance.show();
    };

    const btnDelete = document.getElementById('btnConfirmDelete');
    if (btnDelete) {
        btnDelete.addEventListener('click', async function() {
            btnDelete.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';
            btnDelete.disabled = true;
            try {
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('id', deleteTargetId);

                const res = await fetch(PR_POST_PATH, { method: 'POST', body: formData });
                const json = await res.json();
                
                if (json.status === 'success') {
                    deleteModalInstance.hide();
                    showMsg(json.message, 'success');
                    window.fetchGridData();
                } else throw new Error(json.message);
            } catch (err) {
                deleteModalInstance.hide();
                showMsg(err.message, 'danger');
            } finally {
                btnDelete.innerHTML = 'Delete Record';
                btnDelete.disabled = false;
            }
        });
    }

    window.fetchGridData = async function() {
        const tbody = document.getElementById('prGridBody');
        if (!tbody) return;

        try {
            const params = new URLSearchParams({
                action: 'get_list',
                start_date: document.getElementById('filter_start')?.value || '',
                end_date: document.getElementById('filter_end')?.value || '',
                status: document.getElementById('filter_status')?.value || ''
            });

            tbody.innerHTML = '<tr><td colspan="10" class="text-center py-5"><div class="spinner-border text-primary spinner-border-sm"></div> Syncing Data...</td></tr>';
            
            const res = await fetch(`${PR_API_PATH}?${params.toString()}`);
            const payload = await res.json();

            if (payload.status === 'success') {
                const sSelect = document.getElementById('filter_status');
                if (sSelect && sSelect.options.length === 1 && payload.statuses) {
                    payload.statuses.forEach(s => sSelect.insertAdjacentHTML('beforeend', `<option value="${s}">${s}</option>`));
                }

                const setVal = (id, val) => { if(document.getElementById(id)) document.getElementById(id).textContent = val; };
                setVal('kpi_pr_total', payload.kpis.total);
                setVal('kpi_pr_pending', payload.kpis.pending);
                setVal('kpi_pr_approved', payload.kpis.approved);
                setVal('kpi_pr_value', parseFloat(payload.kpis.value).toLocaleString(undefined, {minimumFractionDigits:2}));

                if (payload.data.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="10" class="text-center py-5 text-muted"><i class="fa-solid fa-ghost fs-2 d-block mb-2"></i> No requisitions found.</td></tr>';
                    return;
                }

                tbody.innerHTML = '';
                payload.data.forEach((item, index) => {
                    let bClass = 'bg-secondary';
                    if (item.status === 'Pending Approval') bClass = 'bg-warning text-dark';
                    if (item.status === 'Approved') bClass = 'bg-success';
                    if (item.status === 'Rejected' || item.status === 'Cancelled') bClass = 'bg-danger';

                    let pClass = 'text-muted';
                    if(item.priority === 'Urgent') pClass = 'text-warning fw-bold';
                    if(item.priority === 'Emergency') pClass = 'text-danger fw-bold';

                    let disableActions = (item.status !== 'Draft' && item.status !== 'Pending Approval') ? 'disabled' : '';

                    tbody.insertAdjacentHTML('beforeend', `
                        <tr class="bg-white">
                            <td class="px-3 border-end text-center fw-bold text-muted">${index + 1}</td>
                            <td class="text-secondary">${item.request_date}</td>
                            <td class="font-monospace text-primary fw-bold">${item.requisition_no}</td>
                            <td class="fw-bold text-dark">${item.store_name}</td>
                            <td class="${pClass}">${item.priority}</td>
                            <td class="text-center fw-bold bg-light-subtle">${item.total_items}</td>
                            <td class="text-end fw-bold text-danger">${parseFloat(item.estimated_total_value).toLocaleString(undefined, {minimumFractionDigits:2})}</td>
                            <td><span class="badge ${bClass} text-uppercase px-2">${item.status}</span></td>
                            <td class="text-muted"><i class="fa-regular fa-user me-1"></i> ${item.requested_by_name || 'System'}</td>
                            <td class="text-center">
                                <div class="d-flex justify-content-center gap-2">
                                    <a href="viewPurchaseRequisition.php?id=${item.id}" class="btn btn-sm btn-outline-primary" title="View Details">
                                        <i class="fa-solid fa-eye"></i>
                                    </a>
                                    <a href="updatePurchaseRequisition.php?id=${item.id}" class="btn btn-sm btn-outline-secondary ${disableActions}" title="Update Requisition">
                                        <i class="fa-solid fa-pen-to-square"></i>
                                    </a>
                                    <button type="button" class="btn btn-sm btn-outline-danger" title="Delete Requisition" onclick="window.confirmDeletePr(${item.id}, '${item.requisition_no}')" ${disableActions}>
                                        <i class="fa-solid fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `);
                });
            } else throw new Error(payload.message);
        } catch (error) {
            tbody.innerHTML = `<tr><td colspan="10" class="text-center py-4 text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation mb-2 fs-3 d-block"></i> Network/API Error: ${error.message}</td></tr>`;
        }
    }
    window.fetchGridData();
};

// ==========================================
// 3. VIEW REQUISITION ENGINE
// ==========================================
window.initViewPurchaseRequisition = async function() {
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id');
    const msgBox = document.getElementById('prViewMessage');

    if (!id) {
        if(msgBox) {
            msgBox.className = 'alert alert-danger d-block shadow-sm';
            msgBox.innerHTML = '<i class="fa-solid fa-triangle-exclamation me-2"></i> Error: No Requisition ID provided in URL.';
        }
        return;
    }

    try {
        const res = await fetch(`${PR_API_PATH}?action=get_single&id=${id}`);
        const payload = await res.json();

        if (payload.status === 'success') {
            const h = payload.data.header;
            if(document.getElementById('v_pr_no')) document.getElementById('v_pr_no').textContent = h.requisition_no;
            if(document.getElementById('v_store')) document.getElementById('v_store').textContent = h.store_name || 'N/A';
            if(document.getElementById('v_staff')) document.getElementById('v_staff').textContent = h.staff_name || 'System';
            if(document.getElementById('v_req_date')) document.getElementById('v_req_date').textContent = h.request_date;
            if(document.getElementById('v_need_date')) document.getElementById('v_need_date').textContent = h.required_date;
            if(document.getElementById('v_priority')) document.getElementById('v_priority').textContent = h.priority;
            if(document.getElementById('v_justification')) document.getElementById('v_justification').textContent = h.justification;
            if(document.getElementById('v_total')) document.getElementById('v_total').textContent = parseFloat(h.estimated_total_value).toLocaleString(undefined, {minimumFractionDigits:2});
            
            let badge = 'bg-secondary';
            if (h.status === 'Approved') badge = 'bg-success';
            if (h.status === 'Rejected' || h.status === 'Cancelled') badge = 'bg-danger';
            if (h.status === 'Pending Approval') badge = 'bg-warning text-dark';
            if(document.getElementById('v_status')) document.getElementById('v_status').innerHTML = `<span class="badge ${badge} fs-5 px-3 py-2 shadow-sm">${h.status}</span>`;

            const tbody = document.getElementById('v_itemsBody');
            if(tbody) {
                tbody.innerHTML = '';
                payload.data.items.forEach(item => {
                    const total = parseFloat(item.requested_quantity) * parseFloat(item.estimated_unit_cost);
                    tbody.insertAdjacentHTML('beforeend', `
                        <tr>
                            <td class="fw-bold text-primary">${item.name}</td>
                            <td class="text-center fw-bold">${item.requested_quantity}</td>
                            <td class="text-end">${parseFloat(item.estimated_unit_cost).toFixed(2)}</td>
                            <td class="text-end fw-bold bg-light">${total.toFixed(2)}</td>
                        </tr>
                    `);
                });
                if(payload.data.items.length === 0) tbody.innerHTML = '<tr><td colspan="4" class="text-center py-3 text-muted">No items found.</td></tr>';
            }
        } else throw new Error(payload.message);
    } catch (err) {
        if(msgBox) {
            msgBox.className = 'alert alert-danger d-block shadow-sm';
            msgBox.innerHTML = `<i class="fa-solid fa-triangle-exclamation me-2"></i> ${err.message}`;
        }
    }
};

// ==========================================
// 4. UPDATE REQUISITION ENGINE
// ==========================================
window.initUpdatePurchaseRequisition = async function() {
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('id');
    const msgBox = document.getElementById('prUpdateMessage');

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

    if (!id) return showMsg('Error: No Requisition ID provided in URL.', 'danger');

    // Initialize Add Engine base functions to reuse logic
    window.initAddPurchaseRequisition();

    try {
        const res = await fetch(`${PR_API_PATH}?action=get_single&id=${id}`);
        const payload = await res.json();

        if (payload.status === 'success') {
            const h = payload.data.header;
            
            document.getElementById('upd_pr_id').value = h.id;
            document.getElementById('upd_pr_no').textContent = h.requisition_no;
            document.getElementById('pr_request_date').value = h.request_date;
            document.getElementById('pr_required_date').value = h.required_date;
            document.getElementById('upd_justification').value = h.justification;
            
            // Allow Dropdowns to fetch lookups before setting selected value
            setTimeout(() => {
                if(document.getElementById('pr_store_id')) document.getElementById('pr_store_id').value = h.store_id;
                if(document.getElementById('pr_priority')) document.getElementById('pr_priority').value = h.priority;
                
                const tbody = document.getElementById('prItemsBody');
                if(tbody) {
                    tbody.innerHTML = '';
                    payload.data.items.forEach(item => window.addPrRow(item.service_id, item.requested_quantity, item.estimated_unit_cost));
                    window.calcPrTotals();
                }
            }, 600);
        } else throw new Error(payload.message);
    } catch (err) {
        showMsg(err.message, 'danger');
    }
};

// ==========================================
// ROUTER INITIALIZATION
// ==========================================
document.addEventListener("DOMContentLoaded", () => {
    if (document.getElementById('prGridBody')) window.initListPurchaseRequisition();
    // Use the specific hidden ID to trigger the update engine instead of the add engine
    else if (document.getElementById('upd_pr_id')) window.initUpdatePurchaseRequisition();
    else if (document.getElementById('purchaseRequisitionForm')) window.initAddPurchaseRequisition();
    else if (document.getElementById('v_pr_no')) window.initViewPurchaseRequisition();
});