<?php 
require_once dirname(__DIR__, 2) . '/dripend/config/config.php'; 
require_once dirname(__DIR__, 2) . '/dripend/includes/db.php'; 

$message = ''; $msgType = '';
$staff_id = $_SESSION['staff_id'] ?? 1; // Simulated session staff ID

// ==========================================
// 1. PROCESS APPROVAL FORM SUBMISSION (AJAX POST)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'process_approval') {
    ob_clean(); // Ensure strictly JSON output
    $conn->begin_transaction();
    try {
        $pr_id = (int)$_POST['requisition_id'];
        $decision = $conn->real_escape_string($_POST['decision']);
        $comments = $conn->real_escape_string(trim($_POST['comments']));

        if ($pr_id <= 0 || !in_array($decision, ['Approved', 'Rejected', 'Returned'])) throw new Exception("Invalid decision data.");
        if (in_array($decision, ['Rejected', 'Returned']) && empty($comments)) throw new Exception("Comments are legally required when Rejecting or Returning a document.");

        $check = $conn->query("SELECT status FROM purchase_requisitions WHERE id = $pr_id");
        if (!$check || $check->num_rows === 0) throw new Exception("Requisition not found in database.");
        if ($check->fetch_assoc()['status'] !== 'Pending Approval') throw new Exception("This document is no longer pending approval.");

        // Insert Audit Log
        $stmtLog = $conn->prepare("INSERT INTO purchase_requisition_approvals (requisition_id, approved_by, decision, comments) VALUES (?, ?, ?, ?)");
        $stmtLog->bind_param("iiss", $pr_id, $staff_id, $decision, $comments);
        $stmtLog->execute();

        // Update Document Status
        $newStatus = ($decision === 'Returned') ? 'Draft' : $decision;
        $conn->query("UPDATE purchase_requisitions SET status = '$newStatus' WHERE id = $pr_id");

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => "Requisition successfully marked as $decision."]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// ==========================================
// 2. FETCH DASHBOARD KPIS
// ==========================================
$kpi_pending = 0; $kpi_approved = 0; $kpi_returned = 0; $kpi_rejected = 0;
$res = $conn->query("SELECT COUNT(id) as c FROM purchase_requisitions WHERE status = 'Pending Approval'");
if($res) $kpi_pending = $res->fetch_assoc()['c'];

$today = date('Y-m-d');
$res = $conn->query("SELECT decision, COUNT(approval_id) as c FROM purchase_requisition_approvals WHERE DATE(approval_date) = '$today' GROUP BY decision");
if($res) {
    while($r = $res->fetch_assoc()) {
        if($r['decision'] === 'Approved') $kpi_approved = $r['c'];
        if($r['decision'] === 'Returned') $kpi_returned = $r['c'];
        if($r['decision'] === 'Rejected') $kpi_rejected = $r['c'];
    }
}

// ==========================================
// 3. ADVANCED FILTER LOGIC & DATA FETCH
// ==========================================
$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$start_date = isset($_GET['start_date']) ? $conn->real_escape_string($_GET['start_date']) : '';
$end_date = isset($_GET['end_date']) ? $conn->real_escape_string($_GET['end_date']) : '';
$status_filter = isset($_GET['status_filter']) ? $conn->real_escape_string($_GET['status_filter']) : 'Pending Approval';

$where = [];
if ($status_filter !== 'All') {
    $where[] = "pr.status = '$status_filter'";
} else {
    // Hide Drafts from Approvers by default when viewing "All"
    $where[] = "pr.status IN ('Pending Approval', 'Approved', 'Rejected', 'Returned', 'Converted to PO')";
}

if (!empty($start_date)) $where[] = "pr.request_date >= '$start_date'";
if (!empty($end_date)) $where[] = "pr.request_date <= '$end_date'";
if (!empty($search)) {
    $where[] = "(pr.requisition_no LIKE '%$search%' OR s.store_name LIKE '%$search%' OR st.first_name LIKE '%$search%' OR st.last_name LIKE '%$search%')";
}

$where_clause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";

$grid_data = [];
$sql = "
    SELECT pr.*, s.store_name, CONCAT(st.first_name, ' ', st.last_name) as staff_name,
           (SELECT COUNT(id) FROM purchase_requisition_items WHERE requisition_id = pr.id) as items_count
    FROM purchase_requisitions pr
    LEFT JOIN stores s ON pr.store_id = s.id
    LEFT JOIN staff st ON pr.requested_by = st.staff_id
    $where_clause
    ORDER BY pr.priority = 'Emergency' DESC, pr.priority = 'Urgent' DESC, pr.request_date ASC
