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

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

// ----------------------
// INPUTS (works for GET and POST)
// ----------------------
$ticketId    = $_POST['ticket_id'] ?? $_GET['ticket_id'] ?? null;
$token       = $_POST['token'] ?? $_GET['token'] ?? null;
$extendDays  = isset($_POST['extend_days']) ? (int)$_POST['extend_days'] : (isset($_GET['extend_days']) ? (int)$_GET['extend_days'] : 0);

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

// ----------------------
// LOOKUP TICKET
// ----------------------
$stmt = $pdo->prepare("
    SELECT p.*, h.hoa_account_name, h.HOA_statement, h.daysOfStay, h.daysOfReset
    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;
}

// ----------------------
// TIME + RULES
// ----------------------
$arrival    = strtotime($ticket['arrival_date']);
$expiration = strtotime($ticket['departure_date']);
$now        = time();

// Must be within 2 hours of expiration
if ($now < $expiration - 7200) { 
    echo json_encode(["error" => "Extensions are only available within 2 hours of expiration."]);
    exit;
}

// ----------------------
// CALCULATE REMAINING DAYS (true 24-hour blocks)
// ----------------------
$periodDays = (int)$ticket['daysOfReset'];
$stayDays   = (int)$ticket['daysOfStay'];

$periodStart = date("Y-m-d H:i:s", strtotime("-{$periodDays} days", $now));

$check = $pdo->prepare("
    SELECT SUM(
        CEIL(
            TIMESTAMPDIFF(
                HOUR,
                GREATEST(arrival_date, ?),
                LEAST(departure_date, NOW())
            ) / 24
        )
    ) AS used_days
    FROM parking_lots
    WHERE hoa_account_id = ?
      AND tag_number = ?
      AND rec_deleted = 'n'
      AND departure_date > ?
");
$check->execute([$periodStart, $ticket['hoa_account_id'], $ticket['tag_number'], $periodStart]);
$row = $check->fetch(PDO::FETCH_ASSOC);

$usedDays = (int)($row['used_days'] ?? 0);
$remainingDays = max($stayDays - $usedDays, 0);

// ----------------------
// QUERY MODE (extend_days == 0)
// ----------------------
if ($extendDays === 0) {
    echo json_encode([
        "success" => true,
        "max_days" => $remainingDays,
        "ticket_id" => $ticketId,
        "expiration" => $ticket['departure_date']
    ]);
    exit;
}

// ----------------------
// EXTEND MODE
// ----------------------
if ($extendDays > $remainingDays) {
    echo json_encode(["error" => "You only have {$remainingDays} days available for extension."]);
    exit;
}

$newDeparture = date("Y-m-d H:i:s", strtotime("+{$extendDays} days", $expiration));
$update = $pdo->prepare("UPDATE parking_lots SET departure_date = ? WHERE parking_lot_id = ?");
$update->execute([$newDeparture, $ticketId]);

// ----------------------
// SMS CONFIRMATION
// ----------------------
$baseUrl   = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
$baseUrl  .= "://{$_SERVER['HTTP_HOST']}";

// Always point to /ui/
$scriptDir = dirname(dirname($_SERVER['SCRIPT_NAME'])); // e.g. /10x/api
$rootDir   = str_replace('/api', '', $scriptDir);       // e.g. /10x
$uiUrl     = $rootDir . '/ui/index.html';

$ticketUrl = $baseUrl . $uiUrl . "?ticket={$ticketId}&token={$token}";

$message = "🚗 Extension Confirmed – Your parking pass has been extended.\nNew expiry: {$newDeparture}\n{$ticketUrl}\nDO NOT REPLY";
sendSMS($ticket['phone'], $message);

// ----------------------
// RESPONSE
// ----------------------
echo json_encode([
    "success" => true,
    "new_expiration" => $newDeparture,
    "ticket_id" => $ticketId
]);