<?php
function csrfToken(): string {
    if (!isset($_SESSION["csrf"]) || !is_string($_SESSION["csrf"]) || strlen($_SESSION["csrf"]) < 32) {
        $_SESSION["csrf"] = bin2hex(random_bytes(32));
    }
    return $_SESSION["csrf"];
}

function validateCsrf(?string $token): bool {
    if (!$token || !isset($_SESSION["csrf"])) {
        return false;
    }
    return hash_equals($_SESSION["csrf"], $token);
}

function requireCsrf(?string $token): void {
    if (!validateCsrf($token)) {
        http_response_code(403);
        header("Content-Type: application/json; charset=utf-8");
        echo json_encode(["success" => false, "error" => "invalid_csrf"]);
        exit;
    }
}

function requireCsrfFromPayload(array $data, string $key = "csrf_token"): bool {
    $token = $data[$key] ?? null;
    if (!is_string($token)) {
        return false;
    }
    return validateCsrf($token);
}
