<?php
declare(strict_types=1);

function mocker_csrf_ensure(): void
{
    if (!isset($_SESSION['mocker_csrf']) || !is_string($_SESSION['mocker_csrf']) || strlen($_SESSION['mocker_csrf']) < 32) {
        $_SESSION['mocker_csrf'] = bin2hex(random_bytes(32));
    }
}

function mocker_csrf_token(): string
{
    mocker_csrf_ensure();

    return (string) $_SESSION['mocker_csrf'];
}

function mocker_require_csrf_post(): void
{
    $m = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
    if (!in_array($m, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
        return;
    }
    $hdr = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    if (!is_string($hdr) || $hdr === '') {
        http_response_code(403);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok' => false, 'error' => 'csrf'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    mocker_csrf_ensure();
    if (!hash_equals((string) $_SESSION['mocker_csrf'], $hdr)) {
        http_response_code(403);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok' => false, 'error' => 'csrf'], JSON_UNESCAPED_UNICODE);
        exit;
    }
}
