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

function respondCancellation(bool $asJson, int $statusCode, string $title, string $message): void
{
    http_response_code($statusCode);

    if ($asJson) {
        echo json_encode([
            "success" => $statusCode >= 200 && $statusCode < 300,
            "title" => $title,
            "message" => $message
        ]);
        return;
    }

    header("Content-Type: text/html; charset=UTF-8");
    $safeTitle = htmlspecialchars($title, ENT_QUOTES, "UTF-8");
    $safeMessage = htmlspecialchars($message, ENT_QUOTES, "UTF-8");
    echo "<!doctype html>
<html lang='en'>
<head>
  <meta charset='utf-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <title>{$safeTitle}</title>
  <style>
    body { font-family: Arial, sans-serif; background: #f8f5ee; color: #2d2b29; margin: 0; }
    .wrap { max-width: 640px; margin: 6rem auto; background: #ffffff; padding: 2rem; border-radius: 12px; border: 1px solid #e2ddcf; }
    h1 { margin-top: 0; font-size: 1.4rem; }
    p { line-height: 1.6; }
  </style>
</head>
<body>
  <div class='wrap'>
    <h1>{$safeTitle}</h1>
    <p>{$safeMessage}</p>
  </div>
</body>
</html>";
}

$acceptHeader = strtolower($_SERVER["HTTP_ACCEPT"] ?? "");
$asJson = strpos($acceptHeader, "application/json") !== false || (isset($_GET["format"]) && $_GET["format"] === "json");
$token = isset($_GET["token"]) ? trim((string) $_GET["token"]) : "";

if ($token === "") {
    respondCancellation($asJson, 400, "Missing token", "No cancellation token was provided.");
    exit;
}

$stmt = $conn->prepare("SELECT id, status FROM reservations WHERE cancellation_token = ?");
if (!$stmt) {
    respondCancellation($asJson, 500, "Server error", "Unable to process your cancellation request right now.");
    exit;
}

$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();
$reservation = $result->fetch_assoc();
$stmt->close();

if (!$reservation) {
    respondCancellation($asJson, 404, "Booking not found", "This cancellation link is invalid or expired.");
    exit;
}

if ($reservation["status"] === "cancelled") {
    respondCancellation($asJson, 200, "Already cancelled", "This booking has already been cancelled.");
    exit;
}

if ($reservation["status"] === "fulfilled" || $reservation["status"] === "no_show") {
    respondCancellation($asJson, 409, "Cannot cancel", "This booking can no longer be cancelled online. Please contact the restaurant by phone.");
    exit;
}

$updateStmt = $conn->prepare("UPDATE reservations SET status = 'cancelled', cancelled_by = 'guest' WHERE id = ?");
if (!$updateStmt) {
    respondCancellation($asJson, 500, "Server error", "Unable to update booking status.");
    exit;
}

$reservationId = (int) $reservation["id"];
$updateStmt->bind_param("i", $reservationId);
$updateStmt->execute();
$updateStmt->close();

respondCancellation($asJson, 200, "Booking cancelled", "Your booking has been cancelled successfully.");
$conn->close();

