<?php
/**
 * Internationalization helper for multi-language plugin support
 *
 * @link       https://mementor.no
 * @since      1.0.0
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/includes
 */

// Prevent direct access to this file
if (!defined('ABSPATH')) {
    exit;
}

/**
 * I18n Helper class for language detection and voice selection
 *
 * Supports: Weglot, WPML, Polylang, TranslatePress
 *
 * @since      1.0.0
 * @package    TTSWP
 * @subpackage Mementor_TTS/includes
 */
class Mementor_TTS_I18n_Helper {

    /**
     * Get the current language code
     *
     * @since    1.0.0
     * @return   string    The current language code (e.g., 'en', 'nb', 'sv')
     */
    public static function get_current_language() {
        // 1. Check Weglot (highest priority if enabled)
        if (self::is_weglot_active()) {
            if (function_exists('weglot_get_current_language')) {
                $lang = weglot_get_current_language();
                if (!empty($lang)) {
                    // Handle object or string
                    if (is_object($lang) && method_exists($lang, 'getInternalCode')) {
                        return $lang->getInternalCode();
                    }
                    return (string) $lang;
                }
            }
        }

        // 2. Check WPML
        if (defined('ICL_LANGUAGE_CODE') && ICL_LANGUAGE_CODE) {
            return ICL_LANGUAGE_CODE;
        }

        // 3. Check Polylang
        if (function_exists('pll_current_language')) {
            $lang = pll_current_language();
            if (!empty($lang)) {
                return $lang;
            }
        }

        // 4. Check TranslatePress
        global $TRP_LANGUAGE;
        if (!empty($TRP_LANGUAGE)) {
            return $TRP_LANGUAGE;
        }

        // 5. Fallback to plugin's default language setting
        return get_option('mementor_tts_language', 'en');
    }

    /**
     * Get the original (source) language
     *
     * @since    1.0.0
     * @return   string    The original language code
     */
    public static function get_original_language() {
        // Check Weglot
        if (self::is_weglot_active() && function_exists('weglot_get_original_language')) {
            $lang = weglot_get_original_language();
            if (is_object($lang) && method_exists($lang, 'getInternalCode')) {
                return $lang->getInternalCode();
            }
            return (string) $lang;
        }

        // Check WPML
        if (function_exists('icl_get_default_language')) {
            return icl_get_default_language();
        }

        // Check Polylang
        if (function_exists('pll_default_language')) {
            return pll_default_language();
        }

        // Fallback
        return get_option('mementor_tts_language', 'en');
    }

    /**
     * Check if we're viewing a translated page (not the original language)
     *
     * @since    1.0.0
     * @return   bool    True if viewing a translated page
     */
    public static function is_translated_page() {
        $current = self::get_current_language();
        $original = self::get_original_language();

        return $current !== $original;
    }

    /**
     * Check if Weglot is active and integration is enabled
     *
     * @since    1.0.0
     * @return   bool    True if Weglot integration is active
     */
    public static function is_weglot_active() {
        return function_exists('weglot_get_current_language')
            && get_option('mementor_tts_weglot_enabled', '0') === '1';
    }

    /**
     * Check if WPML is active and integration is enabled
     *
     * @since    2.1.0
     * @return   bool    True if WPML integration is active
     */
    public static function is_wpml_active() {
        return defined('ICL_SITEPRESS_VERSION')
            && get_option('mementor_tts_wpml_enabled', '0') === '1';
    }

    /**
     * Check if any multilingual integration is active (Weglot or WPML)
     *
     * @since    2.1.0
     * @return   bool    True if any multilingual integration is active
     */
    public static function is_multilingual_active() {
        return self::is_weglot_active() || self::is_wpml_active();
    }

    /**
     * Get the language of a specific post
     *
     * @since    2.1.0
     * @param    int    $post_id    The post ID
     * @return   string             Language code, or empty string if unknown
     */
    public static function get_post_language($post_id) {
        // WPML
        if (self::is_wpml_active()) {
            $lang = apply_filters('wpml_post_language_details', null, $post_id);
            if (is_array($lang) && !empty($lang['language_code'])) {
                return $lang['language_code'];
            }
        }

        // Polylang
        if (function_exists('pll_get_post_language')) {
            $lang = pll_get_post_language($post_id);
            if (!empty($lang)) {
                return $lang;
            }
        }

        // Fallback to current language
        return self::get_current_language();
    }

    /**
     * Get the voice ID for a specific post based on its language
     *
     * @since    2.1.0
     * @param    int    $post_id    The post ID
     * @return   string             Voice ID for the post's language
     */
    public static function get_voice_for_post($post_id) {
        $language = self::get_post_language($post_id);
        return self::get_voice_for_language($language);
    }

    /**
     * Get voice ID for a specific language
     *
     * @since    1.0.0
     * @param    string    $language    Optional. Language code. Defaults to current language.
     * @return   string                 Voice ID for the language
     */
    public static function get_voice_for_language($language = null) {
        if ($language === null) {
            $language = self::get_current_language();
        }

        // Get the default voice
        $default_voice = get_option('mementor_tts_voice', '');

        // If no multilingual integration is enabled, always use default voice
        if (!self::is_multilingual_active()) {
            return $default_voice;
        }

        // Get language-voice mappings
        $mappings = get_option('mementor_tts_language_voice_mappings', array());

        // Check if there's a custom voice for this language (including default language)
        if (isset($mappings[$language]['voice_id']) && !empty($mappings[$language]['voice_id'])) {
            return $mappings[$language]['voice_id'];
        }

        // Fallback to default voice
        return $default_voice;
    }

