<?php
ob_start(); error_reporting(0);
try {
    $db_found = false;
    $paths = [ dirname(__DIR__, 2) . '/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 missing.");

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

    // 1. Get Lookups for Add/Update Forms
    if ($action === 'get_lookups') {
        $stores = []; $sRes = $conn->query("SELECT id, store_name as name FROM stores WHERE is_active=1");
        if($sRes) while($r = $sRes->fetch_assoc()) $stores[] = $r;

        $suppliers = []; $supRes = $conn->query("SELECT id, company_name as name FROM suppliers WHERE is_active=1");
        if($supRes) while($r = $supRes->fetch_assoc()) $suppliers[] = $r;

        $products = []; $pRes = $conn->query("SELECT p.id, p.generic_name as name, MAX(pv.purchase_price) as est_price FROM products p LEFT JOIN product_variants pv ON p.id = pv.product_id WHERE p.is_active=1 GROUP BY p.id ORDER BY p.generic_name ASC");
        if($pRes) while($r = $pRes->fetch_assoc()) $products[] = $r;

        $prs = []; $prRes = $conn->query("SELECT id, requisition_no FROM purchase_requisitions WHERE status = 'Approved'");
        if($prRes) while($r = $prRes->fetch_assoc()) $prs[] = $r;

        ob_clean(); echo json_encode(['status'=>'success', 'stores'=>$stores, 'suppliers'=>$suppliers, 'products'=>$products, 'prs'=>$prs]); exit;
    }

    // 2. Fetch Items from an Approved PR for Auto-Conversion
    if ($action === 'get_pr_items') {
        $pr_id = (int)$_GET['pr_id'];
        $items = []; 
        $res = $conn->query("SELECT pri.service_id, pri.requested_quantity, pri.estimated_unit_cost, p.generic_name FROM purchase_requisition_items pri JOIN products p ON pri.service_id = p.id WHERE pri.requisition_id = $pr_id");
        if($res) while($r = $res->fetch_assoc()) $items[] = $r;
        ob_clean(); echo json_encode(['status'=>'success', 'items'=>$items]); exit;
    }

    // 3. Fetch PO List Grid
    if ($action === 'get_list') {
        $data = [];
        $res = $conn->query("SELECT po.*, s.company_name as supplier_name, st.store_name, (SELECT COUNT(id) FROM purchase_order_items WHERE purchase_order_id = po.id) as items_count FROM purchase_orders po LEFT JOIN suppliers s ON po.supplier_id = s.id LEFT JOIN stores st ON po.store_id = st.id ORDER BY po.id DESC");
        if($res) while($r = $res->fetch_assoc()) $data[] = $r;
        ob_clean(); echo json_encode(['status'=>'success', 'data'=>$data]); exit;
    }

    // 4. Fetch Single PO for View/Update/Delete
    if ($action === 'get_single') {
        $id = (int)$_GET['id'];
        $hRes = $conn->query("SELECT po.*, s.company_name as supplier_name, st.store_name, pr.requisition_no FROM purchase_orders po LEFT JOIN suppliers s ON po.supplier_id = s.id LEFT JOIN stores st ON po.store_id = st.id LEFT JOIN purchase_requisitions pr ON po.requisition_id = pr.id WHERE po.id = $id");
        if(!$hRes || $hRes->num_rows===0) throw new Exception("PO not found.");
        
        $items = [];
        $iRes = $conn->query("SELECT poi.*, p.generic_name as name FROM purchase_order_items poi JOIN products p ON poi.product_id = p.id WHERE poi.purchase_order_id = $id");
        if($iRes) while($r = $iRes->fetch_assoc()) $items[] = $r;
        
        ob_clean(); echo json_encode(['status'=>'success', 'data'=>['header'=>$hRes->fetch_assoc(), 'items'=>$items]]); exit;
    }
} catch (Throwable $e) { ob_clean(); echo json_encode(['status'=>'error', 'message'=>$e->getMessage()]); }
?>