<?php
/**
 * Language Manager Class
 * Handles multi-language support with automatic detection
 */

class LanguageManager {
    
    private $currentLang;
    private $translations;
    private $availableLanguages = [
        'en' => 'English',
        'fr' => 'Français',
        'de' => 'Deutsch',
        'es' => 'Español',
        'pt' => 'Português',
        'no' => 'Norsk'
    ];
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->currentLang = $this->detectLanguage();
        $this->loadTranslations();
    }
    
    /**
     * Detect user's language
     */
    private function detectLanguage() {
        // Check if language is set in session
        if (isset($_SESSION['language'])) {
            return $_SESSION['language'];
        }
        
        // Check if language is set in GET parameter
        if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $this->availableLanguages)) {
            $_SESSION['language'] = $_GET['lang'];
            return $_GET['lang'];
        }
        
        // Auto-detect from browser
        if (AUTO_DETECT_LANGUAGE && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $browserLang = $this->parseBrowserLanguage($_SERVER['HTTP_ACCEPT_LANGUAGE']);
            if (array_key_exists($browserLang, $this->availableLanguages)) {
                return $browserLang;
            }
        }
        
        // Default language
        return DEFAULT_LANGUAGE;
    }
    
    /**
     * Parse browser Accept-Language header
     */
    private function parseBrowserLanguage($acceptLanguage) {
        $languages = explode(',', $acceptLanguage);
        
        foreach ($languages as $language) {
            $lang = strtolower(substr(trim($language), 0, 2));
            
            // Map some language codes
            $langMap = [
                'en' => 'en',
                'fr' => 'fr',
                'de' => 'de',
                'es' => 'es',
                'pt' => 'pt',
                'no' => 'no',
                'nb' => 'no', // Norwegian Bokmål
                'nn' => 'no'  // Norwegian Nynorsk
            ];
            
            if (isset($langMap[$lang])) {
                return $langMap[$lang];
            }
        }
        
        return 'en';
    }
    
    /**
     * Load translations for current language
     */
    private function loadTranslations() {
        $langFile = LANGUAGES_PATH . '/' . $this->currentLang . '.php';
        
        if (file_exists($langFile)) {
            include $langFile;
            $this->translations = isset($lang) ? $lang : [];
        } else {
            // Fallback to English
            $langFile = LANGUAGES_PATH . '/en.php';
            if (file_exists($langFile)) {
                include $langFile;
                $this->translations = isset($lang) ? $lang : [];
            }
        }
    }
    
    /**
     * Get translation
     */
    public function get($key, $default = '') {
        $keys = explode('.', $key);
        $value = $this->translations;
        
        foreach ($keys as $k) {
            if (isset($value[$k])) {
                $value = $value[$k];
            } else {
                return $default ?: $key;
            }
        }
        
        return $value;
    }
    
    /**
     * Get current language code
     */
    public function getCurrentLanguage() {
        return $this->currentLang;
    }
    
    /**
     * Get current language name
     */
    public function getCurrentLanguageName() {
        return $this->availableLanguages[$this->currentLang];
    }
    
    /**
     * Get all available languages
     */
    public function getAvailableLanguages() {
        return $this->availableLanguages;
    }
    
    /**
     * Set language manually
     */
    public function setLanguage($langCode) {
        if (array_key_exists($langCode, $this->availableLanguages)) {
            $this->currentLang = $langCode;
            $_SESSION['language'] = $langCode;
            $this->loadTranslations();
            return true;
        }
        return false;
    }
    
    /**
     * Get all translations
     */
    public function getAll() {
        return $this->translations;
    }
}

/**
 * Helper function to get language manager instance
 */
function getLangManager() {
    static $langManager = null;
    
    if ($langManager === null) {
        $langManager = new LanguageManager();
    }
    
    return $langManager;
}

/**
 * Helper function to get translation
 */
function __($key, $default = '') {
    return getLangManager()->get($key, $default);
}

?>
