<?php
class Language {
    private $db;
    private $current_lang;
    private $translations = [];
    
    public function __construct($db) {
        $this->db = $db;
        $this->current_lang = $this->getDefaultLanguage();
        $this->loadTranslations();
        $this->handleSwitchRequest();
    }

    /* ------------------------------------------------------------------
       Global ?lang=xx handler.  Any page that creates a Language object
       before printing HTML gets the language switcher for free — this is
       what the button in the panel header (includes/theme.php) uses.
       ------------------------------------------------------------------ */
    private function handleSwitchRequest() {
        if (!isset($_GET['lang'])) return;
        if (headers_sent()) return;

        $this->setLanguage(preg_replace('/[^a-zA-Z_-]/', '', $_GET['lang']));

        // Rebuild the current URL without the lang parameter, keeping the rest
        $parts = parse_url($_SERVER['REQUEST_URI'] ?? '');
        $path  = $parts['path'] ?? '';
        $q     = [];
        if (!empty($parts['query'])) { parse_str($parts['query'], $q); }
        unset($q['lang']);
        $url = $path . (!empty($q) ? '?' . http_build_query($q) : '');

        header('Location: ' . $url);
        exit;
    }
    
    private function getDefaultLanguage() {
        if (isset($_SESSION['lang'])) {
            return $_SESSION['lang'];
        }
        
        $result = $this->db->select("SELECT code FROM languages WHERE is_default = 1 AND status = 1 LIMIT 1");
        if (!empty($result)) {
            return $result[0]['code'];
        }
        
        return 'bn';
    }
    
    public function setLanguage($code) {
        $result = $this->db->select("SELECT code FROM languages WHERE code = ? AND status = 1", [$code]);
        if (!empty($result)) {
            $this->current_lang = $code;
            $_SESSION['lang'] = $code;
            $this->loadTranslations();
            return true;
        }
        return false;
    }
    
    private function loadTranslations() {
        $this->translations = [];
        
        $file_path = __DIR__ . '/../translations/' . $this->current_lang . '.php';
        if (file_exists($file_path)) {
            $file_translations = include $file_path;
            if (is_array($file_translations)) {
                foreach ($file_translations as $key => $value) {
                    $this->translations[$key] = $value;
                }
            }
        }

        $db_translations = $this->db->select(
            "SELECT translation_key, translation_value FROM translations WHERE language_code = ?",
            [$this->current_lang]
        );
        
        foreach ($db_translations as $row) {
            if (!empty($row['translation_value'])) {
                $this->translations[$row['translation_key']] = $row['translation_value'];
            }
        }
    }
    
    public function translate($key, $default = '') {
        return isset($this->translations[$key]) ? $this->translations[$key] : ($default ?: $key);
    }
    
    public function getCurrentLanguage() {
        return $this->current_lang;
    }
    
    public function getLanguages() {
        return $this->db->select("SELECT code, name FROM languages WHERE status = 1 ORDER BY is_default DESC, name ASC");
    }
}
?>