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

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

$ticketId = $_GET['ticket_id'] ?? null;
$token    = $_GET['token'] ?? null;

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

// Lookup ticket
$stmt = $pdo->prepare("
    SELECT p.*, h.parkingDays, h.parkingPeriodDays
    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) {
    echo json_encode(["error" => "Ticket not found"]);
    exit;
}

// Calculate remaining extension days
$arrival    = strtotime($ticket['arrival_date']);
$expiration = strtotime($ticket['departure_date']);
$now        = time();

$periodDays = (int)$ticket['parkingPeriodDays'];
$stayDays   = (int)$ticket['parkingDays'];

// How many days already used in the period
$periodStart = date("Y-m-d H:i:s", strtotime("-{$periodDays} days", $now));
$check = $pdo->prepare("
    SELECT SUM(DATEDIFF(
        LEAST(departure_date, NOW()), 
        GREATEST(arrival_date, ?)
    ) + 1) AS used_days
    FROM parking_lots
    WHERE hoa_account_id = ?
      AND tag_number = ?
      AND stateProvidence = ?
      AND rec_deleted = 'n'
      AND departure_date > ?
");
$check->execute([
    $periodStart,
    $ticket['hoa_account_id'],
    $ticket['tag_number'],
    $ticket['stateProvidence'],
    $periodStart
]);
$row = $check->fetch(PDO::FETCH_ASSOC);
$usedDays = (int)($row['used_days'] ?? 0);

$remainingDays = max($stayDays - $usedDays, 0);

if ($remainingDays <= 0) {
    echo json_encode(["error" => "No days left for extension"]);
    exit;
}

// Return a clean list of extension options
$options = [];
for ($i = 1; $i <= $remainingDays; $i++) {
    $options[] = $i;
}

echo json_encode(["options" => $options]);