<?php
/**
 * 多语言管理类（支持动态语言包）
 */
class Language {
    private $lang = 'zh-cn';
    private $translations = [];
    private $config;

    public function __construct() {
        $this->config = include ROOT_PATH . 'includes/lang/lang_config.php';
        global $db;
        $defaultLang = getSetting('site_lang', $db);
        if ($defaultLang && $this->isLangAvailable($defaultLang)) {
            $this->lang = $defaultLang;
        } else {
            $this->lang = $this->config['default'];
        }
        $this->load();
    }

    private function isLangAvailable($code) {
        return isset($this->config['available'][$code]);
    }

    private function load() {
        $file = ROOT_PATH . "includes/lang/{$this->lang}.php";
        if (file_exists($file)) {
            $this->translations = include $file;
        } else {
            $defaultFile = ROOT_PATH . "includes/lang/{$this->config['default']}.php";
            $this->translations = file_exists($defaultFile) ? include $defaultFile : [];
        }
    }

    public function set($lang) {
        if ($this->isLangAvailable($lang)) {
            $this->lang = $lang;
            global $db;
            $db->query("REPLACE INTO settings (`key`, `value`) VALUES ('site_lang', ?)", [$lang]);
            $this->load();
        }
    }

    public function get($key, $default = '') {
        return $this->translations[$key] ?? $default;
    }

    public function current() {
        return $this->lang;
    }

    public function getAllLanguages() {
        return $this->config['available'];
    }

    public function addLanguage($code, $name) {
        $this->config['available'][$code] = $name;
        $this->saveConfig();
    }

    public function removeLanguage($code) {
        if ($code === $this->config['default']) return false;
        unset($this->config['available'][$code]);
        $this->saveConfig();
        return true;
    }

    private function saveConfig() {
        $content = '<?php return ' . var_export($this->config, true) . ';';
        file_put_contents(ROOT_PATH . 'includes/lang/lang_config.php', $content);
    }
}