<?php

namespace App\Helpers;

use App\Core\Session;

class Lang
{
    private static array $translations = [];
    private static string $currentLang = 'en';

    public static function load(): void
    {
        if (!Session::has('lang')) {
            $detected = self::detectBrowserLang();
            Session::set('lang', $detected);
        }

        self::$currentLang = Session::get('lang', 'en');
        $path = __DIR__ . "/../../lang/" . self::$currentLang . ".php";

        self::$translations = [];
        if (file_exists($path)) {
            self::$translations = (function() use ($path) { return require $path; })();
        }
    }

    private static function detectBrowserLang(): string
    {
        if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            return 'en';
        }

        $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        $primary = substr($langs[0], 0, 2);

        $supported = ['en', 'ua', 'ru', 'pl'];
        
        if ($primary === 'uk') return 'ua';
        
        return in_array($primary, $supported) ? $primary : 'en';
    }

    public static function t(string $key): string
    {
        $sessionLang = \App\Core\Session::get('lang', 'en');
        if (empty(self::$translations) || self::$currentLang !== $sessionLang) {
            self::load();
        }
        return self::$translations[$key] ?? $key;
    }

    public static function set(string $lang): void
    {
        $supported = ['en', 'ua', 'ru', 'pl'];
        if (!in_array($lang, $supported)) {
            $lang = 'en';
        }
        
        Session::set('lang', $lang);
        self::load();
    }

    public static function get(): string
    {
        if (!Session::has('lang')) self::load();
        return Session::get('lang', 'en');
    }

    public static function detected(): string
    {
        return self::detectBrowserLang();
    }
}
