<?php

function env(string $key, mixed $default = null): mixed
{
    static $vars = null;
    if ($vars === null) {
        $vars = [];
        $f = ROOT . '/.env';
        if (\file_exists($f)) {
            foreach (\file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
                $line = \trim($line);
                if ($line === '' || $line[0] === '#' || !\str_contains($line, '=')) continue;
                [$k, $v] = \explode('=', $line, 2);
                $k = \trim($k);
                $v = \trim($v);                    // strip whitespace incluindo \r
                // Remover aspas envolventes se existirem
                if (\strlen($v) >= 2) {
                    $q = $v[0];
                    if (($q === '"' || $q === "'") && $v[-1] === $q) {
                        $v = \substr($v, 1, -1);
                    }
                }
                $vars[$k] = $v;
            }
        }
    }
    return $vars[$key] ?? $default;
}

function config(string $key, mixed $default = null): mixed
{
    static $cache = [];
    [$file, $rest] = [\strstr($key, '.', true), \strstr($key, '.') ?: ''];
    if (!isset($cache[$file])) {
        $p = ROOT . "/config/{$file}.php";
        $cache[$file] = \file_exists($p) ? require $p : [];
    }
    if (!$rest) return $cache[$file];
    $val = $cache[$file];
    foreach (\explode('.', \ltrim($rest, '.')) as $part) {
        if (!\is_array($val) || !\array_key_exists($part, $val)) return $default;
        $val = $val[$part];
    }
    return $val;
}

function base_url(string $path = ''): string
{
    $base = \rtrim(config('app.url'), '/');
    return $base . '/' . \ltrim($path, '/');
}

function redirect(string $url): never { \header('Location: ' . $url); exit; }
function abort(int $code = 404): never { \http_response_code($code); exit; }
function h(mixed $v): string { return \htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function money(float $v): string { return \number_format($v, 2, ',', '.') . '€'; }

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="' . csrf_token() . '">'; }
function csrf_ok(): bool { return \hash_equals(csrf_token(), $_POST['_csrf'] ?? ''); }

function flash(string $key, mixed $val = null): mixed
{
    if ($val !== null) { $_SESSION['flash'][$key] = $val; return null; }
    $v = $_SESSION['flash'][$key] ?? null;
    unset($_SESSION['flash'][$key]);
    return $v;
}

function old(string $k, string $d = ''): string { return h($_SESSION['_old'][$k] ?? $d); }

function slug(string $s): string
{
    $s = \mb_strtolower($s, 'UTF-8');
    $s = \strtr($s, ['á'=>'a','à'=>'a','â'=>'a','ã'=>'a','é'=>'e','è'=>'e','ê'=>'e',
                      'í'=>'i','ì'=>'i','ó'=>'o','ò'=>'o','ô'=>'o','õ'=>'o',
                      'ú'=>'u','ù'=>'u','ç'=>'c','ñ'=>'n']);
    $s = \preg_replace('/[^a-z0-9\s-]/', '', $s);
    return \preg_replace('/[\s-]+/', '-', \trim($s));
}

// Nome de ficheiro sem extensão — para mostrar ao utilizador
function fname(string $filename): string
{
    return \pathinfo($filename, PATHINFO_FILENAME);
}

// URL seguro para ficheiro com espaços
function imgurl(string ...$parts): string
{
    $segments = \array_map(fn($p) => \rawurlencode($p), $parts);
    return base_url('imgs/' . \implode('/', $segments));
}

// Ler configuração da tabela _settings
function setting(string $key, string $default = ''): string
{
    static $cache = null;
    if ($cache === null) {
        try {
            $rows  = \App\Core\Database::all("SELECT skey, svalue FROM _settings");
            $cache = \array_column($rows, 'svalue', 'skey');
        } catch(\Throwable $e) {
            $cache = [];
        }
    }
    return $cache[$key] ?? $default;
}

// Nonce CSP para scripts inline seguros
function nonce(): string
{
    return $GLOBALS['_GLOBALS_CSP_NONCE'] ?? '';
}

// Enviar header CSP com nonce (chamado no layout)
function send_csp(): void
{
    $n = nonce();
    if (!$n) return;
    \header("Content-Security-Policy: " .
        "default-src 'self'; " .
        "script-src 'self' 'nonce-{$n}'; " .
        "style-src 'self' 'unsafe-inline'; " .
        "img-src 'self' data:; " .
        "font-src 'self'; " .
        "connect-src 'self'; " .
        "frame-ancestors 'none';"
    );
}
