<?php
ob_start();
error_reporting(0);

try {
    $db_found = false;
    $paths = [ dirname(__DIR__, 3) . '/includes/db.php', dirname(__DIR__, 4) . '/includes/db.php', dirname(__DIR__, 2) . '/config/config.php' ];
    foreach($paths as $p) { if(file_exists($p)) { require_once $p; $db_found = true; break; } }
    if(!$db_found || !isset($conn)) throw new Exception("Critical: Database connection file missing.");

    $action = $_GET['action'] ?? '';

    if ($action === 'get_dashboard') {
        // 1. Fetch Pending Requisitions for the Grid
        $sql = "
            SELECT 
                pr.id, pr.requisition_no, pr.request_date, pr.priority, pr.estimated_total_value,
                s.store_name,
                CONCAT(st.first_name, ' ', st.last_name) as requested_by_name,
                (SELECT COUNT(id) FROM purchase_requisition_items WHERE requisition_id = pr.id) as total_items
            FROM purchase_requisitions pr
            INNER JOIN stores s ON pr.store_id = s.id
            LEFT JOIN staff st ON pr.requested_by = st.staff_id
            WHERE pr.status = 'Pending Approval' 
            ORDER BY pr.priority = 'Emergency' DESC, pr.priority = 'Urgent' DESC, pr.request_date ASC
        ";
        
        $res = $conn->query($sql);
        if (!$res) throw new Exception($conn->error);
        
        $pendingData = [];
        while ($r = $res->fetch_assoc()) { $pendingData[] = $r; }

        // 2. Calculate KPIs (Overall Approval Stats)
        $kpis = ['pending' => count($pendingData), 'approved_today' => 0, 'rejected' => 0, 'returned' => 0];
        
        $today = date('Y-m-d');
        $kpiSql = "SELECT decision, COUNT(approval_id) as total FROM purchase_requisition_approvals WHERE DATE(approval_date) = '$today' GROUP BY decision";
        $kpiRes = $conn->query($kpiSql);
        if ($kpiRes) {
            while($k = $kpiRes->fetch_assoc()) {
                if($k['decision'] === 'Approved') $kpis['approved_today'] = (int)$k['total'];
                if($k['decision'] === 'Rejected') $kpis['rejected'] = (int)$k['total'];
                if($k['decision'] === 'Returned') $kpis['returned'] = (int)$k['total'];
            }
        }
        
        ob_clean();
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'data' => $pendingData, 'kpis' => $kpis]);
        exit;
    }
} catch (Throwable $e) { 
    ob_clean(); header('Content-Type: application/json'); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>