<?php
/**
 * FluentC WordPress Plugin Links File.
 *
 * This file contains the WordPress functions for updating Permalinks and Routes
 *
 */

namespace FluentC\Actions;


if (! defined('ABSPATH') ) {
    exit;
}

use FluentC\Models\Hooks;
use FluentC\Services\Connect;
use FluentC\Utils\Language;
use FluentC\Services\Cache;

/**
 *  Permalinks Actions
 */
class Links implements Hooks
{


    /**
     * FluentC connection class
     *
     * @var object
     */
    protected $fluentc_connect;
    /**
     * FluentC connection class
     *
     * @var object
     */
    protected $fluentc_language;

    protected $fluentc_cache;

    private $translations_by_language = [];
    /**
     * Constructor.
     *
     * @since 1.2
     */
    public function __construct()
    {

        $this->fluentc_connect  = new Connect();
        $this->fluentc_language = new Language();
        $this->fluentc_cache = new Cache();
    }
    /**
     * Hooks for Autoloading
     *
     * @since 1.2
     */
    public function hooks() {
        $api_key = get_option('fluentc_api_key');
        
        // Only add language-specific hooks if API key exists
        if (!empty($api_key)) {
            //add_action('wp', array($this, 'add_language_code_to_home_url_later'));
            add_filter('woocommerce_get_cart_url', array($this, 'add_language_code_to_cart_url'), 10, 1);
            add_filter('query_vars', array($this, 'language_var'), 10, 3);
            add_action('init', array($this, 'flush_rewrite'), 1000);
            add_filter('rewrite_rules_array', array($this, 'fluentc_rewrite_rules_new'), 100);
			add_action('template_redirect', array($this, 'filter_template_for_home_page'), 1);
            add_filter('redirect_canonical', array($this, 'redirect_canonical_filter'), 10, 2);
        }
        
        // Always add these hooks for setup
        add_action('fluentc_activation_setup', array($this, 'set_flush_needed'));
        add_action('fluentc_admin_settings_page_save', array($this, 'set_flush_needed'));
        add_action('permalink_structure_changed', array($this, 'set_flush_needed'), 10, 2);
    }

    /**
     * HomeLink that filters after wp is ready.
     */
    public function add_language_code_to_home_url_later()
    {
        add_filter('home_url', array( $this, 'add_language_code_to_home_url' ), 10, 4);
    }

