<?php
/**
 * 多语言核心类
 * 支持：简体中文、繁体中文、英文、日文
 */

class Language {
    private static $instance = null;
    private $current_lang = 'zh-CN';
    private $translations = [];
    private $supported_langs = [
        'zh-CN' => ['name' => '简体中文', 'flag' => '🇨🇳', 'icon' => 'cn'],
        'zh-TW' => ['name' => '繁體中文', 'flag' => '🇭🇰', 'icon' => 'tw'],
        'en'    => ['name' => 'English', 'flag' => '🇺🇸', 'icon' => 'us'],
        'ja'    => ['name' => '日本語', 'flag' => '🇯🇵', 'icon' => 'jp']
    ];
    
    private function __construct() {
        $this->detectLanguage();
        $this->loadLanguageFile();
    }
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 检测当前语言
     * 优先级：GET参数 > Cookie > Session > 浏览器语言 > 默认
     */
    private function detectLanguage() {
        // 1. GET 参数
        if (isset($_GET['lang']) && isset($this->supported_langs[$_GET['lang']])) {
            $this->current_lang = $_GET['lang'];
            $this->setLanguageCookie($this->current_lang);
            $_SESSION['user_lang'] = $this->current_lang;
            return;
        }
        
        // 2. Session
        if (isset($_SESSION['user_lang']) && isset($this->supported_langs[$_SESSION['user_lang']])) {
            $this->current_lang = $_SESSION['user_lang'];
            return;
        }
        
        // 3. Cookie
        if (isset($_COOKIE['user_lang']) && isset($this->supported_langs[$_COOKIE['user_lang']])) {
            $this->current_lang = $_COOKIE['user_lang'];
            $_SESSION['user_lang'] = $this->current_lang;
            return;
        }
        
        // 4. 浏览器语言
        $browser_lang = $this->getBrowserLanguage();
        if ($browser_lang && isset($this->supported_langs[$browser_lang])) {
            $this->current_lang = $browser_lang;
            return;
        }
        
        // 5. 默认
        $this->current_lang = 'zh-CN';
    }
    
    /**
     * 获取浏览器语言
     */
    private function getBrowserLanguage() {
        if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            return null;
        }
        
        $langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        foreach ($langs as $lang) {
            $lang = substr($lang, 0, 2);
            if ($lang == 'zh') {
                // 进一步区分简繁
                if (strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'TW') !== false || 
                    strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'HK') !== false ||
                    strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'MO') !== false) {
                    return 'zh-TW';
                }
                return 'zh-CN';
            }
            if ($lang == 'en') return 'en';
            if ($lang == 'ja') return 'ja';
        }
        return null;
    }
    
    /**
     * 设置语言 Cookie
     */
    private function setLanguageCookie($lang) {
        setcookie('user_lang', $lang, time() + 31536000, '/', '', false, true);
    }
    
    /**
     * 加载语言文件
     */
    private function loadLanguageFile() {
        $lang_file = __DIR__ . '/../assets/lang/' . $this->current_lang . '.php';
        if (file_exists($lang_file)) {
            $this->translations = include $lang_file;
        } else {
            // 降级到简体中文
            $fallback_file = __DIR__ . '/../assets/lang/zh-CN.php';
            if (file_exists($fallback_file)) {
                $this->translations = include $fallback_file;
            }
        }
    }
    
    /**
     * 获取翻译文本
     * @param string $key 翻译键名
     * @param array $params 参数替换（可选）
     * @return string
     */
    public function get($key, $params = []) {
        $text = isset($this->translations[$key]) ? $this->translations[$key] : $key;
        
        // 参数替换
        if (!empty($params)) {
            foreach ($params as $k => $v) {
                $text = str_replace('{' . $k . '}', $v, $text);
            }
        }
        
        return $text;
    }
    
    /**
     * 获取当前语言代码
     */
    public function getCurrentLang() {
        return $this->current_lang;
    }
    
    /**
     * 获取支持的语言列表
     */
    public function getSupportedLangs() {
        return $this->supported_langs;
    }
    
    /**
     * 切换语言
     */
    public function switchLang($lang) {
        if (isset($this->supported_langs[$lang])) {
            $this->current_lang = $lang;
            $this->setLanguageCookie($lang);
            $_SESSION['user_lang'] = $lang;
            $this->loadLanguageFile();
        }
    }
    
    /**
     * 生成语言切换器 HTML
     */
    public function renderSwitcher($position = 'header') {
        $current = $this->supported_langs[$this->current_lang];
        $html = '<div class="lang-switcher">';
        $html .= '<button class="lang-current" onclick="toggleLangMenu()">';
        $html .= '<span class="lang-flag">' . $current['flag'] . '</span> ';
        $html .= '<span class="lang-name">' . $current['name'] . '</span>';
        $html .= ' <span class="lang-arrow">▼</span>';
        $html .= '</button>';
        $html .= '<div class="lang-menu" id="langMenu">';
        
        foreach ($this->supported_langs as $code => $lang) {
            $active = ($code == $this->current_lang) ? 'active' : '';
            $html .= '<a href="?lang=' . $code . '" class="lang-item ' . $active . '" onclick="switchLanguage(\'' . $code . '\'); return false;">';
            $html .= '<span class="lang-flag">' . $lang['flag'] . '</span> ';
            $html .= '<span class="lang-name">' . $lang['name'] . '</span>';
            $html .= '</a>';
        }
        
        $html .= '</div>';
        $html .= '</div>';
        
        // 添加切换脚本
        $html .= $this->getSwitcherScript();
        
        return $html;
    }
    
    /**
     * 语言切换器 JS 脚本
     */
    private function getSwitcherScript() {
        return '
        <script>
        function toggleLangMenu() {
            var menu = document.getElementById("langMenu");
            if (menu) {
                menu.classList.toggle("show");
            }
        }
        
        function switchLanguage(lang) {
            var url = new URL(window.location.href);
            url.searchParams.set("lang", lang);
            window.location.href = url.toString();
        }
        
        document.addEventListener("click", function(e) {
            var switcher = document.querySelector(".lang-switcher");
            var menu = document.getElementById("langMenu");
            if (switcher && menu && !switcher.contains(e.target)) {
                menu.classList.remove("show");
            }
        });
        </script>
        ';
    }
}

/**
 * 全局翻译函数
 * @param string $key 翻译键名
 * @param array $params 参数替换
 * @return string
 */
function __($key, $params = []) {
    return Language::getInstance()->get($key, $params);
}

/**
 * 获取当前语言
 */
function current_lang() {
    return Language::getInstance()->getCurrentLang();
}

/**
 * 渲染语言切换器
 */
function render_lang_switcher() {
    return Language::getInstance()->renderSwitcher();
}
?>