<?php

declare(strict_types=1);

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

header("Content-Type: application/json");

if (!in_array(($_SERVER["REQUEST_METHOD"] ?? ""), ["DELETE", "POST"], true)) {
    http_response_code(405);
    echo json_encode([
        "success" => false,
        "message" => "Method not allowed",
    ]);
    exit;
}

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

$input = json_decode((string) file_get_contents("php://input"), true);
if (!is_array($input)) {
    $input = [];
}

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

if ($reservationId <= 0) {
    http_response_code(422);
    echo json_encode([
        "success" => false,
        "message" => "Invalid reservation ID.",
    ]);
    exit;
}

$lookupStmt = $conn->prepare(
    "SELECT id, admin_deleted
     FROM reservations
     WHERE id = ?
     LIMIT 1"
);
if (!$lookupStmt) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Failed to prepare reservation lookup.",
    ]);
    exit;
}

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

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

if ((int) ($reservation["admin_deleted"] ?? 0) === 1) {
    echo json_encode([
        "success" => true,
        "message" => "Reservation already deleted.",
    ]);
    exit;
}

$deleteStmt = $conn->prepare(
    "UPDATE reservations
     SET admin_deleted = 1
     WHERE id = ? AND admin_deleted = 0
     LIMIT 1"
);
if (!$deleteStmt) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Failed to prepare reservation delete.",
    ]);
    exit;
}

$deleteStmt->bind_param("i", $reservationId);
$ok = $deleteStmt->execute();
$deleteStmt->close();

if (!$ok) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Unable to delete reservation.",
    ]);
    exit;
}

echo json_encode([
    "success" => true,
    "message" => "Reservation deleted successfully.",
]);

$conn->close();
