<?php
declare(strict_types=1);

function base_url(string $path = ''): string {
    static $base;
    if ($base === null) {
        $app = require __DIR__ . '/../config/app.php';
        $base = rtrim($app['base_url'], '/');
    }
    return $base . '/' . ltrim($path, '/');
}

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

function format_bytes(?int $bytes): string {
    if ($bytes === null) return '—';
    $units = ['B','KB','MB','GB','TB'];
    $i = 0;
    while ($bytes >= 1024 && $i < count($units)-1) { $bytes /= 1024; $i++; }
    return sprintf('%.1f %s', $bytes, $units[$i]);
}

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

function csrf_check(string $token): void {
    if (session_status() !== PHP_SESSION_ACTIVE) session_start();
    if (!isset($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $token)) {
        http_response_code(403);
        exit('CSRF validation failed');
    }
}
