<?php
namespace App\Services;

class TranslationService {
    protected static $translations = [];
    protected static $currentLang = 'tr';
    protected static $availableLangs = ['tr', 'en', 'fr', 'de', 'ru'];

    public static function init() {
        // Determine language from session, cookie, or browser default
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $lang = isset($_SESSION['lang']) ? $_SESSION['lang'] : 'tr';
        
        // If query param sets language, update session
        if (isset($_GET['lang']) && in_array($_GET['lang'], self::$availableLangs)) {
            $lang = $_GET['lang'];
            $_SESSION['lang'] = $lang;
        }

        self::$currentLang = $lang;
        self::loadLanguage($lang);
    }

    protected static function loadLanguage($lang) {
        $file = __DIR__ . "/../Languages/{$lang}.json";
        if (file_exists($file)) {
            $content = file_get_contents($file);
            self::$translations = json_decode($content, true) ?: [];
        } else {
            self::$translations = [];
        }
    }

    public static function t($key, $default = null) {
        if (empty(self::$translations)) {
            self::init();
        }
        return isset(self::$translations[$key]) ? self::$translations[$key] : ($default ?: $key);
    }

    public static function getCurrentLang() {
        return self::$currentLang;
    }

    public static function getAvailableLangs() {
        return self::$availableLangs;
    }
}
