<?php
/**
 * CSRF tokens for state-changing POST forms (session-bound).
 */
declare(strict_types=1);

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

    return $_SESSION['_csrf_token'];
}

/** HTML hidden input name="_csrf" */
function nazareth_csrf_field(): string
{
    $t = htmlspecialchars(nazareth_csrf_token(), ENT_QUOTES, 'UTF-8');

    return '<input type="hidden" name="_csrf" value="' . $t . '">';
}

function nazareth_csrf_validate(?string $posted = null): bool
{
    $posted = $posted ?? ($_POST['_csrf'] ?? '');
    $stored = $_SESSION['_csrf_token'] ?? '';
    if ($stored === '' || !is_string($posted) || $posted === '') {
        return false;
    }

    return hash_equals($stored, $posted);
}
