<?php
declare(strict_types=1);

namespace App\Core {
    function e(mixed $value): string
    {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }

    function url(string $path = '', ?string $area = null): string
    {
        $config = $GLOBALS['zalorox_config'] ?? [];

        return DomainRouter::url($path === '' ? '/' : $path, $area, $config);
    }

    function asset(string $path): string
    {
        return url('/assets/' . ltrim($path, '/'));
    }

    function logo_asset(string $area = 'main'): ?string
    {
        $area = strtolower(trim($area));
        $settingKeys = match ($area) {
            'music' => ['music_logo'],
            'studio' => ['studio_logo'],
            'zpanel' => ['zpanel_logo', 'zpanel_logo_path'],
            default => ['site_logo', 'logo_path'],
        };
        $files = match ($area) {
            'music' => ['logo-music.png', 'logo-music.gif', 'logo.gif', 'logo.png'],
            'studio' => ['logo-studio.png', 'logo-studio.gif', 'logo.gif', 'logo.png'],
            'zpanel' => ['logo-zpanel.png', 'logo-zpanel.gif', 'logo.gif', 'logo.png'],
            default => ['logo.gif', 'logo.png'],
        };

        foreach ($settingKeys as $key) {
            $settingPath = setting_public_path($key);
            if ($settingPath !== null) {
                return $settingPath;
            }
        }

        $base = defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 2);
        foreach ($files as $file) {
            if (is_file($base . '/public/assets/img/' . $file)) {
                return '/assets/img/' . $file;
            }
        }

        return null;
    }

    function favicon_asset(): ?string
    {
        $settingPath = setting_public_path('favicon');
        if ($settingPath !== null) {
            return $settingPath;
        }

        $base = defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 2);
        foreach (glob($base . '/public/assets/img/Fav-*.png') ?: [] as $file) {
            if (is_file($file)) {
                return '/assets/img/' . basename($file);
            }
        }

        foreach (['favicon.png', 'favicon.ico'] as $file) {
            if (is_file($base . '/public/assets/img/' . $file)) {
                return '/assets/img/' . $file;
            }
        }

        return null;
    }

    function site_setting(string $key, mixed $default = ''): mixed
    {
        static $cache = [];

        if (array_key_exists($key, $cache)) {
            return $cache[$key];
        }

        try {
            $cache[$key] = (new \App\Models\Setting())->getByKey($key, $default);
        } catch (\Throwable) {
            $cache[$key] = $default;
        }

        return $cache[$key];
    }

    function setting_public_path(string $key): ?string
    {
        $value = trim((string) site_setting($key, ''));
        if ($value === '') {
            return null;
        }

        if (!str_starts_with($value, '/assets/') && !str_starts_with($value, '/uploads/')) {
            return null;
        }

        $base = defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 2);
        $absolute = realpath($base . '/public' . $value);
        $publicRoot = realpath($base . '/public');
        if ($absolute === false || $publicRoot === false) {
            return null;
        }

        $publicRoot = rtrim(str_replace('\\', '/', $publicRoot), '/') . '/';
        $absolute = str_replace('\\', '/', $absolute);
        if (!str_starts_with($absolute, $publicRoot)) {
            return null;
        }

        return $value;
    }

    function upload_url(string $path): string
    {
        return url('/uploads/' . ltrim($path, '/'));
    }

    function __(string $key, array $replace = []): string
    {
        return Lang::get($key, $replace);
    }

    function t(string $key, array $replace = []): string
    {
        return __($key, $replace);
    }

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

namespace {
    if (!function_exists('__')) {
        function __(string $key, array $replace = []): string
        {
            return \App\Core\Lang::get($key, $replace);
        }
    }
}
