<?php
/**
 * includes/csrf.php — CSRF token + escaping helpers for the super admin module.
 * Each function is guarded individually: several pages historically bundled
 * their own fallbacks inside a single csrf_token guard, so this file must
 * provide the full set (including csrf_verify and h) to avoid undefined-
 * function fatals when it is present.
 */

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);
    }
}

if (!function_exists('csrf_verify')) {
    function csrf_verify(): bool {
        return !empty($_POST['csrf_token']) && !empty($_SESSION['csrf_token'])
            && hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']);
    }
}

// HTML-escape helper used throughout the admin pages. Defined here because
// several pages previously bundled it inside their csrf_token fallback block —
// once this file exists, that block is skipped, so h() must live here too.
if (!function_exists('h')) {
    function h(?string $v): string { return htmlspecialchars($v ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}
