/**
 * RiMax Enterprise Procurement Engine
 * Module: Approval Workflow Engine (AJAX)
 */

const APP_API_PATH = "/rimax/application/dripend/systemSetup/procurement/fetchPrApprovals.php";
const APP_POST_PATH = "/rimax/application/dripend/systemSetup/procurement/processPrApproval.php";

document.addEventListener("DOMContentLoaded", () => {
    
    const msgBox = document.getElementById('approvalMessage');
    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' });
    };

    let decisionModal = null;
    if(document.getElementById('decisionModal')) {
        decisionModal = new bootstrap.Modal(document.getElementById('decisionModal'));
    }

    // 1. Fetch Pending Requisitions Grid
    window.fetchApprovalGrid = async function() {
        const tbody = document.getElementById('approvalGridBody');
        if (!tbody) return;

        try {
            tbody.innerHTML = '<tr><td colspan="8" class="text-center py-5"><div class="spinner-border text-primary spinner-border-sm"></div> Fetching Approvals...</td></tr>';
            
            const res = await fetch(`${APP_API_PATH}?action=get_dashboard`);
            const payload = await res.json();

            if (payload.status === 'success') {
                // Update KPIs
                const setVal = (id, val) => { if(document.getElementById(id)) document.getElementById(id).textContent = val; };
                setVal('kpi_pending', payload.kpis.pending);
                setVal('kpi_approved', payload.kpis.approved_today);
                setVal('kpi_rejected', payload.kpis.rejected);
                setVal('kpi_returned', payload.kpis.returned);

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

                tbody.innerHTML = '';
                payload.data.forEach((item, index) => {
                    let pClass = 'text-muted';
                    if(item.priority === 'Urgent') pClass = 'text-warning fw-bold';
                    if(item.priority === 'Emergency') pClass = 'text-danger fw-bold';

                    tbody.insertAdjacentHTML('beforeend', `
                        <tr class="bg-white">
                            <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 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}" target="_blank" class="btn btn-sm btn-outline-dark" title="View Full Details"><i class="fa-solid fa-eye"></i></a>
                                    <button class="btn btn-sm btn-success shadow-sm fw-bold px-3" onclick="window.openDecisionModal(${item.id}, '${item.requisition_no}', 'Approved')"><i class="fa-solid fa-check"></i></button>
                                    <button class="btn btn-sm btn-warning shadow-sm fw-bold text-dark px-3" onclick="window.openDecisionModal(${item.id}, '${item.requisition_no}', 'Returned')"><i class="fa-solid fa-rotate-left"></i></button>
                                    <button class="btn btn-sm btn-danger shadow-sm fw-bold px-3" onclick="window.openDecisionModal(${item.id}, '${item.requisition_no}', 'Rejected')"><i class="fa-solid fa-times"></i></button>
                                </div>
                            </td>
                        </tr>
                    `);
                });
            } else throw new Error(payload.message);
        } catch (err) {
            tbody.innerHTML = `<tr><td colspan="8" class="text-center py-4 text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation mb-2 fs-3 d-block"></i> Error: ${err.message}</td></tr>`;
        }
    };

    // 2. Modal Controller
    window.openDecisionModal = function(id, pr_no, decisionType) {
        document.getElementById('modal_pr_id').value = id;
        document.getElementById('modal_decision').value = decisionType;
        document.getElementById('modalPrNoText').textContent = pr_no;
        document.getElementById('modalDecisionText').textContent = decisionType.toUpperCase();
        document.getElementById('modal_comments').value = '';

        const mHeader = document.getElementById('modalHeader');
        const mBtn = document.getElementById('btnSubmitDecision');
        
        mHeader.className = 'modal-header text-white ' + (decisionType === 'Approved' ? 'bg-success' : (decisionType === 'Returned' ? 'bg-warning text-dark' : 'bg-danger'));
        mBtn.className = 'btn fw-bold px-4 ' + (decisionType === 'Approved' ? 'btn-success' : (decisionType === 'Returned' ? 'btn-warning text-dark' : 'btn-danger'));
        mBtn.textContent = "Confirm " + decisionType;

        decisionModal.show();
    };

    // 3. Submit Decision via AJAX
    const frm = document.getElementById('approvalForm');
    if (frm) {
        frm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const btn = document.getElementById('btnSubmitDecision');
            const originalText = btn.textContent;
            
            btn.disabled = true; 
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Processing...';

            try {
                const res = await fetch(APP_POST_PATH, { method: 'POST', body: new FormData(frm) });
                const json = await res.json();
                
                if (json.status === 'success') {
                    decisionModal.hide();
                    showMsg(json.message, 'success');
                    window.fetchApprovalGrid();
                } else {
                    throw new Error(json.message);
                }
            } catch (err) {
                alert("Error: " + err.message);
                btn.disabled = false;
                btn.textContent = originalText;
            }
        });
    }

    // Auto-load grid
    if(document.getElementById('approvalGridBody')) window.fetchApprovalGrid();
});