<?php
declare(strict_types=1);

$localConfig = __DIR__ . DIRECTORY_SEPARATOR . 'site.local.php';
$local = [];
if (is_file($localConfig)) {
    $loaded = require $localConfig;
    if (is_array($loaded)) {
        $local = $loaded;
    }
}

$env = static function (string $key, mixed $default = null): mixed {
    if (function_exists('app_env')) {
        return app_env($key, $default);
    }

    $value = getenv($key);

    if ($value === false || $value === null || $value === '') {
        return $default;
    }

    return $value;
};

// Resolved through $env so this agrees with app_base_path(); reading getenv()
// directly here used to miss values provided via .env or Apache SetEnv.
$baseUrl = trim((string) ($local['base_url'] ?? $env('APP_BASE_URL', '')));

if ($baseUrl === '' || $baseUrl === '/') {
    $baseUrl = '';
} else {
    $baseUrl = '/' . trim($baseUrl, "\\/");
}

$supportedLocales = ['ar', 'en'];
$locale = (string) ($local['locale'] ?? $env('APP_LOCALE', 'ar'));

$version = function_exists('app_version')
    ? app_version()
    : trim((string) @file_get_contents(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'VERSION'));

if (preg_match('/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/', $version) !== 1) {
    throw new RuntimeException('VERSION must contain a valid semantic version.');
}

if (!in_array($locale, $supportedLocales, true)) {
    $locale = 'ar';
}

$adminPath = strtolower(trim((string) ($local['admin_path'] ?? $env('APP_ADMIN_PATH', 'admin')), "/ \t\n\r\0\x0B"));
if (preg_match('/^[a-z0-9][a-z0-9_-]{0,31}$/', $adminPath) !== 1) {
    $adminPath = 'admin';
}

return [
    'name' => (string) ($local['name'] ?? 'Quaeriva'),
    'version' => $version,
    'base_url' => $baseUrl,
    'locale' => $locale,
    'timezone' => (string) ($local['timezone'] ?? $env('APP_TIMEZONE', 'UTC')),
    'admin_path' => $adminPath,
    'supported_locales' => $supportedLocales,
    'language_switcher_enabled' => (bool) ($local['language_switcher_enabled'] ?? true),
    'browser_locale_detection' => (bool) ($local['browser_locale_detection'] ?? false),
    'theme' => [
        'primary' => (string) ($local['theme']['primary'] ?? '#0E6F5C'),
        'accent' => (string) ($local['theme']['accent'] ?? '#C99A3B'),
    ],
];
