<?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;
            $translation = str_replace(['_', '.'], ' ', $key);
            $translation = ucwords($translation);
        }
        
        // Cache the translation
        $GLOBALS['translation_cache'][$cacheKey] = $translation;
    }

    // If not found and a default provided, use default
    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);
}
