<?php
require_once '../db.php';
require_once './soft_delete_helpers.php';

header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(["success" => false, "message" => "Method not allowed"]);
    exit;
}

$allowedStatuses = ["pending", "confirmed", "cancelled", "fulfilled", "no_show"];
$statusFilter = isset($_GET['status']) ? trim((string) $_GET['status']) : "";

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

$query = "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 admin_deleted = 0";

$params = [];
$types = "";
if ($statusFilter !== "") {
    if (!in_array($statusFilter, $allowedStatuses, true)) {
        http_response_code(400);
        echo json_encode(["success" => false, "message" => "Invalid status filter."]);
        exit;
    }
    $query .= " AND status = ?";
    $params[] = $statusFilter;
    $types .= "s";
}

$query .= " ORDER BY reservation_date DESC, reservation_time DESC, created_at DESC";

$stmt = $conn->prepare($query);
if (!$stmt) {
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Failed to prepare query."]);
    exit;
}

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();
$reservations = [];

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

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

$stmt->close();

echo json_encode([
    "success" => true,
    "count" => count($reservations),
    "reservations" => $reservations
]);

$conn->close();
