<?php
/**
 * CSRF token helpers. Every POST form must include csrf_field() and
 * the handler must call csrf_check_or_die().
 */

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

function csrf_field(): string
{
    return '<input type="hidden" name="_csrf" value="' . htmlspecialchars(csrf_token(), ENT_QUOTES) . '">';
}

function csrf_check(): bool
{
    start_session();
    $sent = $_POST['_csrf'] ?? '';
    return !empty($_SESSION['_csrf']) && hash_equals($_SESSION['_csrf'], $sent);
}

function csrf_check_or_die(): void
{
    if (!csrf_check()) {
        http_response_code(419);
        exit('CSRF token mismatch. Please refresh and try again.');
    }
}