    /**
     * Updates Home page link
     *
     * @param string $url         url.
     * @param string $path        path.
     * @param string $orig_scheme orig_scheme.
     * @param string $blog_id     blog_id.
     */
    public function add_language_code_to_home_url($url, $path, $orig_scheme, $blog_id)
    {
        $language_code = $this->fluentc_language->get_fluentc_language();
    
        if (empty($language_code)) {
            return $url;
        }
    
        // Explicitly exclude REST API, oEmbed, XML-RPC, wp-admin and wp-login URLs
        // This check is on the $url WordPress is about to return.
        if (
            strpos($url, '/wp-json') !== false ||
            strpos($url, '/xmlrpc.php') !== false ||
            strpos($url, '/wp-admin') !== false ||
            strpos($url, '/feed') !== false ||
            strpos($url, '/wp-login.php') !== false
        ) {
            return $url;
        }
    
        // Get the original URL parts that WordPress was about to return
        $original_url_parts = wp_parse_url($url);
    
        // Get the base URL of the WordPress installation (e.g., https://example.com/advisor)
        $wp_installation_url = get_option('home');
        $wp_installation_parts = wp_parse_url($wp_installation_url);
        
        // Extract the base path of the WP installation, ensuring it ends with a slash (e.g., "/advisor/" or "/")
        $wp_installation_base_path = isset($wp_installation_parts['path']) ? rtrim($wp_installation_parts['path'], '/') . '/' : '/';
    
        // Get the specific path requested in the home_url() call (e.g., "my-page" or "")
        // The $path argument to this filter is what we need.
        $request_specific_path = ltrim($path, '/');
    
        // Construct the new path: /wp_installation_base_path/language_code/request_specific_path/
        $new_path_segments = [];
        if ($wp_installation_base_path !== '/') {
            $new_path_segments[] = trim($wp_installation_base_path, '/'); // e.g., "advisor"
        }
        $new_path_segments[] = $language_code; // e.g., "es"
        if (!empty($request_specific_path)) {
            $new_path_segments[] = trim($request_specific_path, '/'); // e.g., "paid-social-platforms"
        }
        
        $final_path = '/' . implode('/', array_filter($new_path_segments));
    
        // Ensure trailing slash consistency based on the original URL WordPress generated.
        // If the original path (e.g. /advisor/foo/) had a trailing slash, the new one should too, unless it's root.
        if (isset($original_url_parts['path']) && substr($original_url_parts['path'], -1) === '/' && substr($final_path, -1) !== '/' && $final_path !== '/') {
            $final_path .= '/';
        }
        // Handle case where path might become just "//" for root site with language -> fix to "/"
        if ($final_path === '//') {
            $final_path = '/';
        }

        // Rebuild the URL using components from the original $url (scheme, host, port, query, fragment)
        // but with our new $final_path.
        $new_url = ($original_url_parts['scheme'] ?? 'http') . '://' . ($original_url_parts['host'] ?? '');
        if (!empty($original_url_parts['port'])) {
            $new_url .= ':' . $original_url_parts['port'];
        }
        $new_url .= $final_path;
    
        if (!empty($original_url_parts['query'])) {
            $new_url .= '?' . $original_url_parts['query'];
        }
        if (!empty($original_url_parts['fragment'])) {
            $new_url .= '#' . $original_url_parts['fragment'];
        }
    
        return $new_url;
    }

    /**
     * Updates Permalinks
     *
     * @param string $permalink permalink.
     * @param string $post      post.
     */
    public function add_language_code_to_post( $permalink, $post )
    {
        // Assuming you have a function that returns the current language code.
        $language_code = $this->fluentc_language->get_fluentc_language();

        // If there's no language code, return the original permalink.
        if (empty($language_code) ) {
            return $permalink;
        }

        // Modify the permalink to add the language code.
        $url_parts = wp_parse_url($permalink);
        $path      = '/' . $language_code . $url_parts['path'];

        // Rebuild the URL with the language code.
        $new_permalink = $url_parts['scheme'] . '://' . $url_parts['host'] . $path;
        if (! empty($url_parts['query']) ) {
            $new_permalink .= '?' . $url_parts['query'];
        }
        if (! empty($url_parts['fragment']) ) {
            $new_permalink .= '#' . $url_parts['fragment'];
        }

        return $new_permalink;
    }
/**
 * Redirect Canonical Filter
 *
 * Prevents WordPress from performing a canonical redirect on language-prefixed URLs.
 * This is much more performant than the previous implementation and directly ties into the rewrite rules.
 *
 * @param string $redirect_url  The URL to redirect to.
 * @param string $requested_url The original requested URL.
 * @return string|false The redirect URL or false to prevent redirection.
 */
    public function redirect_canonical_filter($redirect_url, $requested_url)
    {
        // If fluentc_language query var is set, it means this is a translated URL.
        // We should not allow WordPress to perform a canonical redirect, as it would
        // remove our language prefix.
        if (get_query_var('fluentc_language')) {
            return false;
        }

        return $redirect_url;
    }
    /**
     * Updates Permalink for Cart Link
     *
     * @param string $cart_url cart_url .
     */
    public function add_language_code_to_cart_url( $cart_url )
    {
        // Assuming you have a function that returns the current language code.
        $language_code = $this->fluentc_language->get_fluentc_language();

        // If there's no language code, return the original cart URL.
        if (empty($language_code) ) {
            return $cart_url;
        }

        // Modify the cart URL to add the language code.
        $url_parts = wp_parse_url($cart_url);
        // Ensure the path includes the leading '/'.
        $modified_path = '/' . trim($language_code . '/' . ltrim($url_parts['path'], '/'), '/');

        // Rebuild the URL with the language code.
        $new_cart_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $modified_path;
        if (! empty($url_parts['query']) ) {
            $new_cart_url .= '?' . $url_parts['query'];
        }
        if (! empty($url_parts['fragment']) ) {
            $new_cart_url .= '#' . $url_parts['fragment'];
        }

        return $new_cart_url;
    }

