<?php
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domainName = $_SERVER['HTTP_HOST'];
$baseDir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$computedBaseUrl = $protocol . $domainName . $baseDir;
?>

<div class="container-fluid py-4 px-4">
    <div class="d-flex justify-content-between align-items-center mb-4 pb-3 border-bottom">
        <div>
            <h2 class="h4 text-dark fw-bold m-0"><i class="fa-solid fa-list-check text-primary me-2"></i>Purchase Requisitions Tracker</h2>
            <p class="text-muted small m-0 mt-1">Monitor internal department requests awaiting procurement approval.</p>
        </div>
        <a href="?cat=procurement&page=procurement/addPurchaseRequisition.php" class="btn btn-primary fw-bold shadow-sm">
            <i class="fa-solid fa-plus me-2"></i> New Requisition
        </a>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="card border-0 p-3 shadow-sm d-flex flex-row justify-content-between align-items-center bg-white rounded-3">
                <div>
                    <span class="text-uppercase text-muted small fw-bold">Total Requisitions</span>
                    <h3 class="m-0 fw-bold text-dark mt-1" id="kpi_pr_total">0</h3>
                </div>
                <div class="bg-primary-subtle text-primary p-3 rounded-3"><i class="fa-solid fa-folder-open fs-4"></i></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 p-3 shadow-sm d-flex flex-row justify-content-between align-items-center bg-white rounded-3">
                <div>
                    <span class="text-uppercase text-muted small fw-bold">Pending Approval</span>
                    <h3 class="m-0 fw-bold text-warning mt-1" id="kpi_pr_pending">0</h3>
                </div>
                <div class="bg-warning-subtle text-warning p-3 rounded-3"><i class="fa-solid fa-clock-rotate-left fs-4"></i></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 p-3 shadow-sm d-flex flex-row justify-content-between align-items-center bg-white rounded-3">
                <div>
                    <span class="text-uppercase text-muted small fw-bold">Approved / Cleared</span>
                    <h3 class="m-0 fw-bold text-success mt-1" id="kpi_pr_approved">0</h3>
                </div>
                <div class="bg-success-subtle text-success p-3 rounded-3"><i class="fa-solid fa-check-double fs-4"></i></div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 p-3 shadow-sm d-flex flex-row justify-content-between align-items-center bg-white rounded-3">
                <div>
                    <span class="text-uppercase text-muted small fw-bold">Total Est. Value</span>
                    <h3 class="m-0 fw-bold text-danger mt-1">GH₵ <span id="kpi_pr_value">0.00</span></h3>
                </div>
                <div class="bg-danger-subtle text-danger p-3 rounded-3"><i class="fa-solid fa-coins fs-4"></i></div>
            </div>
        </div>
    </div>

    <div class="bg-white p-3 rounded-3 border shadow-sm mb-4">
        <form id="prFilterForm" class="row g-3 align-items-end" autocomplete="off">
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted text-uppercase">From Date</label>
                <input type="date" name="start_date" id="filter_start" class="form-control form-control-sm" required>
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-uppercase text-muted">To Date</label>
                <input type="date" name="end_date" id="filter_end" class="form-control form-control-sm" required>
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-uppercase text-muted">Requisition Status</label>
                <select name="status" id="filter_status" class="form-select form-select-sm">
                    <option value="">-- All Statuses --</option>
                </select>
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-sm btn-primary fw-bold w-100"><i class="fa-solid fa-filter me-1"></i> Apply Engine Filters</button>
            </div>
        </form>
    </div>

    <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle m-0 table-sm">
                    <thead class="table-dark small text-uppercase" style="letter-spacing: 0.5px;">
                        <tr>
                            <th class="py-3 px-3">Req Date</th>
                            <th>Requisition No.</th>
                            <th>Requesting Dept</th>
                            <th>Priority</th>
                            <th class="text-center">Items</th>
                            <th class="text-end">Est. Value (GH₵)</th>
                            <th>Status</th>
                            <th>Requested By</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="prGridBody" class="small">
                        <tr><td colspan="9" class="text-center py-5"><div class="spinner-border text-primary"></div></td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
window.initListPurchaseRequisition = function() {
    const apiPath = "/rimax/application/dripend/systemSetup/procurement/fetchPurchaseRequisition.php";

    function setInitialDates() {
        const today = new Date();
        const lastMonth = new Date();
        lastMonth.setDate(today.getDate() - 30); // Default to last 30 days
        
        document.getElementById('filter_start').value = lastMonth.toISOString().split('T')[0];
        document.getElementById('filter_end').value = today.toISOString().split('T')[0];
    }

    const formEl = document.getElementById('prFilterForm');
    if (formEl) {
        const newFormEl = formEl.cloneNode(true);
        formEl.parentNode.replaceChild(newFormEl, formEl);
        newFormEl.addEventListener('submit', function(e) {
            e.preventDefault();
            fetchGridData();
        });
    }

    async function fetchGridData() {
        const tbody = document.getElementById('prGridBody');
        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="9" class="text-center py-5"><div class="spinner-border text-primary spinner-border-sm"></div> Syncing Requisitions...</td></tr>';

            const res = await fetch(`${apiPath}?${params.toString()}`);
            const payload = JSON.parse(await res.text());

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

                // Populate KPIs
                document.getElementById('kpi_pr_total').textContent = payload.kpis.total;
                document.getElementById('kpi_pr_pending').textContent = payload.kpis.pending;
                document.getElementById('kpi_pr_approved').textContent = payload.kpis.approved;
                document.getElementById('kpi_pr_value').textContent = parseFloat(payload.kpis.value).toLocaleString(undefined, {minimumFractionDigits:2});

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

                tbody.innerHTML = '';
                payload.data.forEach(item => {
                    // Status Badge Coloring
                    let badgeClass = 'bg-secondary';
                    if (item.status === 'Pending Approval') badgeClass = 'bg-warning text-dark';
                    if (item.status === 'Approved') badgeClass = 'bg-success';
                    if (item.status === 'Rejected' || item.status === 'Cancelled') badgeClass = 'bg-danger';
                    if (item.status === 'Converted to PO') badgeClass = 'bg-info text-dark';

                    // Priority Badge Coloring
                    let prioClass = 'text-muted';
                    if(item.priority === 'Urgent') prioClass = 'text-warning fw-bold';
                    if(item.priority === 'Emergency') prioClass = 'text-danger fw-bold';

                    const row = `
                        <tr class="bg-white">
                            <td class="px-3 border-end">${item.request_date}</td>
                            <td class="font-monospace text-primary fw-bold">${item.requisition_no}</td>
                            <td class="fw-bold">${item.department_name}</td>
                            <td class="${prioClass}">${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 ${badgeClass} 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">
                                <button class="btn btn-sm btn-outline-dark px-3 shadow-sm rounded-pill fw-bold"><i class="fa-solid fa-eye"></i></button>
                            </td>
                        </tr>
                    `;
                    tbody.insertAdjacentHTML('beforeend', row);
                });
            } else {
                throw new Error(payload.message);
            }
        } catch (error) {
            tbody.innerHTML = `<tr><td colspan="9" class="text-center py-4 text-danger fw-bold"><i class="fa-solid fa-triangle-exclamation mb-2 fs-3 d-block"></i> Database Sync Interrupted: ${error.message}</td></tr>`;
        }
    }

    setInitialDates();
    fetchGridData();
};

if (!document.querySelector('.main-wrapper')) {
    document.addEventListener("DOMContentLoaded", () => {
        if (typeof window.initListPurchaseRequisition === 'function') window.initListPurchaseRequisition();
    });
}
</script>