<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

function csrf_token(): string
{
    if (empty($_SESSION['_csrf_token'])) {
        $_SESSION['_csrf_token'] = bin2hex(random_bytes(32));
    }

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

function csrf_input(): string
{
    return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
}

function verify_csrf(?string $token): bool
{
    $sessionToken = $_SESSION['_csrf_token'] ?? '';

    return is_string($token)
        && is_string($sessionToken)
        && $sessionToken !== ''
        && hash_equals($sessionToken, $token);
}

function require_valid_csrf(?string $token = null): void
{
    $token ??= $_POST['_csrf'] ?? null;

    if (!verify_csrf($token)) {
        abort_request(419, 'Security check failed', 'The form token is invalid or expired. Reload the page and try again.');
    }
}
