<?php

const MESSAGE_SUPPORTED_LOCALES = ['vn', 'eng'];

function determine_locale(): string
{
    if (session_status() === PHP_SESSION_NONE) {
        throw new RuntimeException('Session must be started before loading messages.');
    }

    if (isset($_GET['lang']) && is_string($_GET['lang'])) {
        $requested = strtolower(trim($_GET['lang']));
        if (in_array($requested, MESSAGE_SUPPORTED_LOCALES, true)) {
            $_SESSION['lang'] = $requested;
            return $requested;
        }
    }

    if (isset($_SESSION['lang']) && in_array($_SESSION['lang'], MESSAGE_SUPPORTED_LOCALES, true)) {
        return $_SESSION['lang'];
    }

    $envLocale = getenv('APP_LOCALE');
    if (is_string($envLocale)) {
        $envLocale = strtolower(trim($envLocale));
        if (in_array($envLocale, MESSAGE_SUPPORTED_LOCALES, true)) {
            $_SESSION['lang'] = $envLocale;
            return $envLocale;
        }
    }

    return 'vn';
}

function load_messages(?string $locale = null): array
{
    static $cache = [];

    $locale = $locale ?? determine_locale();

    if (isset($cache[$locale])) {
        return $cache[$locale];
    }

    $filename = __DIR__ . '/../lang/message_' . $locale . '.php';
    if (!is_file($filename)) {
        $filename = __DIR__ . '/../lang/message_vn.php';
        $locale = 'vn';
    }

    $messages = require $filename;
    if (!is_array($messages)) {
        throw new RuntimeException('Message file must return an array.');
    }

    $cache[$locale] = $messages;

    return $messages;
}

function message(string $key, ?string $locale = null): string
{
    $messages = load_messages($locale);
    return $messages[$key] ?? $key;
}
