<?php
namespace TeknoTok\AiTranslator\Frontend;

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

/**
 * Controller to handle browser language detection prompts.
 */
class RedirectController {
	/**
	 * Constructor. Hooks into footer.
	 */
	public function __construct() {
		if ( is_admin() ) {
			return;
		}

		add_action( 'template_redirect', array( $this, 'redirect_inactive_language_request' ), 0 );
		add_action( 'wp_footer', array( $this, 'render_redirection_prompt' ) );
	}

	/**
	 * Redirect stale supported-language 404 URLs to the source-language URL.
	 *
	 * This protects indexed URLs after a target language is removed. Active
	 * translated languages continue to resolve normally; only supported language
	 * prefixes that are no longer configured are redirected.
	 *
	 * @return void
	 */
	public function redirect_inactive_language_request() {
		if ( function_exists( 'is_404' ) && ! is_404() ) {
			return;
		}

		$redirect_url = $this->get_inactive_language_source_url();
		if ( empty( $redirect_url ) ) {
			return;
		}

		wp_safe_redirect( $redirect_url, 301, 'TeknoTok AI Translator' );
		exit;
	}

	/**
	 * Build the clean source URL for an inactive language-prefixed request.
	 *
	 * @param string|null $request_uri Optional request URI for tests.
	 * @param array|null  $settings    Optional settings for tests.
	 * @return string Source-language URL or empty string when no redirect is needed.
	 */
	public function get_inactive_language_source_url( $request_uri = null, $settings = null ) {
		if ( null === $request_uri ) {
			$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		}

		if ( empty( $request_uri ) ) {
			return '';
		}

		if ( null === $settings ) {
			$settings = get_option( 'teknotok_ait_settings', array() );
		}

		$targets   = array_values( array_unique( array_filter( array_map( 'sanitize_key', (array) ( $settings['target_languages'] ?? array() ) ) ) ) );
		$supported = \TeknoTok\AiTranslator\Plugin::get_supported_language_codes();

		$request_path = parse_url( $request_uri, PHP_URL_PATH );
		if ( ! is_string( $request_path ) ) {
			return '';
		}

		$home       = rtrim( (string) get_option( 'home' ), '/' );
		$home_parts = parse_url( $home );
		$home_path  = isset( $home_parts['path'] ) ? trim( (string) $home_parts['path'], '/' ) : '';
		$path       = trim( $request_path, '/' );
		$has_trailing_slash = '/' === substr( $request_path, -1 );

		if ( '' !== $home_path && 0 === strpos( $path, $home_path ) ) {
			$path = trim( substr( $path, strlen( $home_path ) ), '/' );
		}

		if ( '' === $path ) {
			return '';
		}

		$segments      = explode( '/', $path );
		$first_segment = sanitize_key( $segments[0] ?? '' );

		if ( ! in_array( $first_segment, $supported, true ) || in_array( $first_segment, $targets, true ) ) {
			return '';
		}

		$source_segments = array_slice( $segments, 1 );
		$source_path     = implode( '/', $source_segments );
		if ( '' !== $source_path && $has_trailing_slash ) {
			$source_path .= '/';
		}

		if ( $this->is_internal_source_path( $source_path ) ) {
			return '';
		}

		$redirect_url = $home . '/' . ltrim( $source_path, '/' );
		$query        = parse_url( $request_uri, PHP_URL_QUERY );
		if ( is_string( $query ) && '' !== $query ) {
			$redirect_url .= '?' . $query;
		}

		return esc_url_raw( $redirect_url );
	}

	/**
	 * Check whether the cleaned source path points at a WordPress internal path.
	 *
	 * @param string $path Source path without a language prefix.
	 * @return bool True when the path should not be redirected.
	 */
	private function is_internal_source_path( $path ) {
		return (bool) preg_match( '#^(wp-admin|wp-json|wp-login\.php|wp-cron\.php|wp-content|wp-includes|xmlrpc\.php)(/|$)#i', ltrim( (string) $path, '/' ) );
	}

