<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Translate a single string using Google Translate API
 */
if (!function_exists('translate_text')) {
    function translate_text($text, $target_lang, $source_lang = 'en', $apiKey = null)
    {
        // Return original if no API key, language match, or empty text
        if (empty($apiKey) || strtolower($target_lang) === strtolower($source_lang) || trim($text) === '') {
            return $text;
        }

        $url = 'https://translation.googleapis.com/language/translate/v2';

        $postData = [
            'q'      => $text,
            'source' => $source_lang,
            'target' => $target_lang,
            'format' => 'text',
            'key'    => $apiKey
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Optional: timeout
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        // Log and fallback if any issues
        if ($httpCode !== 200 || empty($response)) {
            log_message('error', "Google Translate API Error - HTTP Code: $httpCode | Curl Error: $curlError | Response: $response");
            return $text;
        }

        $data = json_decode($response, true);

        if (isset($data['data']['translations'][0]['translatedText'])) {
            return $data['data']['translations'][0]['translatedText'];
        }

        // Log if translation fails
        log_message('error', 'Google Translate failed to return translatedText: ' . $response);
        return $text;
    }
}

/**
 * Translate specified fields in an array of associative arrays
 */
if (!function_exists('translate_fields')) {
    function translate_fields($data = [], $fields = [], $target_lang = 'en', $source_lang = 'en', $apiKey = null)
    {
        if (!is_array($data) || empty($fields)) {
            return $data;
        }

        foreach ($data as &$row) {
            if (is_array($row)) {
                foreach ($fields as $field) {
                    if (isset($row[$field]) && !empty($row[$field]) && is_string($row[$field])) {
                        $row[$field] = translate_text($row[$field], $target_lang, $source_lang, $apiKey);
                    }
                }
            }
        }

        return $data;
    }
}
