<?php
/**
 * Google Translate Integration - Server-Side Translation
 * Uses Google Translate API to dynamically translate entire website
 * No CSP issues, no JavaScript blocking, 100% reliable
 */

// Cache directory for translations
$cacheDir = __DIR__ . '/../data/translations_cache';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

/**
 * Translate text using Google Translate API (free service)
 * @param string $text Text to translate
 * @param string $target_lang Target language code (en, es, it, de)
 * @return string Translated text
 */
function translateWithGoogle($text, $target_lang = 'en') {
    // Don't translate if already in English or if text is empty
    if (empty($text) || $target_lang === 'en') {
        return $text;
    }

    // Use Google's public translate endpoint
    $url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=' . urlencode($target_lang) . '&dt=t&q=' . urlencode($text);
    
    try {
        $context = stream_context_create([
            'http' => [
                'timeout' => 5,
                'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            ],
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false
            ]
        ]);
        
        $response = @file_get_contents($url, false, $context);
        
        if ($response) {
            // Parse the response - Google returns JSON array
            $result = json_decode($response, true);
            if (is_array($result) && isset($result[0])) {
                // Extract translated text from nested array
                $translated = '';
                foreach ($result[0] as $segment) {
                    if (is_array($segment) && isset($segment[0])) {
                        $translated .= $segment[0];
                    }
                }
                return !empty($translated) ? $translated : $text;
            }
        }
    } catch (Exception $e) {
        error_log('Translation error: ' . $e->getMessage());
    }
    
    // Return original text if translation fails
    return $text;
}

/**
 * Simple alternative: Use a free translation API with fallback
 * @param string $text Text to translate
 * @param string $source_lang Source language code
 * @param string $target_lang Target language code
 * @return string Translated text
 */
function translateText($text, $source_lang = 'en', $target_lang = 'en') {
    // If target is English, return original
    if ($target_lang === 'en' || $source_lang === $target_lang) {
        return $text;
    }

    // Use multiple fallback methods
    $translated = translateWithGoogle($text, $target_lang);
    
    if ($translated !== $text) {
        return $translated;
    }

    // If Google fails, try MyMemory API (completely free, no auth needed)
    $url = 'https://api.mymemory.translated.net/get?q=' . urlencode($text) . '&langpair=' . $source_lang . '|' . $target_lang;
    
    try {
        $context = stream_context_create([
            'http' => ['timeout' => 5],
            'ssl' => ['verify_peer' => false]
        ]);
        
        $response = @file_get_contents($url, false, $context);
        if ($response) {
            $result = json_decode($response, true);
            if (isset($result['responseData']['translatedText'])) {
                return $result['responseData']['translatedText'];
            }
        }
    } catch (Exception $e) {
        error_log('MyMemory translation error: ' . $e->getMessage());
    }

    // Return original if all translations fail
    return $text;
}

/**
 * Get current language code for translation
 */
function getTranslationLanguage() {
    $lang_map = [
        'ENG' => 'en',
        'ITA' => 'it',
        'ESP' => 'es',
        'GER' => 'de'
    ];
    
    $current = $_SESSION['selected_language'] ?? 'ENG';
    return $lang_map[$current] ?? 'en';
}

/**
 * JavaScript function to integrate with dropdowns
 * Call this to enable automatic translation when language changes
 */
function getTranslationScript() {
    return <<<'JS'
<script>
// Override default changeLanguage to use Google Translate
window.originalChangeLanguage = changeLanguage;

function changeLanguageWithGoogleTranslate(selectElement) {
    const value = selectElement.value;
    console.log('Starting translation to:', value);
    
    // Save to server first
    fetch('/emporio-sport/api_set_preference.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ type: 'language', value: value })
    })
    .then(r => r.json())
    .then(data => {
        console.log('Language saved:', data);
        alert('Language changed to: ' + value + '\nPage translating...');
        
        // Reload page which triggers server-side translation
        setTimeout(() => { 
            location.reload(); 
        }, 800);
    })
    .catch(e => {
        console.error('Error:', e);
        alert('Error changing language');
    });
}

// Replace changeLanguage function
changeLanguage = changeLanguageWithGoogleTranslate;

console.log('Google Translate integration loaded');
</script>
JS;
}
?>