    /**
     * Updates Permalinks
     *
     * @param string $permalink permalink.
     * @param string $post      post.
     */
    public function add_language_code_to_permalink( $permalink, $post )
    {
        // Assuming you have a function that returns the current language code.
        $language_code = $this->fluentc_language->get_fluentc_language();

        // If there's no language code, return the original permalink.
        if (empty($language_code) ) {
            return $permalink;
        }

        // Modify the permalink to add the language code.
        $url_parts = wp_parse_url($permalink);
        $path      = '/' . $language_code . $url_parts['path'];

        // Rebuild the URL with the language code.
        $new_permalink = $url_parts['scheme'] . '://' . $url_parts['host'] . $path;
        if (! empty($url_parts['query']) ) {
            $new_permalink .= '?' . $url_parts['query'];
        }
        if (! empty($url_parts['fragment']) ) {
            $new_permalink .= '#' . $url_parts['fragment'];
        }

        return $new_permalink;
    }

    // Set this flag when something happens that requires a flush
function set_flush_needed() {
    update_option('fluentc_need_flush_rewrite', true);
}

    /**
     * Updates Flush ReWrite Rules
     */
    public function flush_rewrite() {
		 flush_rewrite_rules();
        // Get option that indicates if we need to flush
        $flush_needed = get_option('fluentc_need_flush_rewrite', false);
        
        if ($flush_needed) {
            flush_rewrite_rules();
            // Reset the flag so we don't flush again until needed
            update_option('fluentc_need_flush_rewrite', false);
        }
    }

    /**
     * Adds Language Var
     *
     * @param array $vars All WordPress Vars.
     */
    public function language_var( $vars )
    {
        $vars[] = 'fluentc_language'; // 'fluentc_language' is the name of path variable.
        return $vars;
    }

