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

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $conn->begin_transaction();

        $pr_id = (int)($_POST['requisition_id'] ?? 0);
        $decision = $conn->real_escape_string($_POST['decision'] ?? '');
        $comments = $conn->real_escape_string(trim($_POST['comments'] ?? ''));
        
        $staff_id = $_SESSION['staff_id'] ?? 1; // Fallback to 1 if testing without login

        if ($pr_id <= 0 || !in_array($decision, ['Approved', 'Rejected', 'Returned'])) {
            throw new Exception("Invalid approval payload.");
        }
        if (($decision === 'Rejected' || $decision === 'Returned') && empty($comments)) {
            throw new Exception("You must provide a comment when Rejecting or Returning a document.");
        }

        // 1. Ensure PR is actually pending
        $check = $conn->query("SELECT status FROM purchase_requisitions WHERE id = $pr_id");
        if(!$check || $check->num_rows === 0) throw new Exception("Requisition not found.");
        $currStatus = $check->fetch_assoc()['status'];
        if ($currStatus !== 'Pending Approval') throw new Exception("Requisition is currently '$currStatus' and cannot be processed.");

        // 2. Insert into Approval 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);
        if(!$stmtLog->execute()) throw new Exception("Audit Log Error: " . $stmtLog->error);
        $stmtLog->close();

        // 3. Update the Header Status
        $newStatus = $decision === 'Returned' ? 'Draft' : $decision; // Returned goes back to Draft for edits
        $conn->query("UPDATE purchase_requisitions SET status = '$newStatus' WHERE id = $pr_id");

        $conn->commit();
        ob_clean(); 
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'message' => "Requisition successfully $decision."]);
        exit;
    }
} catch (Throwable $e) { 
    if(isset($conn)) $conn->rollback();
    ob_clean(); header('Content-Type: application/json'); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>