<?php
declare(strict_types=1);

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

function csrf_verify(?string $token): void {
  $sess = $_SESSION['csrf'] ?? '';
  if (!$token || !$sess || !hash_equals($sess, $token)) {
    http_response_code(400);
    echo "CSRF inválido";
    exit;
  }
}

function e(string $s): string {
  return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function now_iso(): string {
  return (new DateTimeImmutable('now'))->format(DateTimeInterface::ATOM);
}

function require_post(): void {
  if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "Método no permitido";
    exit;
  }
}