  /**
 * Modify rewrite rules to handle language prefixes for all existing rules
 * with special handling for the home page and non-English source languages
 * 
 * @param array $rules WordPress rewrite rules
 * @return array Modified rewrite rules
 */
public function fluentc_rewrite_rules_new($rules) {
    // Get API key
    $widget_id = is_multisite() ? get_blog_option(get_current_blog_id(), 'fluentc_api_key') : get_option('fluentc_api_key');
    if (!$widget_id) {
        return $rules;
    }
    
    // Get language information
    $languages = $this->fluentc_connect->get_language_list($widget_id);
    if (empty($languages)) {
        return $rules;
    }
    
    $source_language = $this->fluentc_language->fluentc_site_language();
    
    // Check if we're using a static home page
    $show_on_front = get_option('show_on_front');
    $page_on_front = get_option('page_on_front');
    
    // Prepare the new rules array
    $new_rules = array();
    
    // Add language-specific rules for each language
    foreach ($languages as $language) {
        if ($language === $source_language) {
            continue; // Skip default language
        }
        
        // Special handling for home page
        if ($show_on_front === 'page' && $page_on_front) {
            // This rule mirrors WordPress's handling of the home page with a static front page
            $new_rules['^' . $language . '/?$'] = 'index.php?fluentc_language=' . $language . '&page_id=' . $page_on_front;
        } else {
            // Default home page (latest posts)
            $new_rules['^' . $language . '/?$'] = 'index.php?fluentc_language=' . $language;
        }
        
        // Process each existing rule and create a corresponding language-prefixed version
        foreach ($rules as $pattern => $query) {
            // Create the language-prefixed pattern by adding the language code at the start
            $language_pattern = '^' . $language . '/' . $pattern;
            
            // IMPORTANT: Keep the original query structure, just append the language parameter
            // This preserves the $matches references
            $language_query = preg_replace('/^index\.php\?/', 'index.php?fluentc_language=' . $language . '&', $query);
            
            // Add the new rule
            $new_rules[$language_pattern] = $language_query;
        }
    }
    
    // Merge with original rules, giving priority to our language rules
    // Original rules will still work for the default language
    $final_rules = array_merge($new_rules, $rules);
    
    return $final_rules;
}

/**
 * Filter the template for home page in different languages
 * Enhanced to properly handle non-English source languages
 */
public function filter_template_for_home_page() {
    global $wp_query;
    
    // Check if this is a language-prefixed page
    if (!isset($wp_query->query_vars['fluentc_language'])) {
        return;
    }
    
    $language = $wp_query->query_vars['fluentc_language'];
    $source_language = $this->fluentc_language->fluentc_site_language();
    
    // Only proceed if this is a different language than the source 
    // and either we have no posts or this is detected as home when it shouldn't be
    if ($language !== $source_language && 
        (empty($wp_query->posts) || (is_home() && !empty($wp_query->query)))) {
        
        // Get the requested path
        $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        $path = wp_parse_url($request_uri, PHP_URL_PATH);
        
        // Remove language prefix from path to get the source path
        $path = preg_replace('/^\/' . preg_quote($language, '/') . '\//', '/', $path);
        $path = rtrim($path, '/');
        $slug = trim($path, '/');
        
        // Check if we're dealing with homepage or a specific page
        if (empty($slug) || $slug === $language) {
            // This is the homepage in a different language
            $show_on_front = get_option('show_on_front');
            $page_on_front = get_option('page_on_front');
            
            if ($show_on_front === 'page' && $page_on_front) {
                // Set up the main query to load the front page
                $wp_query->is_home = false;
                $wp_query->is_page = true;
                $wp_query->is_singular = true;
                $wp_query->is_front_page = true;
                
                // Set the queried object to be the front page
                $front_page = get_post($page_on_front);
                $wp_query->queried_object = $front_page;
                $wp_query->queried_object_id = $page_on_front;
                $wp_query->post = $front_page;
                $wp_query->posts = array($front_page);
                $wp_query->post_count = 1;
                
                // Force using the page template
                add_filter('template_include', function($template) use ($front_page) {
                    if (is_object($front_page) && isset($front_page->ID)) {
                        $page_template = get_page_template_slug($front_page->ID);
                        if ($page_template) {
                            $templates = array($page_template);
                        } else {
                            $templates = array('page.php', 'singular.php', 'index.php');
                        }
                        
                        $new_template = locate_template($templates);
                        if ($new_template) {
                            return $new_template;
                        }
                    }
                    return $template;
                }, 99);
            }
        } else if (empty($wp_query->posts)) {
            // This is a specific page that failed to resolve - try to find it
            $page = get_page_by_path($slug);
            
            if ($page) {
                // Set up the query to display this page
                $wp_query->is_home = false;
                $wp_query->is_page = true;
                $wp_query->is_singular = true;
                $wp_query->post = $page;
                $wp_query->posts = array($page);
                $wp_query->post_count = 1;
                $wp_query->queried_object = $page;
                $wp_query->queried_object_id = $page->ID;
                
                // Add debugging info if needed
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('FluentC: Resolved page ' . $slug . ' to ID ' . $page->ID);
                }
            } else if (defined('WP_DEBUG') && WP_DEBUG) {
                // Log for debugging if the page couldn't be found
                error_log('FluentC: Could not resolve page for path: ' . $slug);
            }
        }
    }
}
}
