<?php
namespace TeknoTok\AiTranslator\Integrations;

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

use TeknoTok\AiTranslator\Database\MemoryRepository;

/**
 * Class to integrate with popular SEO plugins and native WordPress SEO hooks.
 */
class SeoIntegration {
	/**
	 * Constructor. Registers translation hooks for SEO titles/descriptions and sitemaps.
	 */
	public function __construct() {
		if ( is_admin() ) {
			return;
		}

		// Register sitemap filters regardless of language context (called during sitemap builds)
		add_filter( 'wpseo_sitemap_url', array( $this, 'add_translated_yoast_urls' ), 10, 2 );
		add_filter( 'rank_math/sitemap/entries', array( $this, 'add_translated_rank_math_entries' ), 10, 2 );

		$active_lang = \TeknoTok\AiTranslator\Plugin::get_active_language();
		$settings    = get_option( 'teknotok_ait_settings', array() );
		$source_lang = $settings['source_language'] ?? 'en';

		if ( $active_lang !== $source_lang ) {
			// Native WordPress SEO Hooks
			add_filter( 'document_title_parts', array( $this, 'translate_document_title_parts' ) );
			add_filter( 'wp_title', array( $this, 'translate_seo_string' ) );
			add_filter( 'get_canonical_url', array( $this, 'filter_canonical' ) );

			// Yoast SEO Meta Hooks
			add_filter( 'wpseo_title', array( $this, 'translate_seo_string' ) );
			add_filter( 'wpseo_metadesc', array( $this, 'translate_seo_string' ) );
			add_filter( 'wpseo_canonical', array( $this, 'filter_canonical' ) );

			// Yoast SEO Social Hooks
			add_filter( 'wpseo_opengraph_title', array( $this, 'translate_seo_string' ) );
			add_filter( 'wpseo_opengraph_desc', array( $this, 'translate_seo_string' ) );
			add_filter( 'wpseo_twitter_title', array( $this, 'translate_seo_string' ) );
			add_filter( 'wpseo_twitter_description', array( $this, 'translate_seo_string' ) );

			// Rank Math Meta Hooks
			add_filter( 'rank_math/frontend/title', array( $this, 'translate_seo_string' ) );
			add_filter( 'rank_math/frontend/description', array( $this, 'translate_seo_string' ) );
			add_filter( 'rank_math/frontend/canonical', array( $this, 'filter_canonical' ) );

			// Rank Math Social Hooks
			add_filter( 'rank_math/opengraph/facebook/title', array( $this, 'translate_seo_string' ) );
			add_filter( 'rank_math/opengraph/facebook/description', array( $this, 'translate_seo_string' ) );
			add_filter( 'rank_math/opengraph/twitter/title', array( $this, 'translate_seo_string' ) );
			add_filter( 'rank_math/opengraph/twitter/description', array( $this, 'translate_seo_string' ) );

			// SEOPress Meta Hooks
			add_filter( 'seopress_titles_title', array( $this, 'translate_seo_string' ) );
			add_filter( 'seopress_titles_desc', array( $this, 'translate_seo_string' ) );
			add_filter( 'seopress_titles_canonical', array( $this, 'filter_canonical' ) );

			// SEOPress Social Hooks
			add_filter( 'seopress_social_facebook_title', array( $this, 'translate_seo_string' ) );
			add_filter( 'seopress_social_facebook_desc', array( $this, 'translate_seo_string' ) );
			add_filter( 'seopress_social_twitter_title', array( $this, 'translate_seo_string' ) );
			add_filter( 'seopress_social_twitter_desc', array( $this, 'translate_seo_string' ) );
		}
	}

	/**
	 * Generic translation handler for SEO strings.
	 *
	 * @param string $string Raw SEO title or description.
	 * @return string Translated string if cached, otherwise original.
	 */
	public function translate_seo_string( $string ) {
		if ( empty( $string ) || ! is_string( $string ) ) {
			return $string;
		}

		$active_lang = \TeknoTok\AiTranslator\Plugin::get_active_language();
		$cached = MemoryRepository::get_translation( $string, $active_lang );

		return ( false !== $cached ) ? $cached : $string;
	}

	/**
	 * Override canonical URLs to point to the language-specific version.
	 *
	 * @param string $canonical Original canonical URL.
	 * @return string Language-prefixed canonical URL.
	 */
	public function filter_canonical( $canonical ) {
		if ( empty( $canonical ) ) {
			return $canonical;
		}
		$active_lang = \TeknoTok\AiTranslator\Plugin::get_active_language();
		return \TeknoTok\AiTranslator\Frontend\UrlManager::get_clean_url_for_language( $active_lang );
	}

