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

/**
 * REEID — Woo INLINE robots authority
 *
 * Rules:
 * - REAL source product        → index, follow
 * - INLINE translations        → index, follow
 * - LANGUAGE ALIAS (/source/)  → noindex, follow
 *
 * Scope:
 * - Woo single products ONLY
 * - Independent from SEO plugins
 * - Respects REEID default source language
 * - WP.org safe
 */

/**
 * ---------------------------------------------------------
 * Neutralize Rank Math robots on Woo products
 * ---------------------------------------------------------
 */
add_action( 'rank_math/head', function () {

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

	// Rank Math outputs robots via this method
	remove_action(
		'rank_math/head',
		[ \RankMath\Frontend\Head::class, 'robots' ],
		20
	);

}, 0 );

/**
 * ---------------------------------------------------------
 * Emit authoritative robots meta for Woo INLINE products
 * ---------------------------------------------------------
 */
add_action( 'wp_head', 'reeid_wc_inline_robots_emit', 20 );

function reeid_wc_inline_robots_emit() {

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

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

	global $wp;

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

	/*
	 * =========================
	 * Detect language prefix
	 * =========================
	 */
	$lang = '';
	if ( preg_match( '#^/([a-z]{2})/product/#i', $path, $m ) ) {
		$lang = strtolower( $m[1] );
	}

	/*
	 * =========================
	 * Detect REEID source language
	 * =========================
	 */
	$source_lang = get_option( 'reeid_translation_source_lang', '' );
	$source_lang = is_string( $source_lang ) ? strtolower( $source_lang ) : '';

	// Safety fallback: never index language aliases accidentally
	if ( $source_lang === '' ) {
		$source_lang = 'en';
	}

	/*
	 * =========================
	 * Decide robots policy
	 * =========================
	 */

	// Case 1: REAL source product (/product/slug/)
	if ( $lang === '' ) {
		echo '<meta name="robots" content="index, follow" />' . "\n";
		return;
	}

	// Case 2: Language alias of SOURCE (/en/product/)
	if ( $lang === $source_lang ) {
		echo '<meta name="robots" content="noindex, follow" />' . "\n";
		return;
	}

	// Case 3: Real inline translation (/ar/product/, /de/product/, etc.)
	echo '<meta name="robots" content="index, follow" />' . "\n";
}
