<?php
/// file: app/Helpers/functions.php

declare(strict_types=1);

use App\Core\App;
use App\Core\Config;
use App\Core\Session;

function app(): ?App
{
    return $GLOBALS['saneksa_app'] ?? null;
}

function base_url(): string
{
    static $base;
    if ($base !== null) {
        return $base;
    }
    $script = $_SERVER['SCRIPT_NAME'] ?? '/index.php';
    $base = rtrim(str_replace('\\', '/', dirname($script)), '/');
    return $base;
}

function url(string $path): string
{
    $p = '/' . ltrim($path, '/');
    $b = base_url();
    return ($b === '' ? '' : $b) . $p;
}

function asset(string $path): string
{
    $rel = '/assets/' . ltrim($path, '/');
    $abs = dirname(__DIR__, 2) . '/public' . $rel;
    $v = is_file($abs) ? (string) filemtime($abs) : '0';

    return url($rel) . '?v=' . rawurlencode($v);
}

/** Public URL for the configured default cover when a path is missing or invalid. */
function default_cover_fallback_url(): string
{
    $p = \App\Models\SiteSetting::get('default_placeholder_image');
    if (is_string($p) && $p !== '' && str_starts_with($p, '/')) {
        return url($p);
    }

    return asset('images/placeholder.svg');
}

/** @param array<string, mixed> $replace */
function __(string $key, array $replace = []): string
{
    $locale = Session::get('locale') ?? Config::get('app.locale', 'en');
    if (! is_string($locale)) {
        $locale = 'en';
    }
    $file = dirname(__DIR__, 2) . '/lang/' . $locale . '/messages.php';
    if (! is_file($file)) {
        $file = dirname(__DIR__, 2) . '/lang/en/messages.php';
    }
    /** @var array<string, string> $messages */
    $messages = is_file($file) ? require $file : [];
    $text = $messages[$key] ?? $key;
    foreach ($replace as $k => $v) {
        $text = str_replace(':' . $k, (string) $v, $text);
    }
    return $text;
}

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

function old(string $key, ?string $default = null): ?string
{
    $old = Session::get('_old_input');
    if (is_array($old) && isset($old[$key]) && is_string($old[$key])) {
        return $old[$key];
    }
    return $default;
}
