<?php
defined( 'ABSPATH' ) || exit;

/**
 * REEID — Woo canonical rules (final stable)
 */

add_action( 'wp_head', function () {

	if ( is_admin() || wp_doing_ajax() ) {
		return;
	}

	if ( ! function_exists( 'is_product' ) || ! is_product() ) {
		return;
	}

	global $wp;

	$source_lang = strtolower(
		(string) get_option( 'reeid_translation_source_lang', '' )
	);

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

	$wc = get_option( 'woocommerce_permalinks', array() );
	$base = ( is_array( $wc ) && ! empty( $wc['product_base'] ) )
		? trim( (string) $wc['product_base'], '/' )
		: 'product';

	$path = '/' . ltrim( (string) $wp->request, '/' );

	/*
	 * 1️⃣ Prefixed source language → canonical to root
	 */
	if ( strpos( $path, '/' . $source_lang . '/' . $base . '/' ) === 0 ) {

		$root = preg_replace(
			'#^/' . preg_quote( $source_lang, '#' ) . '/#',
			'/',
			$path
		);

		echo '<link rel="canonical" href="' . esc_url( home_url( trailingslashit( $root ) ) ) . "\" />\n";
		return;
	}

	/*
	 * 2️⃣ Other prefixed language → self canonical
	 */
	if ( preg_match( '#^/([a-z]{2}(?:-[a-z0-9]{2})?)/' . preg_quote( $base, '#' ) . '/#i', $path, $m ) ) {

		if ( strtolower( $m[1] ) !== $source_lang ) {
			echo '<link rel="canonical" href="' . esc_url( home_url( trailingslashit( $path ) ) ) . "\" />\n";
			return;
		}
	}

	/*
	 * 3️⃣ Root source → self canonical
	 */
	echo '<link rel="canonical" href="' . esc_url( get_permalink() ) . "\" />\n";

}, 50 );