<?php

/**
 * WPML Compatibility Class for Kaveh Theme
 * 
 * This class handles WPML integration for theme options and ensures
 * proper translation support for all theme strings and options.
 */
class KavehWPML
{
    private $options;
    private $prefix = 'kaveh_frame';
    
    public function __construct()
    {
        $this->init_hooks();
    }
    
    /**
     * Initialize WPML hooks and filters
     */
    private function init_hooks()
    {
        // Check if WPML is active
        if (!$this->is_wpml_active()) {
            return;
        }
        
        add_action('init', array($this, 'register_multilingual_options'), 1);
        add_filter('kaveh_get_option', array($this, 'translate_option'), 10, 3);
        add_action('admin_init', array($this, 'register_admin_strings'));
        add_filter('wpml_show_admin_language_switcher', array($this, 'show_language_switcher_on_options'));
        
        // Hook into CSF framework
        add_action('csf_kaveh_frame_saved', array($this, 'register_strings_after_save'));
    }
    
    /**
     * Check if WPML is active and available
     */
    private function is_wpml_active()
    {
        return defined('ICL_SITEPRESS_VERSION') && function_exists('icl_object_id');
    }
    
    /**
     * Register theme options as multilingual
     */
    public function register_multilingual_options()
    {
        if (!$this->is_wpml_active()) {
            return;
        }
        
        // Get the screen IDs where theme options are managed
        $screen_ids = array(
            'toplevel_page_kaveh-options',
            'kaveh-settings_page_kaveh-options'
        );
        
        // Register the main options as multilingual
        do_action('wpml_multilingual_options', $this->prefix, $screen_ids);
    }
    
    /**
     * Translate individual option values
     */
    public function translate_option($value, $option_key, $default)
    {
        if (!$this->is_wpml_active()) {
            return $value;
        }
        
        // List of translatable text options
        $translatable_options = array(
            'kaveh_title_social',
            'kaveh_title_two_social',
            'kaveh_title_social_social',
            'kaveh_title_social_two_social',
            'kaveh_after_title_social_social',
            'kaveh_after_title_social_two_social',
            'kaveh_phone_header_mobile',
            'kaveh_foomobile_text1',
            'kaveh_foomobile_text2',
            'kaveh_foomobile_text3',
            'kaveh_foomobile_text4',
            'kaveh_foomobile_text5',
            'kaveh_boxmenudown_text',
            'prtamas_text',
            'kcheckout_header_text1',
            'kcheckout_header_text2',
            'kcheckout_header_text3',
            'kwoocheckoutdesc',
            'kcoupon_single_text',
            'kvideo_qr_single_text1',
            'kvideo_qr_single_text2',
            'kvideo_ersalrygan_single_text1',
            'kvideo_ersalrygan_single_text2',
            'kaveh_matn_raygansms',
            'kaveh_factor_sms_text',
            'kaveh_factor_email_subject',
            'kaveh_factor_email_body'
        );
        
        if (in_array($option_key, $translatable_options) && !empty($value)) {
            // Use WPML string translation
            $translated = apply_filters('wpml_translate_single_string', $value, 'admin_texts_' . $this->prefix, $option_key);
            return $translated ? $translated : $value;
        }
        
        // Handle repeater fields
        if (is_array($value)) {
            return $this->translate_repeater_fields($value, $option_key);
        }
        
        return $value;
    }
    
    /**
     * Translate repeater field values
     */
    private function translate_repeater_fields($value, $option_key)
    {
        $repeater_fields = array(
            'kaveh_footer_menu-repeater' => array('kaveh_title_social_social', 'kaveh_title_social_two_social'),
            'pro-pic-repeater' => array('pro-pic-text'),
            'ktickets_single' => array('ktickets_single_text1', 'ktickets_single_text2'),
            'kticketsthumnail_single' => array('kticketsthumnail_single_text1'),
            'klis_single' => array('klis_single_text1', 'klis_single_text2')
        );
        
        if (isset($repeater_fields[$option_key]) && is_array($value)) {
            foreach ($value as $index => $item) {
                if (is_array($item)) {
                    foreach ($repeater_fields[$option_key] as $field_key) {
                        if (isset($item[$field_key]) && !empty($item[$field_key])) {
                            $string_name = $option_key . '_' . $index . '_' . $field_key;
                            $translated = apply_filters('wpml_translate_single_string', $item[$field_key], 'admin_texts_' . $this->prefix, $string_name);
                            if ($translated) {
                                $value[$index][$field_key] = $translated;
                            }
                        }
                    }
                }
            }
        }
        
        return $value;
    }
    
    /**
     * Register admin strings for translation
     */
    public function register_admin_strings()
    {
        if (!$this->is_wpml_active()) {
            return;
        }
        
        $options = get_option($this->prefix, array());
        
        if (empty($options)) {
            return;
        }
        
        $this->register_strings_recursively($options, $this->prefix);
    }
    