";
$res = $conn->query($sql);
if($res) { while($r = $res->fetch_assoc()) { $grid_data[] = $r; } }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><title>Approval Dashboard | RiMax</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>body{background:#f8fafc;font-family:'Inter',sans-serif;margin:0;} .main-content{margin-left:300px;padding:20px;min-height:100vh;} @media(max-width:1024px){.main-content{margin-left:0;}}</style>
</head>
<body>
    <?php include(dirname(__DIR__, 2) . '/dripend/statpages/sidebar.php'); ?>
    
    <div class="main-content">
        <div class="container-fluid py-2">
            
            <div id="ajaxMessage" class="d-none alert shadow-sm mb-4 rounded-3 border-0"></div>

            <div class="mb-4 pb-3 border-bottom">
                <h2 class="h4 text-dark fw-bold m-0"><i class="fa-solid fa-stamp text-primary me-2"></i>Procurement Approval Engine</h2>
                <p class="text-muted small m-0 mt-1">Review, Approve, Return, or Reject requisitions.</p>
            </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 border-start border-4 border-primary">
                        <div><span class="text-uppercase text-muted small fw-bold">Pending Approval</span><h3 class="m-0 fw-bold text-dark mt-1"><?= $kpi_pending ?></h3></div>
                        <div class="bg-primary-subtle text-primary p-3 rounded-3"><i class="fa-solid fa-hourglass-half 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 border-start border-4 border-success">
                        <div><span class="text-uppercase text-muted small fw-bold">Approved Today</span><h3 class="m-0 fw-bold text-success mt-1"><?= $kpi_approved ?></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 border-start border-4 border-warning">
                        <div><span class="text-uppercase text-muted small fw-bold">Returned For Edit</span><h3 class="m-0 fw-bold text-warning mt-1"><?= $kpi_returned ?></h3></div>
                        <div class="bg-warning-subtle text-warning p-3 rounded-3"><i class="fa-solid fa-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 border-start border-4 border-danger">
                        <div><span class="text-uppercase text-muted small fw-bold">Rejected Today</span><h3 class="m-0 fw-bold text-danger mt-1"><?= $kpi_rejected ?></h3></div>
                        <div class="bg-danger-subtle text-danger p-3 rounded-3"><i class="fa-solid fa-ban fs-4"></i></div>
                    </div>
                </div>
            </div>

            <form method="GET" class="row g-3 bg-white p-3 rounded-3 shadow-sm mb-4 align-items-end">
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted">Advanced Search</label>
                    <input type="text" name="search" class="form-control form-control-sm" placeholder="PR No, Store, or Staff Name..." value="<?= htmlspecialchars($search) ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label small fw-bold text-muted">From Date</label>
                    <input type="date" name="start_date" class="form-control form-control-sm" value="<?= htmlspecialchars($start_date) ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label small fw-bold text-muted">To Date</label>
                    <input type="date" name="end_date" class="form-control form-control-sm" value="<?= htmlspecialchars($end_date) ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted">Document Status</label>
                    <select name="status_filter" class="form-select form-select-sm">
                        <option value="Pending Approval" <?= $status_filter === 'Pending Approval' ? 'selected' : '' ?>>Pending Approval</option>
                        <option value="Approved" <?= $status_filter === 'Approved' ? 'selected' : '' ?>>Approved</option>
                        <option value="Rejected" <?= $status_filter === 'Rejected' ? 'selected' : '' ?>>Rejected</option>
                        <option value="Returned" <?= $status_filter === 'Returned' ? 'selected' : '' ?>>Returned</option>
                        <option value="All" <?= $status_filter === 'All' ? 'selected' : '' ?>>-- View All Historical --</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-sm btn-primary w-100 fw-bold"><i class="fa-solid fa-filter me-1"></i> Apply Filters</button>
                </div>
            </form>

            <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
                <div class="table-responsive">
                    <table class="table table-hover align-middle m-0 table-sm bg-white">
                        <thead class="table-dark small text-uppercase">
                            <tr>
                                <th class="py-3 px-3">Req Date</th><th>PR No.</th><th>Requesting Store</th><th>Priority</th>
                                <th class="text-center">Items</th><th class="text-end">Est. Value (GH₵)</th><th>Requested By</th>
                                <th class="text-center">Status</th><th class="text-center">Decision Panel</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($grid_data)): ?>
                                <tr>
                                    <td colspan="9" class="text-center py-5 text-muted">
                                        <i class="fa-solid fa-folder-open fs-1 text-light mb-3 d-block"></i>
                                        <h5 class="fw-bold text-dark">No data exists</h5>
                                        <p class="small m-0">No requisitions were found matching your current filters.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach($grid_data as $item): 
                                    $pClass = 'text-muted';
                                    if($item['priority'] === 'Urgent') $pClass = 'text-warning fw-bold';
                                    if($item['priority'] === 'Emergency') $pClass = 'text-danger fw-bold';

                                    $bClass = 'bg-secondary';
                                    if($item['status'] === 'Approved') $bClass = 'bg-success';
                                    if($item['status'] === 'Pending Approval') $bClass = 'bg-warning text-dark';
                                    if(in_array($item['status'], ['Rejected', 'Cancelled'])) $bClass = 'bg-danger';
                                ?>
                                <tr>
                                    <td class="px-3 text-secondary"><?= htmlspecialchars($item['request_date']) ?></td>
                                    <td class="font-monospace text-primary fw-bold"><?= htmlspecialchars($item['requisition_no']) ?></td>
                                    <td class="fw-bold text-dark"><?= htmlspecialchars($item['store_name'] ?? 'N/A') ?></td>
                                    <td class="<?= $pClass ?>"><?= htmlspecialchars($item['priority']) ?></td>
                                    <td class="text-center fw-bold bg-light-subtle"><?= htmlspecialchars($item['items_count']) ?></td>
                                    <td class="text-end fw-bold text-danger"><?= number_format($item['estimated_total_value'], 2) ?></td>
                                    <td class="text-muted"><i class="fa-regular fa-user me-1"></i> <?= htmlspecialchars($item['staff_name'] ?? 'System') ?></td>
                                    <td class="text-center"><span class="badge <?= $bClass ?> px-2 text-uppercase"><?= htmlspecialchars($item['status']) ?></span></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 Details"><i class="fa-solid fa-eye"></i></a>
                                            
                                            <?php if($item['status'] === 'Pending Approval'): ?>
                                                <button class="btn btn-sm btn-success shadow-sm fw-bold px-3" onclick="openModal(<?= $item['id'] ?>, '<?= $item['requisition_no'] ?>', 'Approved')" title="Approve"><i class="fa-solid fa-check"></i></button>
                                                <button class="btn btn-sm btn-warning shadow-sm fw-bold text-dark px-3" onclick="openModal(<?= $item['id'] ?>, '<?= $item['requisition_no'] ?>', 'Returned')" title="Return for Edit"><i class="fa-solid fa-rotate-left"></i></button>
                                                <button class="btn btn-sm btn-danger shadow-sm fw-bold px-3" onclick="openModal(<?= $item['id'] ?>, '<?= $item['requisition_no'] ?>', 'Rejected')" title="Reject"><i class="fa-solid fa-times"></i></button>
                                            <?php else: ?>
                                                <button class="btn btn-sm btn-light border text-muted px-3" disabled><i class="fa-solid fa-check"></i></button>
                                                <button class="btn btn-sm btn-light border text-muted px-3" disabled><i class="fa-solid fa-rotate-left"></i></button>
                                                <button class="btn btn-sm btn-light border text-muted px-3" disabled><i class="fa-solid fa-times"></i></button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="decisionModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow-lg">
                <div id="modalHeader" class="modal-header text-white">
                    <h5 class="modal-title fw-bold"><i class="fa-solid fa-scale-balanced me-2"></i> Process Requisition</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form id="approvalForm" autocomplete="off">
                    <div class="modal-body p-4 bg-light">
                        <input type="hidden" name="action" value="process_approval">
                        <input type="hidden" name="requisition_id" id="modal_pr_id">
                        <input type="hidden" name="decision" id="modal_decision">
                        
                        <div class="text-center mb-4">
                            <span class="text-muted small text-uppercase fw-bold d-block">You are about to Mark</span>
                            <h3 id="modalPrNoText" class="text-dark fw-bold font-monospace mb-1"></h3>
                            <span class="badge bg-dark fs-6" id="modalDecisionText"></span>
                        </div>

                        <label class="form-label small fw-bold text-uppercase">Approver Comments <span id="commentAsterisk" class="text-danger"></span></label>
                        <textarea name="comments" id="modal_comments" class="form-control shadow-sm" rows="3" placeholder="Provide justification for your decision..."></textarea>
                        <small class="text-muted mt-1 d-block"><i class="fa-solid fa-circle-info me-1"></i> Comments are permanently logged in the audit trail.</small>
                    </div>
                    <div class="modal-footer bg-white">
                        <button type="button" class="btn btn-outline-secondary fw-bold" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn" id="btnSubmitDecision">Submit Decision</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let decisionModalInstance = null;
        document.addEventListener("DOMContentLoaded", () => {
            decisionModalInstance = new bootstrap.Modal(document.getElementById('decisionModal'));
            
            const form = document.getElementById('approvalForm');
            if(form) {
                form.addEventListener('submit', async function(e) {
                    e.preventDefault();
                    const btn = document.getElementById('btnSubmitDecision');
                    const ogText = btn.textContent;
                    btn.disabled = true; btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Processing...';

                    try {
                        const res = await fetch('', { method: 'POST', body: new FormData(form) });
                        const json = await res.json();
                        
                        const msgBox = document.getElementById('ajaxMessage');
                        if (json.status === 'success') {
                            decisionModalInstance.hide();
                            msgBox.className = 'alert alert-success shadow-sm mb-4 rounded-3 border-0 d-block';
                            msgBox.innerHTML = `<i class="fa-solid fa-check-circle me-2"></i> ${json.message}`;
                            setTimeout(() => { window.location.reload(); }, 1500);
                        } else {
                            throw new Error(json.message);
                        }
                    } catch (err) {
                        alert("Error: " + err.message);
                        btn.disabled = false; btn.textContent = ogText;
                    }
                });
            }
        });

        function openModal(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();
            
            const reqComments = (decisionType === 'Returned' || decisionType === 'Rejected');
            document.getElementById('modal_comments').required = reqComments;
            document.getElementById('commentAsterisk').textContent = reqComments ? '*' : '';
            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;

            decisionModalInstance.show();
        }
    </script>
</body>
</html>