<?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
$input = json_decode(file_get_contents("php://input"), true);
$email = isset($input['email']) ? trim($input['email']) : "";

if (empty($email)) {
    echo json_encode([
        "success" => false,
        "message" => "Email is required"
    ]);
    exit;
}

// Fetch all tickets for the user
$sql = "SELECT * FROM tickets WHERE email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

$tickets = [];
while ($row = $result->fetch_assoc()) {
    $tickets[] = $row;
}

// Count totals for this user
$totalTickets = count($tickets);
$totalOpen = 0;
$totalClose = 0;
foreach ($tickets as $ticket) {
    if ($ticket['status'] == 0) $totalOpen++;   // 0 = Open
    elseif ($ticket['status'] == 1) $totalClose++; // 1 = Close
}

// Return response
echo json_encode([
    "success" => true,
    "total_tickets" => $totalTickets,
    "total_open_tickets" => $totalOpen,
    "total_close_tickets" => $totalClose,
    "tickets" => $tickets
]);
?>
