<?php
declare(strict_types=1);

// Small global helpers used by pages and templates.

function config(string $key, mixed $default = null): mixed
{
    return $GLOBALS['config'][$key] ?? $default;
}

/** HTML-escape. Use for every value printed into a page. */
function e(mixed $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function url(string $path = '/'): string
{
    return rtrim((string) config('base_path', ''), '/') . $path;
}

function redirect(string $path): never
{
    header('Location: ' . url($path), true, 303);
    exit;
}

function flash(string $type, string $message): void
{
    $_SESSION['flash'][] = ['type' => $type, 'msg' => $message];
}

function take_flashes(): array
{
    $f = $_SESSION['flash'] ?? [];
    unset($_SESSION['flash']);
    return $f;
}

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

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

function csrf_ok(): bool
{
    $sent = $_POST['_csrf'] ?? '';
    return is_string($sent) && $sent !== '' && hash_equals(csrf_token(), $sent);
}

function post_str(string $name, int $maxLen = 200): string
{
    $v = $_POST[$name] ?? '';
    return is_string($v) ? mb_substr(trim($v), 0, $maxLen) : '';
}

function post_int(string $name): int
{
    $v = $_POST[$name] ?? '';
    return is_string($v) && preg_match('/^\d{1,9}$/', $v) ? (int) $v : 0;
}

function client_ip(): string
{
    if (config('trust_cloudflare_ip') && !empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return (string) $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
    return (string) ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
}

function now(): int
{
    return time();
}

/** "1h 05m", "12m", "45s" */
function duration(int $seconds): string
{
    if ($seconds <= 0) {
        return 'now';
    }
    $h = intdiv($seconds, 3600);
    $m = intdiv($seconds % 3600, 60);
    if ($h > 0) {
        return sprintf('%dh %02dm', $h, $m);
    }
    if ($m > 0) {
        return $m . 'm';
    }
    return $seconds . 's';
}

function fmt_stat(float|string $v): string
{
    return number_format((float) $v, 2);
}

function initials(string $name): string
{
    $words = preg_split('/[\s\-]+/', $name) ?: [];
    $out = '';
    foreach ($words as $w) {
        if ($w !== '') {
            $out .= mb_strtoupper(mb_substr($w, 0, 1));
        }
        if (mb_strlen($out) >= 2) {
            break;
        }
    }
    return $out ?: '?';
}

/** Full https address of a page, for sitemaps and link previews. */
function abs_url(string $path = '/'): string
{
    $site = rtrim((string) (config('site_url') ?: ('https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost'))), '/');
    return $site . url($path);
}
