<?php
// includes/csrf.php
declare(strict_types=1);

function csrf_token(): string {
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(32));
  }
  return $_SESSION['csrf'];
}

function csrf_verify(string $token): void {
  if (session_status() !== PHP_SESSION_ACTIVE) session_start();
  $ok = isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $token);
  if (!$ok) {
    http_response_code(419);
    exit('CSRF inválido.');
  }
}