<?php
/**
 * FluentC Manager Class.
 *
 * @package FluentCPlugin
 */


namespace FluentC;

use FluentC\Models\FluentC_Links_Model;
use FluentC\Services\PLL_Language;
use FluentC\Services\Connect;
use FluentC\Utils\Language;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class Polylang {
    public $links_model;
	public $options;
	public $model;
	public $curlang; // Current language object for Polylang compatibility

	protected $fluentc_language;
	protected $fluentc_connenct;

	
	public function __construct() {
        $this->links_model = new FluentC_Links_Model();
		$this->model = new PLL_Language();
		$this->fluentc_connenct = new Connect();
		$this->fluentc_language = new Language();
		$this->options = $this->links_model->options;
		
		// Initialize curlang property for Polylang compatibility
		$this->curlang = $this->fluentc_language->get_fluentc_language();
		
		add_action( 'init', array( $this, 'init_hooks' ), 1 );
	}

/*	public function __call($name, $arguments) {
        error_log("Polylang method called: " . $name);
        
        switch($name) {
            case 'pll_get_post_translations':  
				$post_id = isset($arguments[0]) ? $arguments[0] : null;
               
                $languages = $this->fluentc_connenct->get_pll_fluentc_languages_list();
                
                // Create translations array using the same post ID for each language.
                $translations = [];
                foreach ($languages as $lang) {
                    $translations[$lang->slug] = $post_id;
                }
                
                return $translations;
            
            default:
                error_log("Unhandled Polylang method: " . $name);
                return null;
        }
    } */
	/**
	 * Register hooks to replace Polylang functionality
	 */
	public function init_hooks() {
		//add_filter( 'locale', array( $this, 'set_locale' ) );
	}

	/**
 * Allow the canonical redirect for default language if "Hide URL language information for default language" 
 * is turned on in FluentC/Polylang settings
 *
 * @param array $query The WordPress query variables
 * @param array $old_query Original query variables
 * @param array $uri_parts Parts of the URI including language information
 * @param array $pm_query Permalink Manager query info
 * @param string $content_type Type of content being accessed
 *
 * @return array Modified query
 */
public function pl_allow_canonical_redirect($query, $old_query, $uri_parts, $pm_query, $content_type) {
    // First check if we have polylang global set up
    global $polylang;

    if (empty($polylang) || empty($polylang->links_model) || empty($polylang->links_model->options)) {
        return $query;
    }

    // Run only if we have ID and language data
    if (!empty($pm_query['id']) && !empty($pm_query['lang'])) {
        // Get language from URL using our implementation
        $url_lang = $polylang->links_model->get_language_from_url();
        
        // Get default language using existing FluentC function
        $fluentc_language = new \FluentC\Utils\Language();
        $def_lang = $fluentc_language->fluentc_site_language();
        
        // Get hide_default option from our FluentC links model
        $hide_default = !empty($polylang->links_model->options['hide_default']);
        $force_lang = isset($polylang->options['force_lang']) ? $polylang->options['force_lang'] : 1;
        
        // A. Check if URL contains default language code but "hide default" is enabled
        //    OR using different domains for languages (force_lang == 3)
        if (($url_lang == $def_lang && $hide_default) || $force_lang == 3) {
            unset($query['do_not_redirect']);
        } 
        // B. Check if URL does NOT contain default language code but "hide default" is disabled
        else if (empty($url_lang) && !$hide_default) {
            unset($query['do_not_redirect']);
        }
    }

    return $query;
}


/**
 * Detect the language of requested content and add it to $uri_parts array
 *
 * @param array $uri_parts Current URI parts
 * @param string $request_url The requested URL
 * @param string $endpoints URL endpoints string
 * @return array Modified URI parts with language information
 */
public function detect_uri_language($uri_parts, $request_url, $endpoints) {
    // Get available languages
    $fluentc_connect = new \FluentC\Services\Connect();
    $widgetapikey = get_option('fluentc_api_key');
    $languages_list = $fluentc_connect->get_language_list($widgetapikey);
    
    if (empty($languages_list) || !is_array($languages_list)) {
        return $uri_parts;
    }
    
    $languages_pattern = implode('|', $languages_list);
    
    // Check URL configuration (domain per language)
    if (!empty($this->options['force_lang']) && $this->options['force_lang'] == 3) {
        if (!empty($this->options['domains'])) {
            $domains = (array)$this->options['domains'];
            
            // Clean domains for comparison
            foreach ($domains as &$domain) {
                $domain = preg_replace('/((http(s)?:\/\/(www\.)?)|(www\.))?(.+?)\/?$/', 'http://$6', $domain);
            }
            
            // Remove domain from request URL
            $request_url = trim(str_replace($domains, "", $request_url), "/");
        }
        
        $default_language = "";
    } else {
        $default_language = $this->fluentc_language->fluentc_site_language();
    }
    
    // Parse the URL to extract language and other parts
    if (!empty($languages_pattern)) {
        preg_match("/^(?:({$languages_pattern})\/)?(.+?)(?|\/({$endpoints})(?|\/(.*)|$)|\/()([\d]+)\/?)?$/i", $request_url, $regex_parts);
        
        $uri_parts['lang'] = (!empty($regex_parts[1])) ? $regex_parts[1] : $default_language;
        $uri_parts['uri'] = (!empty($regex_parts[2])) ? $regex_parts[2] : "";
        $uri_parts['endpoint'] = (!empty($regex_parts[3])) ? $regex_parts[3] : "";
        $uri_parts['endpoint_value'] = (!empty($regex_parts[4])) ? $regex_parts[4] : "";
    }
    
    return $uri_parts;
}

/**
 * Append language code as URL prefix
 *
 * @param string $base URL base
 * @param mixed $element Post or term object
 * @param string $language_code Optional language code override
 * @return string Modified URL base with language prefix
 */
public function prepend_lang_prefix($base, $element, $language_code = '') {
    if (!empty($element) && empty($language_code)) {
        $language_code = $this->fluentc_language->get_fluentc_language($element);
        
        // Use language parameter from GET if in admin and no language detected
        $language_code = (is_admin() && empty($language_code) && !empty($_GET['lang'])) 
            ? sanitize_key($_GET['lang']) 
            : $language_code;
    }
    
    // Adjust URL base
    if (!empty($language_code)) {
        $default_language_code = $this->fluentc_language->fluentc_site_language();
        $home_url = get_home_url();
        
        // Check if default language code should be hidden
        $hide_prefix_for_default_lang = !empty($this->links_model->options['hide_default']);
        
        // Check URL configuration
        $force_lang = isset($this->options['force_lang']) ? $this->options['force_lang'] : 1;
        
        // A. Different domain per language
        if ($force_lang == 3) {
            if (!empty($this->options['domains']) && !empty($this->options['domains'][$language_code])) {
                $base = trim($this->options['domains'][$language_code], "/");
                
                // Append URL scheme
                if (!preg_match("~^(?:f|ht)tps?://~i", $base)) {
                    $scheme = parse_url($home_url, PHP_URL_SCHEME);
                    $base = "{$scheme}://{$base}";
                }
            }
        } 
        // B. Language as subdomain
        else if ($force_lang == 2) {
            if ($hide_prefix_for_default_lang && ($default_language_code == $language_code)) {
                return $base;
            } else {
                $base = preg_replace('/(https?:\/\/)/', "$1{$language_code}.", $home_url);
            }
        } 
        // C. Language in URL path (default)
        else {
            if ($hide_prefix_for_default_lang && ($default_language_code == $language_code)) {
                return $base;
            } else {
                $base .= "/{$language_code}";
            }
        }
    }
    
    return $base;
}

/**
 * Support for pagination endpoints translated by Polylang
 *
 * @param string $endpoints Current endpoints string
 * @return string Modified endpoints including translated pagination endpoint
 */
public function pl_translate_pagination_endpoint($endpoints) {
    $pagination_endpoint = $this->pl_get_translated_slugs('paged');
    
    if (!empty($pagination_endpoint) && !empty($pagination_endpoint['translations'])) {
        $current_language = $this->fluentc_language->get_fluentc_language();
        
        if (!empty($current_language) && !empty($pagination_endpoint['translations'][$current_language])) {
            $endpoints .= "|" . $pagination_endpoint['translations'][$current_language];
        }
    }
    
    return $endpoints;
}

/**
 * Get back the original name of the translated endpoint
 *
 * @param array $uri_parts Current URI parts
 * @param string $request_url The requested URL
 * @param string $endpoints URL endpoints string
 * @return array Modified URI parts
 */
public function pl_detect_pagination_endpoint($uri_parts, $request_url, $endpoints) {
    if (!empty($uri_parts['endpoint'])) {
        $pagination_endpoint = $this->pl_get_translated_slugs('paged');
        
        if (!empty($pagination_endpoint['translations']) && 
            in_array($uri_parts['endpoint'], $pagination_endpoint['translations'])) {
            $uri_parts['endpoint'] = $pagination_endpoint['slug'];
        }
    }
    
    return $uri_parts;
}

/**
 * Display the language code in URI editor table
 *
 * @param string $output Current output HTML
 * @param string $column Column name
 * @param object $element Post or term object
 * @return string Modified output with language information
 */
public function uri_editor_get_lang_col($output, $column, $element) {
    $language_code = $this->fluentc_language->get_fluentc_language($element);
    
    if (!empty($language_code)) {
        $output .= sprintf(" | <span><strong>%s:</strong> %s</span>", 
                          __('Language', 'fluentc-translation'), 
                          $language_code);
    }
    
    return $output;
}

/**
 * Add language filter to URI editor
 *
 * @param string $html Current filter HTML
 * @param string $content_type Content type being filtered
 * @return string Modified HTML with language filter
 */
public function uri_editor_filter_lang($html, $content_type) {
    $choices = [];
    
    // Get languages from FluentC
    $fluentc_connect = new \FluentC\Services\Connect();
    $widgetapikey = get_option('fluentc_api_key');
    $languages = $fluentc_connect->get_display_language_list($widgetapikey);
    
    if (!empty($languages)) {
        foreach ($languages as $language) {
            $choices[$language[1]] = $language[0];
        }
        
        // Add "All languages" option
        $choices = array_merge(['all' => __('All languages', 'fluentc-translation')], $choices);
        
        // Create a select field
        // Note: This depends on how your UI elements are generated
        $select_field = '<select name="langcode" id="langcode">';
        $current_lang = isset($_REQUEST['langcode']) ? esc_attr($_REQUEST['langcode']) : '';
        
        foreach ($choices as $value => $label) {
            $selected = ($current_lang === $value) ? ' selected="selected"' : '';
            $select_field .= '<option value="' . esc_attr($value) . '"' . $selected . '>' . esc_html($label) . '</option>';
        }
        
        $select_field .= '</select>';
        
        $html = '<div class="alignleft actions">' . $select_field . '</div>';
    }
    
    return $html;
}

/**
 * Get original slugs without translation
 * Since FluentC doesn't translate slugs, this returns the original slug structure
 *
 * @param string $slug Optional slug to retrieve
 * @return array Array with slug structure but no translations
 */
public function pl_get_translated_slugs($slug = '') {
    // For Permalink Manager compatibility, return a structure with the original slug
    // but no actual translations since FluentC doesn't translate slugs
    
    if (!empty($slug)) {
        // Return a basic structure with just the original slug
        // For pagination, 'page' is the standard
        $default_slug = ($slug === 'paged') ? 'page' : $slug;
        
        // Get current language
        $current_language = $this->fluentc_language->get_fluentc_language();
        
        // Get all available languages
        $fluentc_connect = new \FluentC\Services\Connect();
        $widgetapikey = get_option('fluentc_api_key');
        $languages = $fluentc_connect->get_language_list($widgetapikey);
        
        // Initialize translations array
        $translations = [];
        
        // For each language, use the same original slug
        // This emulates Polylang's structure without actual translations
        if (!empty($languages) && is_array($languages)) {
            foreach ($languages as $lang_code) {
                $translations[$lang_code] = $default_slug;
            }
        } elseif (!empty($current_language)) {
            // Fallback if languages list is unavailable
            $translations[$current_language] = $default_slug;
        }
        
        return [
            'slug' => $default_slug,
            'translations' => $translations
        ];
    }
    
    // Return empty array if no slug specified
    return [];
}

/**
 * Filter SQL query in URI editor by language
 *
 * @param string $sql_query Current SQL query
 * @param array $sql_parts SQL query parts
 * @param bool $is_taxonomy Whether query is for taxonomies
 * @return string Modified SQL query filtered by language
 */
public function uri_editor_filter_sql_query($sql_query, $sql_parts, $is_taxonomy) {
    global $wpdb;
    
    if (isset($_GET['langcode']) && $_GET['langcode'] !== 'all') {
        $lang = esc_sql($_GET['langcode']);
        
        // We need different approaches for taxonomies vs posts
        if ($is_taxonomy) {
            // Use term relationships table to filter terms by language
            $join = "{$sql_parts['start']} INNER JOIN {$wpdb->term_relationships} AS tr ON tt.term_id = tr.object_id ";
            
            // This is a simplified approach - proper implementation would need actual language term taxonomy ID
            $lang_term_ttid = 0; // This should be dynamically determined
            if ($lang_term_ttid) {
                $join .= "AND tr.term_taxonomy_id = {$lang_term_ttid} ";
            }
        } else {
            // For posts, create a join to filter by language meta
            $join = "{$sql_parts['start']} INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id AND pm.meta_key = 'fluentc_language' AND pm.meta_value = '{$lang}' ";
        }
        
        // Replace the original SQL start with our join
        if (!empty($join)) {
            $sql_query = str_replace($sql_parts['start'], $join, $sql_query);
        }
    }
    
    return $sql_query;
}
	/**
	 * Set locale function to replace Polylang functionality
	 */
	public function set_locale( $locale ) {
		// Always return the original locale unchanged
		// FluentC should never modify WordPress locale
		return $locale;
	}

	/**
	 * Update the current language property
	 * This should be called when the language changes
	 */
	public function update_curlang() {
		$this->curlang = $this->fluentc_language->get_fluentc_language();
		return $this->curlang;
	}

	/**
	 * Get the current language (Polylang compatibility)
	 */
	public function get_current_language() {
		return $this->curlang;
	}

	/**
	 * Magic getter to ensure curlang is always up-to-date
	 */
	public function __get($name) {
		if ($name === 'curlang') {
			// Update curlang before returning it
			$this->update_curlang();
			return $this->curlang;
		}
		
		// For other properties, return null to prevent undefined property errors
		return null;
	}

	/**
	 * Check if FluentC is active
	 */
	public function is_fluentc_active() {
		return true; // Replace with your logic to check if FluentC is active.
	}

	/**
	 * Get the locale for FluentC
	 */
	public function get_fluentc_locale() {
		return 'en'; // Replace with your logic to get the current locale.
	}
}