<?php
// CSRF token issue + verify. Every state-changing form/fetch call embeds
// this token; every state-changing request verifies it server-side.
// Requires an active session (includes/auth.php starts one before this
// file is used).

/** Returns the current session's CSRF token, creating one if needed. */
function csrf_token(): string
{
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['csrf_token'];
}

/** Hidden input HTML to embed in every state-changing form. */
function csrf_field(): string
{
    return '<input type="hidden" name="csrf_token" value="' . e(csrf_token()) . '">';
}

/** Verifies a submitted token against the session's token. */
function csrf_verify(?string $token): bool
{
    return !empty($_SESSION['csrf_token']) && !empty($token) && hash_equals($_SESSION['csrf_token'], $token);
}
