<?php
declare(strict_types=1);

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

function csrf_field(): string {
  $t = htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8');
  return '<input type="hidden" name="csrf" value="'.$t.'">';
}

/**
 * Validate a CSRF token (uses provided token or POST body if omitted).
 */
function csrf_check(?string $token = null): bool {
  $sent = $token ?? (string)($_POST['csrf'] ?? '');
  $stored = (string)($_SESSION['_csrf'] ?? ($_SESSION['csrf'] ?? ''));
  return ($sent !== '' && $stored !== '' && hash_equals($stored, $sent));
}