    /**
     * Register strings recursively for complex option structures
     */
    private function register_strings_recursively($options, $context, $prefix = '')
    {
        if (!is_array($options)) {
            return;
        }
        
        foreach ($options as $key => $value) {
            $string_name = $prefix ? $prefix . '_' . $key : $key;
            
            if (is_string($value) && !empty($value) && $this->is_translatable_string($key, $value)) {
                do_action('wpml_register_single_string', 'admin_texts_' . $context, $string_name, $value);
            } elseif (is_array($value)) {
                $this->register_strings_recursively($value, $context, $string_name);
            }
        }
    }
    
    /**
     * Check if a string should be translatable
     */
    private function is_translatable_string($key, $value)
    {
        // Skip URLs, colors, numbers, and other non-text values
        $skip_patterns = array(
            '/^https?:\/\//',  // URLs
            '/^#[0-9a-fA-F]{3,6}$/',  // Color codes
            '/^\d+$/',  // Pure numbers
            '/\.(jpg|jpeg|png|gif|svg|webp)$/i',  // Image extensions
            '/^icon-/',  // Icon classes
            '/^value-\d+$/'  // Option values
        );
        
        foreach ($skip_patterns as $pattern) {
            if (preg_match($pattern, $value)) {
                return false;
            }
        }
        
        // Skip certain key patterns
        $skip_keys = array(
            'url', 'link', 'color', 'icon', 'image', 'video', 'upload',
            'width', 'height', 'size', 'id', 'class', 'style'
        );
        
        foreach ($skip_keys as $skip_key) {
            if (strpos(strtolower($key), $skip_key) !== false) {
                return false;
            }
        }
        
        // Only register strings that contain actual text (not just numbers or symbols)
        return strlen($value) > 2 && preg_match('/[a-zA-Z\x{0600}-\x{06FF}]/u', $value);
    }
    
    /**
     * Show language switcher on theme options pages
     */
    public function show_language_switcher_on_options($show)
    {
        global $pagenow;
        
        if ($pagenow === 'admin.php' && isset($_GET['page']) && $_GET['page'] === 'kaveh-options') {
            return true;
        }
        
        return $show;
    }
    
    /**
     * Register strings after options are saved
     */
    public function register_strings_after_save($options)
    {
        if (!$this->is_wpml_active()) {
            return;
        }
        
        // Re-register all strings after save
        $this->register_strings_recursively($options, $this->prefix);
    }
    
    /**
     * Get translated option value
     */
    public static function get_translated_option($option_key, $default = null)
    {
        $instance = new self();
        $value = kaveh_get_option($option_key, $default);
        
        return $instance->translate_option($value, $option_key, $default);
    }
    
    /**
     * Helper function to translate post/page IDs
     */
    public static function translate_object_id($id, $type = 'post')
    {
        if (!defined('ICL_SITEPRESS_VERSION')) {
            return $id;
        }
        
        return apply_filters('wpml_object_id', $id, $type, true);
    }
    
    /**
     * Get current language code
     */
    public static function get_current_language()
    {
        if (!defined('ICL_SITEPRESS_VERSION')) {
            return 'en';
        }
        
        return apply_filters('wpml_current_language', null);
    }
    
    /**
     * Get default language code
     */
    public static function get_default_language()
    {
        if (!defined('ICL_SITEPRESS_VERSION')) {
            return 'en';
        }
        
        return apply_filters('wpml_default_language', null);
    }
}

// Initialize WPML compatibility
new KavehWPML();

/**
 * Helper functions for WPML compatibility
 */

/**
 * Get translated theme option
 */
function kaveh_get_translated_option($option_key, $default = null)
{
    return KavehWPML::get_translated_option($option_key, $default);
}

/**
 * Translate object ID (post, page, etc.)
 */
function kaveh_translate_id($id, $type = 'post')
{
    return KavehWPML::translate_object_id($id, $type);
}

/**
 * Get current language
 */
function kaveh_get_current_language()
{
    return KavehWPML::get_current_language();
}

/**
 * Check if current language is RTL
 */
function kaveh_is_rtl_language()
{
    $rtl_languages = array('ar', 'fa', 'he', 'ur', 'yi');
    return in_array(kaveh_get_current_language(), $rtl_languages);
}

/**
 * Get language-specific option
 */
function kaveh_get_language_option($option_key, $language = null, $default = null)
{
    if (!$language) {
        $language = kaveh_get_current_language();
    }
    
    $option_name = 'kaveh_frame';
    if ($language !== KavehWPML::get_default_language()) {
        $option_name .= '_' . $language;
    }
    
    $options = get_option($option_name, array());
    
    if ($option_key && isset($options[$option_key])) {
        return $options[$option_key];
    }
    
    return $option_key ? $default : $options;
}