<?php

declare(strict_types=1);

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

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

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;
}

function fetchScalarInt(mysqli $conn, string $query): int
{
    $result = $conn->query($query);
    if (!$result instanceof mysqli_result) {
        return 0;
    }

    $row = $result->fetch_row();
    $result->free();
    return (int) ($row[0] ?? 0);
}

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

$stats = [
    "pendingReservations" => fetchScalarInt(
        $conn,
        "SELECT COUNT(*) FROM reservations WHERE status = 'pending' AND admin_deleted = 0"
    ),
    "latestReservationId" => fetchScalarInt(
        $conn,
        "SELECT COALESCE(MAX(id), 0) FROM reservations WHERE admin_deleted = 0"
    ),
    "newContacts" => fetchScalarInt(
        $conn,
        "SELECT COUNT(*) FROM contact_messages WHERE status = 'new'"
    ),
    "latestContactId" => fetchScalarInt(
        $conn,
        "SELECT COALESCE(MAX(id), 0) FROM contact_messages"
    ),
    "userCancelledReservations" => fetchScalarInt(
        $conn,
        "SELECT COUNT(*) FROM reservations WHERE status = 'cancelled' AND cancelled_by = 'guest' AND admin_deleted = 0"
    ),
    "latestUserCancelledReservationId" => fetchScalarInt(
        $conn,
        "SELECT COALESCE(MAX(id), 0) FROM reservations WHERE status = 'cancelled' AND cancelled_by = 'guest' AND admin_deleted = 0"
    ),
];

echo json_encode([
    "success" => true,
    "stats" => $stats,
    "serverTime" => date("c"),
]);

$conn->close();
