<?php
/**
 * includes/csrf.php — CSRF token helpers for the super admin module.
 * (Previously missing; organizations.php fell back to inline definitions and
 * logged "Failed opening includes/csrf.php" warnings on every load.)
 */

if (session_status() === PHP_SESSION_NONE) session_start();

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

if (!function_exists('csrf_field')) {
    function csrf_field(): string {
        return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars(csrf_token()) . '">';
    }
}

if (!function_exists('csrf_check')) {
    function csrf_check(?string $token = null): bool {
        $token = $token ?? ($_POST['csrf_token'] ?? '');
        return is_string($token) && $token !== ''
            && hash_equals($_SESSION['csrf_token'] ?? '', $token);
    }
}
