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

/**
 * REEID — WooCommerce INLINE hreflang
 *
 * Model:
 * - REAL source product        → hreflang hub (indexable)
 * - INLINE translations        → hreflang hub (indexable)
 * - SOURCE language alias      → NO hreflang (noindex alias)
 *
 * Ownership:
 * - Enabled  → REEID controls Woo hreflang
 * - Disabled → Other SEO plugins control Woo hreflang
 *
 * Notes:
 * - Source language is user-defined (reeid_translation_source_lang)
 * - No hardcoded "en"
 * - WP.org safe
 */

/**
 * We hook VERY late so if any SEO plugin prints/filters earlier,
 * we remain the last writer in <head>.
 */
add_action( 'wp_head', 'reeid_wc_inline_hreflang_emit', 9999 );

function reeid_wc_inline_hreflang_emit() {

	if ( ! get_option( 'reeid_seo_override_hreflang', false ) ) {
		return;
	}

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

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

	global $post, $wp;

	if ( ! $post || $post->post_type !== 'product' ) {
		return;
	}

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

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

	// Detect current lang from URL
	$current_lang = '';
	if ( preg_match( '#^/([a-z]{2}(?:-[a-z0-9]{2})?)/#i', $path, $m ) ) {
		$current_lang = strtolower( (string) $m[1] );
	}

	// Root URL is SOURCE
	$source_url = get_permalink( $post->ID );
	if ( ! $source_url ) {
		return;
	}

	$pairs = array();

	// Source language is root (no prefix)
	$pairs['x-default'] = $source_url;

	// Infer source lang from root canonical language attribute
	$root_lang = get_locale();
	if ( is_string( $root_lang ) ) {
		$root_lang = strtolower( substr( $root_lang, 0, 2 ) );
	} else {
		$root_lang = 'en';
	}

	$pairs[ $root_lang ] = $source_url;

	// Add inline translations
	$meta = get_post_meta( $post->ID );

	foreach ( $meta as $key => $vals ) {

		if ( strpos( (string) $key, '_reeid_wc_tr_' ) !== 0 ) {
			continue;
		}

		$lang = strtolower( (string) substr( (string) $key, 13 ) );

		$packet = maybe_unserialize( $vals[0] ?? null );

		if ( ! is_array( $packet ) || empty( $packet['slug'] ) ) {
			continue;
		}

		$pairs[ $lang ] = home_url(
			'/' . $lang . '/' . $product_base . '/' . rawurlencode( (string) $packet['slug'] ) . '/'
		);
	}

	// Ensure current URL included
	if ( $current_lang && ! isset( $pairs[ $current_lang ] ) ) {
		$pairs[ $current_lang ] = home_url(
			'/' . $current_lang . '/' . $product_base . '/' . rawurlencode( (string) $post->post_name ) . '/'
		);
	}

	foreach ( $pairs as $code => $url ) {
		echo '<link rel="alternate" hreflang="' . esc_attr( (string) $code ) .
			'" href="' . esc_url( (string) $url ) . "\" />\n";
	}
}