<?php
require __DIR__ . '/../config/db.php';

header('Content-Type: application/json');
date_default_timezone_set('America/New_York'); // Force Eastern timezone

// ----------------------
//  INPUT VALIDATION
// ----------------------
$ticketId = $_GET['id'] ?? null;
$token    = $_GET['token'] ?? null;

if (!$ticketId || !$token) {
    http_response_code(400);
    echo json_encode(["error" => "Missing ticket ID or token"]);
    exit;
}

// ----------------------
//  LOOKUP TICKET
// ----------------------
$stmt = $pdo->prepare("
    SELECT 
        p.parking_lot_id AS id,
        p.tag_number AS plate,
        p.stateProvidence AS state,
        p.residence_address AS address,
        p.email,
        p.phone,
        p.arrival_date AS arrival,
        p.departure_date AS expiration_time,
        p.ticket_token,
        h.hoa_account_name AS property_name,
        h.HOA_statement AS property_statement
    FROM parking_lots p
    JOIN hoa_account h ON p.hoa_account_id = h.hoa_account_id
    WHERE p.parking_lot_id = ? 
      AND p.ticket_token = ?
      AND p.rec_deleted = 'n'
    LIMIT 1
");
$stmt->execute([$ticketId, $token]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$ticket) {
    http_response_code(404);
    echo json_encode(["error" => "Ticket not found or expired"]);
    exit;
}

// ----------------------
//  FORMAT DATES IN PHP
// ----------------------
if (!empty($ticket['arrival'])) {
    $ticket['arrival'] = date("Y-m-d H:i:s", strtotime($ticket['arrival']));
}
if (!empty($ticket['expiration_time'])) {
    $ticket['expiration_time'] = date("Y-m-d H:i:s", strtotime($ticket['expiration_time']));
}

// ----------------------
//  RESPONSE
// ----------------------
echo json_encode([
    "ticket" => [
        "id" => $ticket['id'],
        "plate" => $ticket['plate'],
        "state" => $ticket['state'],
        "address" => $ticket['address'],
        "email" => $ticket['email'],
        "phone" => $ticket['phone'],
        "arrival" => $ticket['arrival'],
        "expiration_time" => $ticket['expiration_time'],
        "property_name" => $ticket['property_name'],
        "property_statement" => $ticket['property_statement']
    ]
]);