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

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

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

$email = trim((string) ($data["email"] ?? ""));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    echo json_encode(["success" => false, "message" => "Please enter a valid email address."]);
    exit;
}

$cooldownSeconds = 60;
$cooldownStmt = $conn->prepare(
    "SELECT TIMESTAMPDIFF(SECOND, created_at, NOW()) AS elapsed_seconds
     FROM reservation_email_verifications
     WHERE email = ?
     ORDER BY id DESC
     LIMIT 1"
);

if ($cooldownStmt) {
    $cooldownStmt->bind_param("s", $email);
    $cooldownStmt->execute();
    $cooldownResult = $cooldownStmt->get_result();
    $cooldownRow = $cooldownResult ? $cooldownResult->fetch_assoc() : null;
    $cooldownStmt->close();

    if ($cooldownRow && isset($cooldownRow["elapsed_seconds"])) {
        $elapsed = (int) $cooldownRow["elapsed_seconds"];
        if ($elapsed >= 0 && $elapsed < $cooldownSeconds) {
            $remaining = $cooldownSeconds - $elapsed;
            http_response_code(429);
            echo json_encode([
                "success" => false,
                "message" => "Please wait {$remaining} seconds before requesting another code."
            ]);
            exit;
        }
    }
}

$otpCode = str_pad((string) random_int(0, 999999), 6, "0", STR_PAD_LEFT);
$otpHash = hash("sha256", $otpCode);
$otpToken = bin2hex(random_bytes(24));
$expiresAt = date("Y-m-d H:i:s", time() + (10 * 60));

$disableOldStmt = $conn->prepare(
    "UPDATE reservation_email_verifications
     SET used_at = NOW()
     WHERE email = ? AND used_at IS NULL AND verified_at IS NULL"
);
if ($disableOldStmt) {
    $disableOldStmt->bind_param("s", $email);
    $disableOldStmt->execute();
    $disableOldStmt->close();
}

$insertStmt = $conn->prepare(
    "INSERT INTO reservation_email_verifications
        (email, otp_hash, otp_token, expires_at)
     VALUES (?, ?, ?, ?)"
);

if (!$insertStmt) {
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Unable to prepare OTP request."]);
    exit;
}

$insertStmt->bind_param("ssss", $email, $otpHash, $otpToken, $expiresAt);
if (!$insertStmt->execute()) {
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "Unable to generate OTP request."]);
    $insertStmt->close();
    exit;
}

$verificationRowId = (int) $conn->insert_id;
$insertStmt->close();

$emailResult = sendReservationOtpEmail($email, $otpCode);
if (!$emailResult["success"]) {
    $rollbackStmt = $conn->prepare("DELETE FROM reservation_email_verifications WHERE id = ?");
    if ($rollbackStmt) {
        $rollbackStmt->bind_param("i", $verificationRowId);
        $rollbackStmt->execute();
        $rollbackStmt->close();
    }

    http_response_code(422);
    echo json_encode([
        "success" => false,
        "message" => "Could not send verification code to this email address.",
        "emailMessage" => $emailResult["message"]
    ]);
    $conn->close();
    exit;
}

echo json_encode([
    "success" => true,
    "message" => "Verification code sent. Please check your email.",
    "otpToken" => $otpToken,
    "expiresInSeconds" => 600
]);

$conn->close();
