<?php
/**
 * Global Translation Helper Functions
 * This file provides the main __ translation function that can be used throughout the application
 */

// Only define functions if they don't already exist to prevent conflicts
if (!function_exists('__')) {
    /**
     * Main translation function
     * @param string $key Translation key (e.g., 'dashboard.title')
     * @param mixed $params Array of parameters or default string if not found
     * @return string Translated text
     */
    function __($key, $params = []) {
        // Handle both parameter patterns:
        // __('key', ['param' => 'value']) - parameters
        // __('key', 'default value') - default fallback
        $default = null;
        if (!is_array($params)) {
            $default = (string)$params;
            $params = [];
        }
        
        try {
            // Include required models if not already loaded
            if (!class_exists('Translation')) {
                require_once __DIR__ . '/../Models/Translation.php';
            }
            if (!class_exists('Language')) {
                require_once __DIR__ . '/../Models/Language.php';
            }
            
            // Initialize global cache if not exists
            if (!isset($GLOBALS['translation_cache'])) {
                $GLOBALS['translation_cache'] = [];
            }
            
            // Static instances to avoid recreating
            static $translationModel = null;
            static $languageModel = null;
            
            if (!$translationModel) {
                $translationModel = new Translation();
                $languageModel = new Language();
            }
            
            $currentLang = Translation::getCurrentLanguage();
            $cacheKey = $currentLang . '.' . $key;
            
            // Check cache first
            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']);
                    }
                }
                
                // Auto-create missing translation if not found
                if (!$translation) {
                    
                    // 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
                if (!isset($GLOBALS['translation_cache'])) {
                    $GLOBALS['translation_cache'] = [];
                }
                $GLOBALS['translation_cache'][$cacheKey] = $translation;
            }
            
            // Replace parameters if provided
            if (!empty($params)) {
                foreach ($params as $param => $value) {
                    $translation = str_replace(':' . $param, $value, $translation);
                }
            }
            
            return $translation;
            
        } catch (Exception $e) {
            // Fallback in case of any errors
            if ($default !== null && $default !== '') {
                return $default;
            }
            // Format the key as a readable string
            return ucwords(str_replace(['_', '.'], ' ', $key));
        }
    }
    
    /**
     * 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;
            }
            
            // 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;
        }
    }
}

if (!function_exists('_e')) {
    /**
     * Echo translation function
     * @param string $key Translation key
     * @param array $params Parameters
     */
    function _e($key, $params = []) {
        echo __($key, $params);
    }
}

