<?php
if (!class_exists('LanguageHandler')) {
class LanguageHandler {
    private $db;
    private $current_language;
    private $translations = [];
    
    public function __construct($database) {
        $this->db = $database;
        $this->current_language = $this->getCurrentLanguage();
        $this->loadTranslations();
    }
    
    public function getCurrentLanguage() {
        // Check session first
        if (isset($_SESSION['language'])) {
            return $_SESSION['language'];
        }
        
        // Check user preference
        if (isset($_SESSION['user_id'])) {
            $stmt = $this->db->prepare("SELECT language_code FROM user_language_preferences WHERE user_id = ?");
            $stmt->bind_param("i", $_SESSION['user_id']);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($row = $result->fetch_assoc()) {
                $_SESSION['language'] = $row['language_code'];
                return $row['language_code'];
            }
        }
        
        // Use system default
        $stmt = $this->db->prepare("SELECT value FROM settings WHERE code = 'default_language'");
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $default = $row['value'];
        } else {
            $default = 'en';
        }
        $_SESSION['language'] = $default;
        return $default;
    }
    
    public function setLanguage($language_code) {
        // Validate language exists
        $stmt = $this->db->prepare("SELECT * FROM languages WHERE code = ? AND active = 1");
        $stmt->bind_param("s", $language_code);
        $stmt->execute();
        $result = $stmt->get_result();
        if (!$result->fetch_assoc()) {
            return false;
        }
        
        $_SESSION['language'] = $language_code;
        
        // Update user preference if logged in
        if (isset($_SESSION['user_id'])) {
            $stmt = $this->db->prepare("INSERT INTO user_language_preferences (user_id, language_code) VALUES (?, ?) ON DUPLICATE KEY UPDATE language_code = ?");
            $stmt->bind_param("iss", $_SESSION['user_id'], $language_code, $language_code);
            $stmt->execute();
        }
        
        $this->current_language = $language_code;
        $this->loadTranslations();
        return true;
    }
    
    public function loadTranslations() {
        $stmt = $this->db->prepare("SELECT `key`, `value` FROM translations WHERE language_code = ?");
        $stmt->bind_param("s", $this->current_language);
        $stmt->execute();
        $result = $stmt->get_result();
        $this->translations = [];
        while ($row = $result->fetch_assoc()) {
            $this->translations[$row['key']] = $row['value'];
        }
    }
    
    public function translate($key, $default = null) {
        if (isset($this->translations[$key])) {
            return $this->translations[$key];
        }
        
        // If no translation found, return default or key
        return $default ?: $key;
    }
    
    public function getAvailableLanguages() {
        $stmt = $this->db->prepare("SELECT * FROM languages WHERE active = 1 ORDER BY name");
        $stmt->execute();
        $result = $stmt->get_result();
        $languages = [];
        while ($row = $result->fetch_assoc()) {
            $languages[] = $row;
        }
        return $languages;
    }
    
    public function isRTL() {
        $stmt = $this->db->prepare("SELECT rtl FROM languages WHERE code = ?");
        $stmt->bind_param("s", $this->current_language);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            return (bool)$row['rtl'];
        }
        return false;
    }
    
    public function getCurrentLanguageInfo() {
        $stmt = $this->db->prepare("SELECT * FROM languages WHERE code = ?");
        $stmt->bind_param("s", $this->current_language);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }
    
    public function addTranslation($key, $value, $context = null) {
        $stmt = $this->db->prepare("INSERT INTO translations (language_code, `key`, `value`, `context`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `value` = ?");
        $stmt->bind_param("sssss", $this->current_language, $key, $value, $context, $value);
        return $stmt->execute();
    }
    
    public function updateTranslation($key, $value) {
        $stmt = $this->db->prepare("UPDATE translations SET `value` = ? WHERE language_code = ? AND `key` = ?");
        $stmt->bind_param("sss", $value, $this->current_language, $key);
        return $stmt->execute();
    }
    
    public function deleteTranslation($key) {
        $stmt = $this->db->prepare("DELETE FROM translations WHERE language_code = ? AND `key` = ?");
        $stmt->bind_param("ss", $this->current_language, $key);
        return $stmt->execute();
    }
    
    public function getAllTranslations() {
        $stmt = $this->db->prepare("SELECT * FROM translations WHERE language_code = ? ORDER BY `key`");
        $stmt->bind_param("s", $this->current_language);
        $stmt->execute();
        $result = $stmt->get_result();
        $translations = [];
        while ($row = $result->fetch_assoc()) {
            $translations[] = $row;
        }
        return $translations;
    }
}
}

// Global translation function
if (!function_exists('__')) {
    function __($key, $default = null) {
        global $language_handler;
        if ($language_handler) {
            return $language_handler->translate($key, $default);
        }
        return $default ?: $key;
    }
}

// Initialize language handler globally
if (!isset($language_handler) && isset($conn)) {
    $language_handler = new LanguageHandler($conn);
}
?>
