<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once dirname(__DIR__, 2) . '/includes/db.php';
ini_set('display_errors', 0);
ob_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // NEW: Handle Delete Request
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        try {
            $id = (int)$_POST['id'];
            if ($id <= 0) throw new Exception("Invalid Requisition ID provided.");

            // Safety rule: Only Draft or Pending Approval can be deleted
            $stmt = $conn->prepare("DELETE FROM purchase_requisitions 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' => "Requisition deleted permanently."]);
            } else {
                throw new Exception("Could not delete. It may have already been approved or processed.");
            }
            $stmt->close();
        } catch (Exception $e) {
            ob_clean();
            echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
        }
        exit;
    }

    // NORMAL: Handle Insert Request
    $conn->begin_transaction();
    try {
        $staff_id = isset($_SESSION['staff_id']) ? (int)$_SESSION['staff_id'] : 0;
        if ($staff_id <= 0) {
            $fallback = $conn->query("SELECT staff_id FROM staff WHERE is_active = 1 LIMIT 1");
            if ($fallback && $fallback->num_rows > 0) $staff_id = (int)$fallback->fetch_assoc()['staff_id'];
            else throw new Exception("Session Security: Active Staff context missing.");
        }

        $store_id = (int)($_POST['store_id'] ?? 0);
        $req_date  = $conn->real_escape_string($_POST['request_date'] ?? date('Y-m-d'));
        $need_date = $conn->real_escape_string($_POST['required_date'] ?? date('Y-m-d'));
        $priority  = $conn->real_escape_string($_POST['priority'] ?? 'Routine');
        $justification = $conn->real_escape_string(trim($_POST['justification'] ?? ''));
        $est_total = (float)($_POST['estimated_total_value'] ?? 0);

        if ($store_id <= 0 || empty($justification) || empty($_POST['service_id'])) {
            throw new Exception("Store selection, justification, or product lines are missing.");
        }

        $year = date('Y');
        $countQuery = $conn->query("SELECT COUNT(id) as total FROM purchase_requisitions WHERE YEAR(created_at) = '$year'");
        $count = $countQuery ? $countQuery->fetch_assoc()['total'] + 1 : 1;
        $pr_no = "PR-" . $year . "-" . str_pad($count, 5, '0', STR_PAD_LEFT);

        $stmtHead = $conn->prepare("INSERT INTO purchase_requisitions (requisition_no, store_id, requested_by, request_date, required_date, priority, justification, estimated_total_value, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Pending Approval')");
        $stmtHead->bind_param("siissssd", $pr_no, $store_id, $staff_id, $req_date, $need_date, $priority, $justification, $est_total);
        if (!$stmtHead->execute()) throw new Exception($stmtHead->error);
        
        $pr_id = $conn->insert_id;
        $stmtHead->close();

        $stmtItem = $conn->prepare("INSERT INTO purchase_requisition_items (requisition_id, service_id, requested_quantity, estimated_unit_cost) VALUES (?, ?, ?, ?)");
        $itemsAdded = 0;
        foreach ($_POST['service_id'] as $idx => $sid) {
            $service_id = (int)$sid;
            $qty = (int)($_POST['quantity'][$idx] ?? 0);
            $cost = (float)($_POST['unit_cost'][$idx] ?? 0);

            if ($service_id > 0 && $qty > 0) {
                $stmtItem->bind_param("iiid", $pr_id, $service_id, $qty, $cost);
                $stmtItem->execute();
                $itemsAdded++;
            }
        }
        $stmtItem->close();

        if ($itemsAdded === 0) throw new Exception("No valid quantities were provided in the payload.");

        $conn->commit();
        ob_clean();
        echo json_encode(['status' => 'success', 'message' => "Requisition [ $pr_no ] Generated & Routed for Approval."]);

    } catch (Exception $e) {
        $conn->rollback();
        ob_clean();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}

?>