<?php
/**
 * FluentC WordPress Plugin File.
 *
 * This file contains the adjustments for the Yoast Plugin
 *
 * @package FluentCPlugin
 * @author  FluentC <wp@fluentc.io>
 */

namespace FluentC\Actions;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use FluentC\Models\Hooks;
use FluentC\Models\Htmltags;
use FluentC\Services\Connect;
use FluentC\Utils\Language;
use FluentC\Services\Cache;

/**
 * YoastSEO specific modifications
 */
class Yoast implements Hooks {

	/**
	 * FluentC connection class
	 *
	 * @var object
	 */
	protected $fluentc_connenct;

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

	/**
	 * FluentC cache class
	 *
	 * @var object
	 */
	protected $fluentc_cache;

	/**
	 * FluentC htmltags class
	 *
	 * @var object
	 */
	protected $fluentc_htmltags;

	/**
	 * Constructor.
	 *
	 * @since 1.2
	 */
	public function __construct() {
		$this->fluentc_connenct = new Connect();
		$this->fluentc_language = new Language();
		$this->fluentc_cache = new Cache();
		$this->fluentc_htmltags = new Htmltags();

	}
	/**
	 * Hooks for Autoloading
	 *
	 * @since 1.2
	 */
	public function hooks() {

		//add_filter( 'wpseo_metadesc', array( $this, 'yoast_filter_description' ), 10, 1 );
		//add_filter( 'wpseo_title', array( $this, 'yoast_filter_description' ), 10, 1 );
		//add_filter('wpseo_sitemap_url', array($this, 'modify_sitemap_entries'), 10, 2);
		//add_filter('wpseo_sitemap_index', array($this, 'add_language_sitemaps_to_index'), 10, 1);
		add_filter('wpseo_sitemap_index', array($this, 'add_sitemap_custom_items'), 10, 1);
		add_action('init', array($this, 'register_language_sitemaps'));
		
	}

	/**
 * Modify sitemap entries to include translated URLs
 *
 * @param array  $entries Array of sitemap entries
 * @param string $type    Type of sitemap (posts, pages, etc)
 * @return array Modified sitemap entries
 */
public function modify_sitemap_entries($entries, $type) {
    // Skip if no entries
    if (empty($entries)) {
        return $entries;
    }

    // Get available languages
    $widgetapikey  = get_option( 'fluentc_api_key' );
	if (empty($widgetapikey)) {
		return $entries;
	}

    $languages = $this->fluentc_connenct->get_display_language_list($widgetapikey);
    
    // If no languages configured, return original entries
    if (empty($languages)) {
        return $entries;
    }

    $modified_entries = [];
    $site_language = $this->fluentc_language->fluentc_site_language();

    // Keep original entries (default language)
    $modified_entries = $entries;

    // Add entries for each additional language
    foreach ($languages as $language) {
        $language_code = $language[1];

        // Skip default language as it's already included
        if ($language_code === $site_language) {
            continue;
        }

       // foreach ($entries as $entry) {
		 $entry = $entries;
            $new_entry = $entry;
            $new_entry['loc'] = $this->fluentc_htmltags->add_language_code_to_link($language_code, $entry['loc'] );
            
            // Maintain priority and frequency if set
            if (isset($entry['mod'])) {
                $new_entry['mod'] = $entry['mod'];
            }
            if (isset($entry['priority'])) {
                $new_entry['priority'] = $entry['priority'];
            }
            if (isset($entry['changefreq'])) {
                $new_entry['changefreq'] = $entry['changefreq'];
            }

            $modified_entries[] = $new_entry;
       // }
    }

    return $modified_entries;
}

/**
 * Generate sitemap content for a specific language
 *
 * @param string $content The initial content (empty)
 * @param string $type The sitemap type (language code in our case)
 * @return string The XML sitemap content
 */
public function generate_language_sitemap($content, $type) {
    // Initialize XML
    $output = '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
    $output .= 'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" ';
    $output .= 'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
    
    // Get all sitemaps
    global $wpseo_sitemaps;
    $sitemap_registry = $wpseo_sitemaps->registry;
    $providers = $sitemap_registry->get_providers();
    
    $urls = [];
    foreach ($providers as $provider) {
        // Get URLs for each sitemap type
        $links = $provider->get_index_links();
        if (!empty($links)) {
            foreach ($links as $link) {
                $sitemap_content = $wpseo_sitemaps->get_sitemap_from_provider(basename($link['loc'], '.xml'));
                if ($sitemap_content) {
                    $xml = new \SimpleXMLElement($sitemap_content);
                    foreach ($xml->url as $url) {
                        $urls[] = array(
                            'loc' =>  $this->fluentc_htmltags->add_language_code_to_link($type, (string)$url->loc),
                            'lastmod' => isset($url->lastmod) ? (string)$url->lastmod : '',
                            'changefreq' => isset($url->changefreq) ? (string)$url->changefreq : '',
                            'priority' => isset($url->priority) ? (string)$url->priority : ''
                        );
                    }
                }
            }
        }
    }

    // Add URLs to sitemap
    foreach ($urls as $url) {
        $output .= "\t<url>\n";
        $output .= "\t\t<loc>" . esc_url($url['loc']) . "</loc>\n";
        if (!empty($url['lastmod'])) {
            $output .= "\t\t<lastmod>" . esc_html($url['lastmod']) . "</lastmod>\n";
        }
        if (!empty($url['changefreq'])) {
            $output .= "\t\t<changefreq>" . esc_html($url['changefreq']) . "</changefreq>\n";
        }
        if (!empty($url['priority'])) {
            $output .= "\t\t<priority>" . esc_html($url['priority']) . "</priority>\n";
        }
        $output .= "\t</url>\n";
    }

    $output .= "</urlset>";
    return $output;
}

public function register_language_sitemaps() {
    global $wpseo_sitemaps;
    
    if (!$wpseo_sitemaps) {
        return;
    }

    // Get available languages
    $widget_id  = get_option( 'fluentc_api_key' );
	if (empty($widget_id)) {
		return;
	}
    $languages = $this->fluentc_connenct->get_display_language_list($widget_id);
    $site_language = $this->fluentc_language->fluentc_site_language();

    foreach ($languages as $language) {
        $language_code = $language[1];
        
        // Skip default language as it's handled by default sitemaps
        if ($language_code === $site_language) {
            continue;
        }

        add_filter('wpseo_sitemap_' . $language_code . '_content', array($this, 'generate_language_sitemap'), 10, 2);
    }
}

public function add_language_sitemaps_to_index($index) {
	if (!is_array($index)) {
        $index = array();
    }
    // Get available languages
    $widget_id  = get_option( 'fluentc_api_key' );
	if (empty($widget_id)) {
		return;
	}
    $languages = $this->fluentc_connenct->get_display_language_list($widget_id);
    $site_language = $this->fluentc_language->fluentc_site_language();
	$modified_index = $index;
	// Get the current time in W3C format for lastmod
    $lastmod = gmdate('c');

    foreach ($languages as $language) {
        $language_code = $language[1];
        
        if ($language_code === $site_language) {
            continue;
        }

        $modified_index[] = array(
            'loc' => home_url($language_code . '-sitemap.xml'),
			'lastmod' => $lastmod
        );
    }

    return $modified_index;
}

public function add_sitemap_custom_items( $sitemap_custom_items ) {
    $sitemap_custom_items .= '
<sitemap>
<loc>https://www.example.com/external-sitemap-1.xml</loc>
<lastmod>2017-05-22T23:12:27+00:00</lastmod>
</sitemap>';
    return $sitemap_custom_items;
}
}
