<?php
class Lang
{
    private static array $translations = [];
    private static bool $loaded = false;

    public static function get(string $key, array $replacements = []): string
    {
        self::loadIfNeeded();
        $lang = self::current();

        $value = self::$translations[$lang][$key] ?? self::$translations['en'][$key] ?? $key;

        foreach ($replacements as $k => $v) {
            $value = str_replace(':' . $k, $v, $value);
        }

        return $value;
    }

    public static function current(): string
    {
        return Session::get('app_language', 'en');
    }

    public static function set(string $code): void
    {
        Session::set('app_language', $code);
        self::$loaded = false;
    }

    public static function isRtl(): bool
    {
        return self::current() === 'ar';
    }

    public static function direction(): string
    {
        return self::isRtl() ? 'rtl' : 'ltr';
    }

    private static function loadIfNeeded(): void
    {
        if (self::$loaded) return;

        // Load core translations
        $enFile = ROOT_PATH . '/views/lang/en.php';
        $arFile = ROOT_PATH . '/views/lang/ar.php';

        self::$translations['en'] = file_exists($enFile) ? (require $enFile) : [];
        self::$translations['ar'] = file_exists($arFile) ? (require $arFile) : [];

        // Load module translations
        $modulesPath = ROOT_PATH . '/modules';
        if (is_dir($modulesPath)) {
            foreach (scandir($modulesPath) as $dir) {
                if ($dir === '.' || $dir === '..') continue;
                $modEnFile = $modulesPath . '/' . $dir . '/lang/en.php';
                $modArFile = $modulesPath . '/' . $dir . '/lang/ar.php';
                if (file_exists($modEnFile)) {
                    $modTranslations = require $modEnFile;
                    self::$translations['en'] = array_merge(self::$translations['en'], $modTranslations);
                }
                if (file_exists($modArFile)) {
                    $modTranslations = require $modArFile;
                    self::$translations['ar'] = array_merge(self::$translations['ar'], $modTranslations);
                }
            }
        }

        self::$loaded = true;
    }
}