<?php

declare(strict_types=1);

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

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

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

$session = customerAuthRequireSession($conn);
$input = customerAuthReadJsonInput();

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

$reservationIdRaw = $input["id"] ?? $_POST["id"] ?? 0;
$reservationId = is_numeric($reservationIdRaw) ? (int) $reservationIdRaw : 0;

if ($reservationId <= 0) {
    customerAuthJsonResponse(422, [
        "success" => false,
        "message" => "Invalid reservation id.",
    ]);
}

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

$lookupStmt = $conn->prepare(
    "SELECT id, status, full_name, reservation_date, reservation_time, guests
     FROM reservations
     WHERE id = ?
       AND email = ?
       AND user_deleted = 0
       AND admin_deleted = 0
     LIMIT 1"
);
if (!$lookupStmt) {
    customerAuthJsonResponse(500, [
        "success" => false,
        "message" => "Failed to prepare reservation lookup.",
    ]);
}

$lookupStmt->bind_param("is", $reservationId, $email);
$lookupStmt->execute();
$lookupResult = $lookupStmt->get_result();
$reservation = $lookupResult ? $lookupResult->fetch_assoc() : null;
$lookupStmt->close();

if (!$reservation) {
    customerAuthJsonResponse(404, [
        "success" => false,
        "message" => "Reservation not found.",
    ]);
}

$status = (string) ($reservation["status"] ?? "");
if ($status === "cancelled") {
    customerAuthJsonResponse(200, [
        "success" => true,
        "message" => "Reservation is already cancelled.",
    ]);
}

if ($status === "fulfilled" || $status === "no_show") {
    customerAuthJsonResponse(409, [
        "success" => false,
        "message" => "This reservation can no longer be cancelled.",
    ]);
}

$cancelStatus = "cancelled";
$cancelledBy = "guest";
$updateStmt = $conn->prepare(
    "UPDATE reservations
     SET status = ?, cancelled_by = ?
     WHERE id = ?
       AND email = ?
       AND user_deleted = 0
       AND admin_deleted = 0"
);
if (!$updateStmt) {
    customerAuthJsonResponse(500, [
        "success" => false,
        "message" => "Failed to prepare reservation update.",
    ]);
}

$updateStmt->bind_param("ssis", $cancelStatus, $cancelledBy, $reservationId, $email);
$ok = $updateStmt->execute();
$updateStmt->close();

if (!$ok) {
    customerAuthJsonResponse(500, [
        "success" => false,
        "message" => "Unable to cancel reservation.",
    ]);
}

$adminReservationsUrl = rtrim((string) ((require __DIR__ . "/mail_config.php")["frontend_url"] ?? ""), "/") . "/admin/reservations";
adminNotifierSendEvent($conn, "Reservation cancelled by user", [
    "Reservation ID" => (string) $reservationId,
    "Guest Name" => (string) ($reservation["full_name"] ?? ""),
    "Email" => $email,
    "Date" => (string) ($reservation["reservation_date"] ?? ""),
    "Time" => (string) ($reservation["reservation_time"] ?? ""),
    "Guests" => (string) ((int) ($reservation["guests"] ?? 0)),
    "Cancelled By" => "guest",
    "Admin Page" => $adminReservationsUrl,
]);

customerAuthJsonResponse(200, [
    "success" => true,
    "message" => "Reservation cancelled successfully.",
]);
