<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

include_once __DIR__ . "/config.php";

// Handle OPTIONS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Read JSON input if provided
$input = json_decode(file_get_contents("php://input"), true);
$statusFilter = isset($input['status']) ? strtolower(trim($input['status'])) : "";

// Build query based on filter
$sql = "SELECT * FROM tickets";
if ($statusFilter === "open") {
    $sql .= " WHERE status = 0";   // assuming 1 = open
} elseif ($statusFilter === "close") {
    $sql .= " WHERE status = 1";   // assuming 0 = close
}

$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    $tickets = [];
    while ($row = $result->fetch_assoc()) {
        $tickets[] = $row;
    }
    echo json_encode([
        "success" => true,
        "count" => count($tickets),
        "tickets" => $tickets
    ]);
} else {
    echo json_encode([
        "success" => false,
        "message" => "No tickets found"
    ]);
}
?>
