<?php
/**
 * Translation Helper Functions
 * Provides global functions for easy translation throughout the application
 */

require_once __DIR__ . '/../app/Models/Language.php';
require_once __DIR__ . '/../app/Models/Translation.php';

// Global translation cache
$GLOBALS['translation_cache'] = [];
$GLOBALS['current_language_data'] = null;

/**
 * Main translation function
 * Usage: __('hello_world') or __('user.name')
 */
function __($key, $params = []) {
    $default = null;
    // If second argument is a scalar (string) treat it as default fallback text
    if(!is_array($params)){
        $default = (string)$params;
        $params = [];
    }
    static $translationModel = null;
    static $languageModel = null;
    
    if (!$translationModel) {
        $translationModel = new Translation();
        $languageModel = new Language();
    }
    
    $currentLang = Translation::getCurrentLanguage();
    $cacheKey = $currentLang . '.' . $key;
    
    // Check cache first
    $found = true; // assume found until proven otherwise
    if (isset($GLOBALS['translation_cache'][$cacheKey])) {
        $translation = $GLOBALS['translation_cache'][$cacheKey];
    } else {
        // Get translation from database
        $language = $languageModel->findByCode($currentLang);
        $languageId = $language ? $language['id'] : null;
        
        $translation = $translationModel->getByKey($key, $languageId);
        
        // Fallback to English if translation not found
        if (!$translation && $currentLang !== 'en') {
            $englishLang = $languageModel->findByCode('en');
            if ($englishLang) {
                $translation = $translationModel->getByKey($key, $englishLang['id']);
            }
        }
        
        // Ultimate fallback to the key itself (formatted)
        if (!$translation) {
            $found = false;
            
            // Use default if provided, otherwise format the key
            $autoTranslation = ($default !== null && $default !== '') 
                ? $default 
                : ucwords(str_replace(['_', '.'], ' ', $key));
            
            // Auto-create the translation in database (if enabled)
            if (defined('AUTO_CREATE_TRANSLATIONS') && AUTO_CREATE_TRANSLATIONS) {
                autoCreateMissingTranslation($key, $autoTranslation, $currentLang, $translationModel, $languageModel);
            }
            
            $translation = $autoTranslation;
        }
        
        // Cache the translation
        $GLOBALS['translation_cache'][$cacheKey] = $translation;
    }

    // If not found and a default provided, use default (already handled above)
    if(!$found && $default !== null && $default !== ''){
        $translation = $default;
    }
    
    // Replace parameters if provided
    if (!empty($params)) {
        foreach ($params as $param => $value) {
            $translation = str_replace(':' . $param, $value, $translation);
        }
    }
    
    return $translation;
}

/**
 * Echo translation function
 * Usage: _e('hello_world')
 */
function _e($key, $params = []) {
    echo __($key, $params);
}

/**
 * Get current language data
 */
function getCurrentLanguage() {
    static $languageModel = null;
    
    if (!$languageModel) {
        $languageModel = new Language();
    }
    
    if (!$GLOBALS['current_language_data']) {
        $currentCode = Translation::getCurrentLanguage();
        $GLOBALS['current_language_data'] = $languageModel->findByCode($currentCode);
    }
    
    return $GLOBALS['current_language_data'];
}

/**
 * Get available languages
 */
function getAvailableLanguages() {
    static $languageModel = null;
    static $languages = null;
    
    if (!$languageModel) {
        $languageModel = new Language();
    }
    
    if (!$languages) {
        $languages = $languageModel->getActive();
    }
    
    return $languages;
}

/**
 * Change current language
 */
function setLanguage($languageCode) {
    Translation::setLanguage($languageCode);
    
    // Clear cache
    $GLOBALS['translation_cache'] = [];
    $GLOBALS['current_language_data'] = null;
}

/**
 * Get text direction for current language
 */
function getTextDirection() {
    $rtlLanguages = ['ar', 'he', 'fa', 'ur'];
    $currentLang = Translation::getCurrentLanguage();
    
    return in_array($currentLang, $rtlLanguages) ? 'rtl' : 'ltr';
}

/**
 * Format number according to current language
 */
function formatNumber($number, $decimals = 0) {
    $currentLang = Translation::getCurrentLanguage();
    
    $locales = [
        'en' => ['decimal' => '.', 'thousands' => ','],
        'es' => ['decimal' => ',', 'thousands' => '.'],
        'fr' => ['decimal' => ',', 'thousands' => ' '],
        'de' => ['decimal' => ',', 'thousands' => '.'],
        'it' => ['decimal' => ',', 'thousands' => '.'],
        'pt' => ['decimal' => ',', 'thousands' => '.'],
    ];
    
    $locale = $locales[$currentLang] ?? $locales['en'];
    
    return number_format($number, $decimals, $locale['decimal'], $locale['thousands']);
}

/**
 * Format date according to current language
 */
function formatDate($date, $format = null) {
    $currentLang = Translation::getCurrentLanguage();
    
    if (!$format) {
        $formats = [
            'en' => 'M j, Y',
            'es' => 'd/m/Y',
            'fr' => 'd/m/Y',
            'de' => 'd.m.Y',
            'it' => 'd/m/Y',
            'pt' => 'd/m/Y',
        ];
        
        $format = $formats[$currentLang] ?? $formats['en'];
    }
    
    return date($format, is_string($date) ? strtotime($date) : $date);
}

/**
 * Automatically create missing translation in database
 */
function autoCreateMissingTranslation($key, $translation, $currentLang, $translationModel, $languageModel) {
    try {
        // Determine category from key (e.g., 'products.name' -> 'products')
        $keyParts = explode('.', $key);
        $category = count($keyParts) > 1 ? $keyParts[0] : 'general';
        
        // Get current language
        $language = $languageModel->findByCode($currentLang);
        if (!$language) {
            return false;
        }
        
        // Check if translation already exists to avoid duplicates
        $existing = $translationModel->getByKey($key, $language['id']);
        if ($existing) {
            return true; // Already exists
        }
        
        // Create the translation
        $success = $translationModel->create([
            'language_id' => $language['id'],
            'key' => $key,
            'value' => $translation,
            'category' => $category
        ]);
        
        // Log auto-creation for debugging (optional)
        if ($success && defined('AUTO_TRANSLATION_LOG') && AUTO_TRANSLATION_LOG) {
            error_log("Auto-created translation: {$key} = {$translation} [{$currentLang}]");
        }
        
        return $success;
        
    } catch (Exception $e) {
        // Silently fail to avoid breaking the application
        if (defined('AUTO_TRANSLATION_LOG') && AUTO_TRANSLATION_LOG) {
            error_log("Failed to auto-create translation {$key}: " . $e->getMessage());
        }
        return false;
    }
}
