<?php

class Translation
{
    private $pdo;
    private static $cache = [];
    private static $currentLanguage = null;
    
    public function __construct()
    {
        $this->pdo = $GLOBALS['pdo'];
    }
    
    public static function setLanguage($languageCode)
    {
        self::$currentLanguage = $languageCode;
        $_SESSION['language'] = $languageCode;
    }
    
    public static function getCurrentLanguage()
    {
        if (self::$currentLanguage) {
            return self::$currentLanguage;
        }
        
        // Check session
        if (isset($_SESSION['language'])) {
            self::$currentLanguage = $_SESSION['language'];
            return self::$currentLanguage;
        }
        
        // Default to English
        self::$currentLanguage = 'en';
        return self::$currentLanguage;
    }
    
    public function create($data)
    {
        $sql = "INSERT INTO translations (language_id, translation_key, translation_value, category, created_at) VALUES (?, ?, ?, ?, NOW())
                ON DUPLICATE KEY UPDATE translation_value = VALUES(translation_value), updated_at = NOW()";
        $stmt = $this->pdo->prepare($sql);
        
        return $stmt->execute([
            $data['language_id'],
            $data['key'],
            $data['value'],
            $data['category'] ?? 'general'
        ]);
    }
    
    /**
     * Create new translation (alternative signature for views)
     */
    public function createTranslation($language_id, $key, $value, $category = 'general') {
        return $this->create([
            'language_id' => $language_id,
            'key' => $key,
            'value' => $value,
            'category' => $category
        ]);
    }
    
    public function getByLanguage($languageId)
    {
        $sql = "SELECT * FROM translations WHERE language_id = ? ORDER BY category, translation_key";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$languageId]);
        
        return $stmt->fetchAll();
    }
    
    public function getByKey($key, $languageId = null)
    {
        if (!$languageId) {
            // Get current language ID
            $langModel = new Language();
            $lang = $langModel->findByCode(self::getCurrentLanguage());
            $languageId = $lang ? $lang['id'] : 1;
        }
        
        $sql = "SELECT translation_value FROM translations WHERE translation_key = ? AND language_id = ?";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([$key, $languageId]);
        
        $result = $stmt->fetch();
        return $result ? $result['translation_value'] : null;
    }
    
    public function getAllKeys()
    {
        $sql = "SELECT DISTINCT translation_key, category FROM translations ORDER BY category, translation_key";
        $stmt = $this->pdo->query($sql);
        
        return $stmt->fetchAll();
    }
    
    public function update($id, $data)
    {
        $sql = "UPDATE translations SET translation_value = ?, category = ?, updated_at = NOW() WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        
        return $stmt->execute([
            $data['value'],
            $data['category'] ?? 'general',
            $id
        ]);
    }
    
    public function delete($id)
    {
        $sql = "DELETE FROM translations WHERE id = ?";
        $stmt = $this->pdo->prepare($sql);
        
        return $stmt->execute([$id]);
    }
    
    public function importTranslations($languageId, $translations, $category = 'general')
    {
        $this->pdo->beginTransaction();
        
        try {
            foreach ($translations as $key => $value) {
                $this->create([
                    'language_id' => $languageId,
                    'key' => $key,
                    'value' => $value,
                    'category' => $category
                ]);
            }
            
            $this->pdo->commit();
            return true;
        } catch (Exception $e) {
            $this->pdo->rollback();
            return false;
        }
    }
    
    public function getTranslationsMatrix()
    {
        $sql = "
        SELECT 
            t.translation_key,
            t.category,
            l.code as language_code,
            l.name as language_name,
            t.translation_value
        FROM translations t
        JOIN languages l ON t.language_id = l.id
        ORDER BY t.category, t.translation_key, l.name
        ";
        
        $stmt = $this->pdo->query($sql);
        $results = $stmt->fetchAll();
        
        $matrix = [];
        foreach ($results as $row) {
            $matrix[$row['translation_key']][$row['language_code']] = $row['translation_value'];
            $matrix[$row['translation_key']]['category'] = $row['category'];
        }
        
        return $matrix;
    }
    
    /**
     * Get translation count by language
     */
    public function getCountByLanguage($language_id) {
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM translations WHERE language_id = ?");
        $stmt->execute([$language_id]);
        return $stmt->fetchColumn();
    }
    
    /**
     * Get translation by key and language
     */
    public function getByKeyAndLanguage($key, $language_id) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM translations 
            WHERE translation_key = ? AND language_id = ?
        ");
        $stmt->execute([$key, $language_id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    /**
     * Update translation by key and language
     */
    public function updateByKeyAndLanguage($key, $language_id, $value) {
        $stmt = $this->pdo->prepare("
            UPDATE translations 
            SET translation_value = ?, updated_at = CURRENT_TIMESTAMP 
            WHERE translation_key = ? AND language_id = ?
        ");
        return $stmt->execute([$value, $key, $language_id]);
    }
}

