<?php
namespace TeknoTok\AiTranslator\Integrations;

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

use TeknoTok\AiTranslator\Database\MemoryRepository;

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

		if ( ! \TeknoTok\AiTranslator\Integrations\LicenseManager::is_premium_active() ) {
			return;
		}

		$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 ) {
			// Yoast SEO
			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' ) );

			// Rank Math
			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' ) );

			// SEOPress
			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' ) );
		}
	}

	/**
	 * 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 );
	}
}
