<?php

declare(strict_types=1);

require_once "../db.php";
require_once "../auth/customer_auth_common.php";
require_once "./soft_delete_helpers.php";

error_reporting(E_ERROR | E_PARSE);
ini_set("display_errors", "0");

if (($_SERVER["REQUEST_METHOD"] ?? "") !== "GET") {
    customerAuthJsonResponse(405, [
        "success" => false,
        "message" => "Method not allowed",
    ]);
}

$session = customerAuthRequireSession($conn);
$email = trim((string) ($session["email"] ?? ""));

[$softDeleteReady, $softDeleteError] = reservationEnsureSoftDeleteColumns($conn);
if (!$softDeleteReady) {
    customerAuthJsonResponse(500, [
        "success" => false,
        "message" => $softDeleteError,
    ]);
}

$stmt = $conn->prepare(
    "SELECT id, full_name, email, phone, reservation_date, reservation_time, guests, notes, food_preferences, allergies, status, terms_accepted, terms_version, cancellation_token, cancelled_by, created_at, updated_at
     FROM reservations
     WHERE email = ?
       AND user_deleted = 0
       AND admin_deleted = 0
     ORDER BY created_at DESC, id DESC"
);

if (!$stmt) {
    customerAuthJsonResponse(500, [
        "success" => false,
        "message" => "Failed to prepare reservation query.",
    ]);
}

$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

$mailConfig = require __DIR__ . "/mail_config.php";
$backendBase = $mailConfig["backend_url"];

$reservations = [];
while ($row = $result->fetch_assoc()) {
    $row["cancellation_link"] = $backendBase . "/reservation/cancel_reservation.php?token=" . urlencode((string) $row["cancellation_token"]);
    $reservations[] = $row;
}

$stmt->close();

customerAuthJsonResponse(200, [
    "success" => true,
    "count" => count($reservations),
    "reservations" => $reservations,
]);
