<?php
require_once __DIR__ . '/functions.php';

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

function csrf_field(): string {
  $t = csrf_token();
  return '<input type="hidden" name="csrf" value="' . e($t) . '">';
}

function csrf_verify() {
  session_boot();
  $sent = $_POST['csrf'] ?? '';
  $real = $_SESSION['csrf'] ?? '';
  if (!$sent || !$real || !hash_equals($real, $sent)) {
    http_response_code(419);
    die('Invalid CSRF token');
  }
}
