<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
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.");

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        
        // 1. DELETE ACTION
        if (isset($_POST['action']) && $_POST['action'] === 'delete') {
            $id = (int)$_POST['id'];
            $stmt = $conn->prepare("DELETE FROM purchase_orders WHERE id=? AND status IN ('Draft', 'Pending Approval')");
            $stmt->bind_param("i", $id); $stmt->execute();
            if($stmt->affected_rows > 0) { ob_clean(); echo json_encode(['status'=>'success', 'message'=>"PO Deleted Permanently."]); exit; }
            else throw new Exception("Delete failed. Record may be locked or issued.");
        }

        // 2. ADD & UPDATE ACTION
        $conn->begin_transaction();
        $staff_id = $_SESSION['staff_id'] ?? 1;
        $po_type = $_POST['po_type'] ?? 'direct';
        $req_id = ($po_type === 'pr' && !empty($_POST['requisition_id'])) ? (int)$_POST['requisition_id'] : "NULL";
        $store_id = (int)$_POST['store_id'];
        $supplier_id = (int)$_POST['supplier_id'];
        $del_date = $conn->real_escape_string($_POST['expected_delivery_date']);
        $subtotal = (float)$_POST['subtotal'];
        $tax = (float)$_POST['tax_amount'];
        $disc = (float)$_POST['discount_amount'];
        $grand = (float)$_POST['grand_total'];

        if ($store_id <= 0 || $supplier_id <= 0 || empty($_POST['product_id'])) throw new Exception("Missing required fields or items.");
        if (count($_POST['product_id']) !== count(array_unique($_POST['product_id']))) throw new Exception("Duplicate items detected in the list.");

        if (isset($_POST['action']) && $_POST['action'] === 'update') {
            $po_id = (int)$_POST['po_id'];
            $stmt = $conn->prepare("UPDATE purchase_orders SET supplier_id=?, store_id=?, expected_delivery_date=?, subtotal=?, tax_amount=?, discount_amount=?, grand_total=? WHERE id=? AND status IN ('Draft', 'Pending Approval')");
            $stmt->bind_param("iisddddi", $supplier_id, $store_id, $del_date, $subtotal, $tax, $disc, $grand, $po_id); $stmt->execute();
            if($stmt->affected_rows === 0 && $stmt->error) throw new Exception("Update failed.");
            
            $conn->query("DELETE FROM purchase_order_items WHERE purchase_order_id = $po_id");
            $msg = "Purchase Order Updated.";
        } else {
            $cnt = $conn->query("SELECT COUNT(id) as t FROM purchase_orders WHERE YEAR(created_at) = ".date('Y'))->fetch_assoc()['t'] + 1;
            $po_no = "PO-" . date('Y') . "-" . str_pad($cnt, 5, '0', STR_PAD_LEFT);
            $order_date = date('Y-m-d');
            
            $req_val = $req_id !== "NULL" ? $req_id : null;
            $stmt = $conn->prepare("INSERT INTO purchase_orders (po_number, requisition_id, supplier_id, store_id, order_date, expected_delivery_date, subtotal, tax_amount, discount_amount, grand_total, status, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending Approval', ?)");
            $stmt->bind_param("siiissddddi", $po_no, $req_val, $supplier_id, $store_id, $order_date, $del_date, $subtotal, $tax, $disc, $grand, $staff_id); 
            $stmt->execute();
            $po_id = $conn->insert_id; $msg = "Generated PO: $po_no";
            
            if($req_val) $conn->query("UPDATE purchase_requisitions SET status = 'Converted to PO' WHERE id = $req_val");
        }

        $stmtI = $conn->prepare("INSERT INTO purchase_order_items (purchase_order_id, product_id, ordered_quantity, unit_cost, line_total) VALUES (?, ?, ?, ?, ?)");
        foreach ($_POST['product_id'] as $idx => $pid) {
            $p = (int)$pid; $q = (int)$_POST['quantity'][$idx]; $c = (float)$_POST['unit_cost'][$idx]; $t = (float)$_POST['line_total'][$idx];
            if ($p > 0 && $q > 0) { $stmtI->bind_param("iiidd", $po_id, $p, $q, $c, $t); $stmtI->execute(); }
        }
        $conn->commit(); ob_clean(); echo json_encode(['status'=>'success', 'message'=>$msg]); exit;
    }
} catch (Throwable $e) { if(isset($conn)) $conn->rollback(); ob_clean(); echo json_encode(['status'=>'error', 'message'=>$e->getMessage()]); }
?>