<?php
/**
 * Multi-Language System
 * Version: 2.0
 * PHP: 7.4+
 */

declare(strict_types=1);

class Language {
    private static ?Language $instance = null;
    private string $currentLang = 'fa';
    private array $translations = [];
    private array $availableLanguages = ['fa', 'en', 'ar', 'tr'];
    
    private function __construct() {
        $this->loadLanguage($this->currentLang);
    }
    
    public static function getInstance(): Language {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Set current language
     */
    public function setLanguage(string $lang): bool {
        if (!in_array($lang, $this->availableLanguages)) {
            return false;
        }
        
        $this->currentLang = $lang;
        $this->loadLanguage($lang);
        return true;
    }
    
    /**
     * Get current language
     */
    public function getCurrentLanguage(): string {
        return $this->currentLang;
    }
    
    /**
     * Load language file
     */
    private function loadLanguage(string $lang): void {
        $file = __DIR__ . "/languages/{$lang}.php";
        
        if (file_exists($file)) {
            $this->translations = require $file;
        } else {
            $this->translations = [];
        }
    }
    
    /**
     * Get translation
     */
    public function get(string $key, array $params = []): string {
        $keys = explode('.', $key);
        $value = $this->translations;
        
        foreach ($keys as $k) {
            if (!isset($value[$k])) {
                return $key; // Return key if translation not found
            }
            $value = $value[$k];
        }
        
        // Replace parameters
        if (!empty($params)) {
            foreach ($params as $param => $val) {
                $value = str_replace(":{$param}", $val, $value);
            }
        }
        
        return $value;
    }
    
    /**
     * Shorthand for get()
     */
    public function t(string $key, array $params = []): string {
        return $this->get($key, $params);
    }
    
    /**
     * Get all available languages
     */
    public function getAvailableLanguages(): array {
        return $this->availableLanguages;
    }
    
    /**
     * Detect language from text
     */
    public function detectLanguage(string $text): string {
        // Persian
        if (preg_match('/[\x{0600}-\x{06FF}]/u', $text)) {
            return 'fa';
        }
        
        // Arabic
        if (preg_match('/[\x{0600}-\x{06FF}\x{0750}-\x{077F}]/u', $text)) {
            return 'ar';
        }
        
        // Turkish
        if (preg_match('/[ğĞıİöÖüÜşŞçÇ]/u', $text)) {
            return 'tr';
        }
        
        // Default to English
        return 'en';
    }
    
    /**
     * Get user language from database
     */
    public function getUserLanguage(int $userId): string {
        $db = Database::getInstance();
        $user = $db->fetchOne(
            "SELECT language FROM `members` WHERE id = ?",
            [$userId]
        );
        
        return $user['language'] ?? 'fa';
    }
    
    /**
     * Set user language in database
     */
    public function setUserLanguage(int $userId, string $lang): bool {
        if (!in_array($lang, $this->availableLanguages)) {
            return false;
        }
        
        $db = Database::getInstance();
        
        return $db->update('members', [
            'language' => $lang
        ], 'id = ?', [$userId]);
    }
}

/**
 * Helper function for translations
 */
function __($key, $params = []) {
    return Language::getInstance()->get($key, $params);
}