	/**
	 * Injects the redirection banner container and parameters.
	 *
	 * @return void
	 */
	public function render_redirection_prompt() {
		$settings = get_option( 'teknotok_ait_settings', array() );
		$detect_browser = $settings['detect_browser'] ?? '1';

		if ( '1' !== $detect_browser ) {
			return;
		}

		$targets = \TeknoTok\AiTranslator\Plugin::normalize_target_languages( $settings['target_languages'] ?? array(), $settings['source_language'] ?? 'en' );
		if ( empty( $targets ) ) {
			return;
		}

		$languages = \TeknoTok\AiTranslator\Plugin::get_supported_languages();

		// Pass target languages configuration to JavaScript
		$targets_mapped = array();
		foreach ( $targets as $lang ) {
			$targets_mapped[ $lang ] = $languages[ $lang ] ?? $lang;
		}

		$prompts = $this->get_redirect_prompts( $targets_mapped );

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

		// If user is already on a translated locale, do not prompt
		if ( $active_lang !== $source_lang ) {
			return;
		}

		?>
		<div id="teknotok-ait-redirect-prompt" class="teknotok-ait-banner notranslate" translate="no" style="display:none;" data-targets="<?php echo esc_attr( json_encode( $targets_mapped ) ); ?>" data-prompts="<?php echo esc_attr( json_encode( $prompts ) ); ?>">
			<div class="teknotok-ait-banner-content">
				<span class="teknotok-ait-banner-text">
					<?php esc_html_e( 'It looks like your browser language is %lang_name%. Would you like to switch?', 'teknotok-ai-translator' ); ?>
				</span>
				<div class="teknotok-ait-banner-actions">
					<button id="teknotok-ait-btn-switch" class="button button-primary"><?php esc_html_e( 'Yes, Switch', 'teknotok-ai-translator' ); ?></button>
					<button id="teknotok-ait-btn-dismiss" class="button button-secondary"><?php esc_html_e( 'No', 'teknotok-ai-translator' ); ?></button>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Build browser-language prompt labels for every configured target language.
	 *
	 * @param array $targets_mapped Target language code to display name map.
	 * @return array Prompt copy keyed by target language.
	 */
	private function get_redirect_prompts( $targets_mapped ) {
		$default_prompt = array(
			'text'    => __( 'Our website already supports %lang_name%. Do you want to use it in your language?', 'teknotok-ai-translator' ),
			'switch'  => __( 'Yes, Switch', 'teknotok-ai-translator' ),
			'dismiss' => __( 'No', 'teknotok-ai-translator' ),
		);

		$localized_prompts = array(
			'en' => array(
				'text'   => 'Our website already supports English. Do you want to use it in your language?',
				'switch' => 'Yes, Switch',
				'dismiss'=> 'No',
			),
			'es' => array(
				'text'   => 'Nuestro sitio web ya es compatible con español. ¿Desea utilizarlo en su idioma?',
				'switch' => 'Sí, cambiar',
				'dismiss'=> 'No',
			),
			'tr' => array(
				'text'   => 'Web sitemiz zaten Türkçe destekliyor. Kendi dilinizde kullanmak ister misiniz?',
				'switch' => 'Evet, değiştir',
				'dismiss'=> 'Hayır',
			),
			'zh' => array(
				'text'   => '我们的网站已支持中文。您想用您的语言浏览吗？',
				'switch' => '是的，切换',
				'dismiss'=> '不用了',
			),
			'hi' => array(
				'text'   => 'हमारी वेबसाइट पहले से ही हिन्दी का समर्थन करती है। क्या आप इसे अपनी भाषा में उपयोग करना चाहते हैं？',
				'switch' => 'हाँ, बदलें',
				'dismiss'=> 'नहीं',
			),
			'ar' => array(
				'text'   => 'موقعنا يدعم اللغة العربية بالفعل. هل ترغب في تصفحه باللغة العربية؟',
				'switch' => 'نعم، قم بالتحويل',
				'dismiss'=> 'لا',
			),
			'pt' => array(
				'text'   => 'Nosso site já é compatível com português. Deseja utilizá-lo em seu idioma?',
				'switch' => 'Sim, alterar',
				'dismiss'=> 'Não',
			),
			'bn' => array(
				'text'   => 'আমাদের ওয়েবসাইট ইতিমধ্যে বাংলা সমর্থন করে। আপনি কি এটি আপনার নিজের ভাষায় ব্যবহার করতে চান？',
				'switch' => 'হ্যাঁ, পরিবর্তন করুন',
				'dismiss'=> 'না',
			),
			'ru' => array(
				'text'   => 'Наш сайт уже поддерживает русский язык. Хотите ли вы использовать его на своем языке?',
				'switch' => 'Да, переключить',
				'dismiss'=> 'Нет',
			),
			'ja' => array(
				'text'   => '当サイトはすでに日本語に対応しています。日本語で表示しますか？',
				'switch' => 'はい、切り替えます',
				'dismiss'=> 'いいえ',
			),
			'fr' => array(
				'text'   => 'Notre site web prend déjà en charge le français. Souhaitez-vous l\'utiliser dans votre langue ?',
				'switch' => 'Oui, changer',
				'dismiss'=> 'Non',
			),
		);

		$prompts = array();
		foreach ( $targets_mapped as $code => $name ) {
			$prompts[ $code ] = $localized_prompts[ $code ] ?? $default_prompt;
		}

		return $prompts;
	}
}
