<?php
/**
 * SYSTRAN Translation API Client
 * Translates names and text to English using SYSTRAN API
 */

class SystranAPI {
    private $apiKey;
    private $apiUrl = 'https://api-translate.systran.net';
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }
    
    /**
     * Translate text from any language to English
     * Uses auto-detection for source language
     * 
     * @param string $text Text to translate
     * @param string $sourceLanguage Source language code (optional, 'auto' for auto-detection)
     * @return array Result with 'success', 'translated_text', 'detected_language', 'error'
     */
    public function translateToEnglish($text, $sourceLanguage = 'auto') {
        if (empty($this->apiKey)) {
            error_log("SYSTRAN API key not configured");
            return [
                'success' => false,
                'error' => 'SYSTRAN API key not configured',
                'translated_text' => $text, // Return original text on error
                'detected_language' => null
            ];
        }
        
        if (empty(trim($text))) {
            return [
                'success' => true,
                'translated_text' => $text,
                'detected_language' => null
            ];
        }
        
        // Check if text is already in English (simple heuristic)
        if ($this->isEnglish($text)) {
            error_log("Text appears to be already in English: $text");
            return [
                'success' => true,
                'translated_text' => $text,
                'detected_language' => 'en'
            ];
        }
        
        try {
            $url = $this->apiUrl . '/translation/text/translate';
            
            // Build query parameters (SYSTRAN uses query params, not JSON body)
            $params = [
                'source' => $sourceLanguage, // 'auto' for auto-detection
                'target' => 'en', // Target: English
                'input' => $text,
                'withInfo' => 'true', // Get detected language info
                'key' => $this->apiKey // API key in query string
            ];
            
            $url .= '?' . http_build_query($params);
            
            error_log("SYSTRAN Translation request: Translating '$text' to English");
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true); // POST method as per API docs
            curl_setopt($ch, CURLOPT_POSTFIELDS, ''); // Empty body, params are in query string
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Accept: application/json'
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $curlError = curl_error($ch);
            curl_close($ch);
            
            if ($curlError) {
                error_log("SYSTRAN API cURL error: $curlError");
                return [
                    'success' => false,
                    'error' => "Translation API error: $curlError",
                    'translated_text' => $text, // Return original on error
                    'detected_language' => null
                ];
            }
            
            if ($httpCode !== 200) {
                error_log("SYSTRAN API returned HTTP $httpCode. Response: $response");
                return [
                    'success' => false,
                    'error' => "Translation API returned HTTP $httpCode",
                    'translated_text' => $text, // Return original on error
                    'detected_language' => null
                ];
            }
            
            $responseData = json_decode($response, true);
            
            if (json_last_error() !== JSON_ERROR_NONE) {
                error_log("SYSTRAN API response JSON decode error: " . json_last_error_msg());
                error_log("Response: $response");
                return [
                    'success' => false,
                    'error' => 'Invalid JSON response from translation API',
                    'translated_text' => $text, // Return original on error
                    'detected_language' => null
                ];
            }
            
            // Check for errors in response
            if (isset($responseData['error'])) {
                $errorMsg = $responseData['error']['message'] ?? 'Unknown translation error';
                error_log("SYSTRAN API error: $errorMsg");
                return [
                    'success' => false,
                    'error' => $errorMsg,
                    'translated_text' => $text, // Return original on error
                    'detected_language' => null
                ];
            }
            
            // Extract translated text and detected language
            $translatedText = $text; // Default to original
            $detectedLanguage = null;
            
            if (isset($responseData['outputs']) && is_array($responseData['outputs']) && !empty($responseData['outputs'])) {
                $output = $responseData['outputs'][0];
                
                if (isset($output['output'])) {
                    $translatedText = trim($output['output']);
                }
                
                // Get detected language from info
                if (isset($output['info']['lid']['language'])) {
                    $detectedLanguage = $output['info']['lid']['language'];
                    $confidence = $output['info']['lid']['confidence'] ?? 0;
                    error_log("SYSTRAN detected language: $detectedLanguage (confidence: $confidence)");
                }
            }
            
            // If translation is same as original or empty, return original
            if (empty($translatedText) || strtolower(trim($translatedText)) === strtolower(trim($text))) {
                error_log("SYSTRAN translation returned same as original or empty. Using original text.");
                $translatedText = $text;
            } else {
                error_log("SYSTRAN translation successful: '$text' -> '$translatedText'");
            }
            
            return [
                'success' => true,
                'translated_text' => $translatedText,
                'detected_language' => $detectedLanguage,
                'original_text' => $text
            ];
            
        } catch (Exception $e) {
            error_log("SYSTRAN translation exception: " . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage(),
                'translated_text' => $text, // Return original on error
                'detected_language' => null
            ];
        }
    }
    
    /**
     * Simple heuristic to check if text is already in English
     * Checks if text contains only ASCII characters and common English patterns
     * 
     * @param string $text Text to check
     * @return bool True if text appears to be English
     */
    private function isEnglish($text) {
        // Remove common punctuation and whitespace
        $cleanText = preg_replace('/[^\p{L}\p{N}]/u', '', $text);
        
        // Check if text contains only ASCII characters (A-Z, a-z, 0-9)
        // If it does, it's likely English or already in Latin script
        if (mb_strlen($cleanText) > 0 && preg_match('/^[a-zA-Z0-9\s]+$/', $text)) {
            // Additional check: if text has accented characters, it might not be English
            // But we'll let SYSTRAN API decide to be safe
            if (!preg_match('/[àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ]/i', $text)) {
                // No accented characters - likely English or already in Latin script
                return true;
            }
        }
        
        // If text contains non-ASCII characters (Cyrillic, Arabic, Chinese, etc.), it's not English
        if (!mb_check_encoding($text, 'ASCII')) {
            // Check if it's just extended ASCII (Latin-1) or truly non-Latin
            $hasNonLatin = preg_match('/[^\x00-\x7F]/u', $text);
            if ($hasNonLatin && !preg_match('/[àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞß]/u', $text)) {
                // Contains non-Latin characters - definitely not English
                return false;
            }
        }
        
        // If we can't determine, let SYSTRAN API auto-detect
        return false;
    }
}

