<?php
/**
 * Google Translate API Integration
 * Translates entire page content using Google's free translation service
 * No authentication needed, completely free
 */

// Only start session if not already active
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// Language mapping
$langMap = [
    'eng' => 'en',
    'ita' => 'it', 
    'esp' => 'es',
    'ger' => 'de'
];

// Get current language from session (lowercase 3-letter code)
$currentLang = $_SESSION['selected_language'] ?? 'eng';
$googleLang = $langMap[$currentLang] ?? 'en';

/**
 * Translate text using Google Translate Free API
 * No authentication needed!
 */
function translateText($text, $targetLang = 'en') {
    // Don't translate if already in English
    if ($targetLang === 'en' || empty($text)) {
        return $text;
    }
    
    // Use Google Translate free endpoint
    $url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=' . urlencode($targetLang) . '&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) {
            $result = json_decode($response, true);
            if (is_array($result) && isset($result[0])) {
                $translated = '';
                foreach ($result[0] as $segment) {
                    if (is_array($segment) && isset($segment[0])) {
                        $translated .= $segment[0];
                    }
                }
                return !empty($translated) ? $translated : $text;
            }
        }
    } catch (Exception $e) {
        // Fallback to original if translation fails
        return $text;
    }
    
    return $text;
}

/**
 * Start output buffering to translate entire page
 */
function startTranslationBuffer() {
    ob_start();
}

/**
 * End output buffering and translate collected content
 */
function endTranslationBuffer($targetLang = 'en') {
    $content = ob_get_clean();
    
    // Don't translate if English
    if ($targetLang === 'en') {
        echo $content;
        return;
    }
    
    // Split content into chunks for translation
    // Translate in smaller chunks to avoid timeout
    $chunkSize = 3000;
    $chunks = str_split($content, $chunkSize);
    
    $translated = '';
    foreach ($chunks as $chunk) {
        // Translate the chunk
        $translatedChunk = translateText($chunk, $targetLang);
        $translated .= $translatedChunk;
    }
    
    echo $translated;
}

// Export functions for use in pages
if (!function_exists('translate')) {
    function translate($text, $targetLang = null) {
        global $googleLang;
        $lang = $targetLang ?? $googleLang;
        return translateText($text, $lang);
    }
}

if (!function_exists('getTargetLanguage')) {
    function getTargetLanguage() {
        global $googleLang;
        return $googleLang;
    }
}
?>
