<?php
function getPreferredLanguage(array $availableLanguages, string $httpAcceptLanguage): string {
    $langs = explode(',', $httpAcceptLanguage);

    foreach ($langs as $lang) {
        $langCode = strtolower(substr(trim($lang), 0, 2));
        if (in_array($langCode, $availableLanguages)) {
            return $langCode;
        }
    }
    return 'en';
}

$availableLanguages = ['en', 'no'];

// URL override has priority
if (isset($_GET['lang']) && in_array($_GET['lang'], $availableLanguages)) {
    $_SESSION['lang'] = $_GET['lang'];
}

// Set lang based on browser if not set already
if (!isset($_SESSION['lang'])) {
    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
        $_SESSION['lang'] = getPreferredLanguage($availableLanguages, $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    } else {
        $_SESSION['lang'] = 'en';
    }
}

$lang = $_SESSION['lang'];
$langFile = __DIR__ . "/{$lang}.php";
$translations = [];

if (file_exists($langFile)) {
    $translations = include $langFile;
} else {
    $translations = include __DIR__ . '/en.php';
}

function t(string $key): string {
    global $translations;
    return htmlspecialchars($translations[$key] ?? $key);
}
?>