	/**
	 * Translate native WordPress document title parts.
	 *
	 * @param array $title_parts Title parts array.
	 * @return array Translated title parts.
	 */
	public function translate_document_title_parts( $title_parts ) {
		if ( ! is_array( $title_parts ) ) {
			return $title_parts;
		}

		if ( isset( $title_parts['title'] ) ) {
			$title_parts['title'] = $this->translate_seo_string( $title_parts['title'] );
		}
		if ( isset( $title_parts['tagline'] ) ) {
			$title_parts['tagline'] = $this->translate_seo_string( $title_parts['tagline'] );
		}

		return $title_parts;
	}

	/**
	 * Check if a translation job is completed for a specific URL and target language.
	 *
	 * @param string $url  Original source URL.
	 * @param string $lang Target language.
	 * @return bool True if the translation job status is 'completed'.
	 */
	private function is_translation_completed( $url, $lang ) {
		if ( empty( $url ) || empty( $lang ) ) {
			return false;
		}

		$post_id = url_to_postid( $url );
		if ( ! $post_id ) {
			// Fallback to true for non-post ID URLs (like home URL or custom sitemap page)
			return true;
		}

		static $cache = array();
		$cache_key = $post_id . '_' . $lang;
		if ( isset( $cache[ $cache_key ] ) ) {
			return $cache[ $cache_key ];
		}

		global $wpdb;
		$table  = $wpdb->prefix . 'teknotok_jobs';
		$status = $wpdb->get_var( $wpdb->prepare(
			"SELECT status FROM {$table} WHERE object_type = 'post' AND object_id = %d AND target_lang = %s ORDER BY id DESC LIMIT 1",
			$post_id,
			$lang
		) );

		$completed = 'completed' === $status;
		$cache[ $cache_key ] = $completed;

		return $completed;
	}

	/**
	 * Dynamically inject translated URLs into Yoast XML Sitemaps.
	 *
	 * @param string $url_xml Original URL XML string.
	 * @param array  $url     URL details array.
	 * @return string Modified XML string.
	 */
	public function add_translated_yoast_urls( $url_xml, $url ) {
		if ( empty( $url['loc'] ) ) {
			return $url_xml;
		}

		$settings = get_option( 'teknotok_ait_settings', array() );
		$targets  = $settings['target_languages'] ?? array();
		if ( empty( $targets ) ) {
			return $url_xml;
		}

		$loc       = $url['loc'];
		$extra_xml = '';

		foreach ( $targets as $lang ) {
			// Exclude if translation job is not completed
			if ( ! $this->is_translation_completed( $loc, $lang ) ) {
				continue;
			}

			$translated_url = \TeknoTok\AiTranslator\Plugin::get_translated_url_for_source( $loc, $lang );
			if ( $translated_url && $translated_url !== $loc ) {
				$extra_xml .= "\t<url>\n";
				$extra_xml .= "\t\t<loc>" . esc_url( $translated_url ) . "</loc>\n";
				if ( ! empty( $url['mod'] ) ) {
					$extra_xml .= "\t\t<lastmod>" . esc_html( $url['mod'] ) . "</lastmod>\n";
				}
				if ( ! empty( $url['chf'] ) ) {
					$extra_xml .= "\t\t<changefreq>" . esc_html( $url['chf'] ) . "</changefreq>\n";
				}
				if ( isset( $url['pri'] ) ) {
					$extra_xml .= "\t\t<priority>" . esc_html( $url['pri'] ) . "</priority>\n";
				}
				$extra_xml .= "\t</url>\n";
			}
		}

		return $url_xml . $extra_xml;
	}

	/**
	 * Dynamically inject translated URLs into Rank Math XML Sitemaps.
	 *
	 * @param array  $entries Sitemap URL entries list.
	 * @param string $type    Sitemap content type (e.g. 'post', 'page').
	 * @return array Modified entries list.
	 */
	public function add_translated_rank_math_entries( $entries, $type ) {
		if ( empty( $entries ) || ! is_array( $entries ) ) {
			return $entries;
		}

		$settings = get_option( 'teknotok_ait_settings', array() );
		$targets  = $settings['target_languages'] ?? array();
		if ( empty( $targets ) ) {
			return $entries;
		}

		$new_entries = array();
		foreach ( $entries as $entry ) {
			$loc = $entry['loc'] ?? '';
			if ( empty( $loc ) ) {
				continue;
			}

			foreach ( $targets as $lang ) {
				// Exclude if translation job is not completed
				if ( ! $this->is_translation_completed( $loc, $lang ) ) {
					continue;
				}

				$translated_url = \TeknoTok\AiTranslator\Plugin::get_translated_url_for_source( $loc, $lang );
				if ( $translated_url && $translated_url !== $loc ) {
					$new_entry        = $entry;
					$new_entry['loc'] = $translated_url;
					$new_entries[]    = $new_entry;
				}
			}
		}

		return array_merge( $entries, $new_entries );
	}
}
