<?php
define('SUPPORTED_LANGS', ['en', 'fr', 'rw']);

function current_lang(): string {
    static $lang = null;
    if ($lang !== null) return $lang;
    $cookieLang = $_COOKIE['ky_lang'] ?? 'en';
    $lang = in_array($cookieLang, SUPPORTED_LANGS, true) ? $cookieLang : 'en';
    return $lang;
}

function lang_strings(string $lang): array {
    static $cache = [];
    if (isset($cache[$lang])) return $cache[$lang];
    $path = __DIR__ . '/../lang/' . $lang . '.php';
    $cache[$lang] = file_exists($path) ? require $path : [];
    return $cache[$lang];
}

/** Translate a UI string key, falling back to English, then the raw key. */
function t(string $key): string {
    $lang = current_lang();
    $strings = lang_strings($lang);
    if (isset($strings[$key])) return $strings[$key];
    $en = lang_strings('en');
    return $en[$key] ?? $key;
}

function has_chosen_lang(): bool {
    return isset($_COOKIE['ky_lang']) && in_array($_COOKIE['ky_lang'], SUPPORTED_LANGS, true);
}