    /**
     * Get all configured language-voice mappings
     *
     * @since    1.0.0
     * @return   array    Array of language => voice_id mappings
     */
    public static function get_language_voice_mappings() {
        return get_option('mementor_tts_language_voice_mappings', array());
    }

    /**
     * Check if a language has a custom voice configured
     *
     * @since    1.0.0
     * @param    string    $language    Language code
     * @return   bool                   True if custom voice is configured
     */
    public static function has_custom_voice($language) {
        $mappings = self::get_language_voice_mappings();
        return isset($mappings[$language]['voice_id']) && !empty($mappings[$language]['voice_id']);
    }

    /**
     * Get cache key suffix for the current language
     * Used to differentiate cached audio files by language
     *
     * @since    1.0.0
     * @return   string    Language suffix for cache keys (e.g., '-en', '-sv')
     */
    public static function get_language_cache_suffix() {
        if (!self::is_multilingual_active()) {
            return '';
        }

        $current = self::get_current_language();
        $original = self::get_original_language();

        // No suffix for original language
        if ($current === $original) {
            return '';
        }

        return '-' . $current;
    }

    /**
     * Debug: Get all language info
     *
     * @since    1.0.0
     * @return   array    Debug information about current language state
     */
    public static function get_debug_info() {
        return array(
            'weglot_active' => self::is_weglot_active(),
            'wpml_active' => self::is_wpml_active(),
            'multilingual_active' => self::is_multilingual_active(),
            'current_language' => self::get_current_language(),
            'original_language' => self::get_original_language(),
            'is_translated_page' => self::is_translated_page(),
            'current_voice' => self::get_voice_for_language(),
            'language_mappings' => self::get_language_voice_mappings(),
            'cache_suffix' => self::get_language_cache_suffix(),
        );
    }

    /**
     * Translate content using Weglot API
     *
     * @since    1.0.0
     * @param    string    $content        The content to translate
     * @param    string    $target_lang    Target language code
     * @param    string    $source_lang    Source language code (optional, defaults to original)
     * @return   string                    Translated content or original if translation fails
     */
    public static function translate_content($content, $target_lang, $source_lang = null) {
        // If Weglot is not active, return original content
        if (!self::is_weglot_active()) {
            return $content;
        }

        // Get source language if not provided
        if ($source_lang === null) {
            $source_lang = self::get_original_language();
        }

        // If target is same as source, no translation needed
        if ($target_lang === $source_lang) {
            return $content;
        }

        // Get Weglot API key
        if (!function_exists('weglot_get_api_key')) {
            error_log('[TTS I18n] Weglot API key function not available');
            return $content;
        }

        $api_key = weglot_get_api_key();
        if (empty($api_key)) {
            error_log('[TTS I18n] Weglot API key is empty');
            return $content;
        }

        // Prepare the content - split into chunks if too long (Weglot has limits)
        $max_length = 10000; // Weglot recommends smaller chunks
        $content_chunks = array();

        if (strlen($content) > $max_length) {
            // Split by paragraphs to maintain structure
            $paragraphs = preg_split('/(\r\n|\n|\r){2,}/', $content);
            $current_chunk = '';

            foreach ($paragraphs as $paragraph) {
                if (strlen($current_chunk) + strlen($paragraph) + 2 > $max_length) {
                    if (!empty($current_chunk)) {
                        $content_chunks[] = trim($current_chunk);
                    }
                    $current_chunk = $paragraph;
                } else {
                    $current_chunk .= ($current_chunk ? "\n\n" : '') . $paragraph;
                }
            }
            if (!empty($current_chunk)) {
                $content_chunks[] = trim($current_chunk);
            }
        } else {
            $content_chunks[] = $content;
        }

        // Translate each chunk
        $translated_chunks = array();

        foreach ($content_chunks as $chunk) {
            $translated = self::call_weglot_api($chunk, $source_lang, $target_lang, $api_key);
            if ($translated !== false) {
                $translated_chunks[] = $translated;
            } else {
                // If translation fails, use original chunk
                $translated_chunks[] = $chunk;
                error_log('[TTS I18n] Translation failed for chunk, using original');
            }
        }

        return implode("\n\n", $translated_chunks);
    }

    /**
     * Call Weglot Translation API
     *
     * @since    1.0.0
     * @param    string    $text           Text to translate
     * @param    string    $source_lang    Source language code
     * @param    string    $target_lang    Target language code
     * @param    string    $api_key        Weglot API key
     * @return   string|false              Translated text or false on failure
     */
    private static function call_weglot_api($text, $source_lang, $target_lang, $api_key) {
        $api_url = 'https://api.weglot.com/translate?api_key=' . urlencode($api_key);

        // Prepare request body
        $body = array(
            'l_from' => $source_lang,
            'l_to' => $target_lang,
            'request_url' => home_url(),
            'words' => array(
                array(
                    'w' => $text,
                    't' => 1  // Type 1 = text
                )
            )
        );

        // Make API request
        $response = wp_remote_post($api_url, array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => wp_json_encode($body),
            'timeout' => 30,
        ));

        // Check for errors
        if (is_wp_error($response)) {
            error_log('[TTS I18n] Weglot API error: ' . $response->get_error_message());
            return false;
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            error_log('[TTS I18n] Weglot API returned status ' . $response_code);
            return false;
        }

        // Parse response
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log('[TTS I18n] Weglot API response JSON parse error');
            return false;
        }

        // Extract translated text
        if (isset($data['to_words']) && is_array($data['to_words']) && !empty($data['to_words'][0])) {
            return $data['to_words'][0];
        }

        error_log('[TTS I18n] Weglot API response missing to_words');
        return false;
    }
}
