<?php
declare(strict_types=1);

use App\App;

function app(): App
{
    return App::get();
}

function t(string $key, $default = '', array $vars = []): string
{
    return app()->i18n()->get($key, $default, $vars);
}

function tpl(string $file, string $type = 'structure', string $site = 'main'): void
{
    $base = __DIR__ . '/../partials/';

    // very small validation
    foreach ([$file, $type, $site] as $v) {
        if (preg_match('/[^a-zA-Z0-9_\-]/', $v)) {
            echo "<!-- tpl(): invalid parameter -->";
            return;
        }
    }

    if ($type === 'landing') {
        $path = $base . "landing/$site/$file.php";
    } else {
        $path = $base . "structure/$file.php";
    }

    if (file_exists($path)) {
        include $path;
    } else {
        echo "<!-- tpl(): not found: $path -->";
    }
}

function app_primary_domain(): string
{
    if (defined('APP_DOMAIN_PRIMARY')) {
        return APP_DOMAIN_PRIMARY;
    }
    if (defined('APP_DOMAIN_NAME')) {
        return APP_DOMAIN_NAME;
    }
    return $_SERVER['HTTP_HOST'] ?? '';
}

function app_fakecheck_domain(): string
{
    if (defined('APP_DOMAIN_FAKECHECK')) {
        return APP_DOMAIN_FAKECHECK;
    }
    return app_primary_domain();
}

function asset_styles(): void
{
    $styles = app()->assets()->styles();

    // simple priority order
    $order = ['early' => 0, 'normal' => 1, 'late' => 2];
    usort($styles, fn($a,$b) => ($order[$a['priority']] ?? 1) <=> ($order[$b['priority']] ?? 1));

    foreach ($styles as $s) {
        $href = $s['href'];
        $v    = $s['version'];
        if ($v !== null && $v !== '') {
            $sep  = (str_contains($href, '?') ? '&' : '?');
            $href = $href . $sep . 'v=' . rawurlencode((string)$v);
        }
        echo '<link rel="stylesheet" href="' . htmlspecialchars($href, ENT_QUOTES) . '">' . "\n";
    }
}

function asset_scripts(string $pos = 'footer'): void
{
    $scripts = ($pos === 'header') ? app()->assets()->headerScripts() : app()->assets()->footerScripts();

    foreach ($scripts as $s) {
        $src = $s['src'];
        $v   = $s['version'];
        if ($v !== null && $v !== '') {
            $sep = (str_contains($src, '?') ? '&' : '?');
            $src = $src . $sep . 'v=' . rawurlencode((string)$v);
        }

        $attrs = '';
        if (!empty($s['defer'])) $attrs .= ' defer';
        if (!empty($s['async'])) $attrs .= ' async';

        echo '<script src="' . htmlspecialchars($src, ENT_QUOTES) . '"' . $attrs . '></script>' . "\n";
    }
}

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