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

/**
 * REEID — Force <html lang> for Woo INLINE product translations
 *
 * - Woo single products ONLY
 * - Only when REEID controls Woo SEO
 * - No output buffering
 */

add_filter(
	'language_attributes',
	function ( $output, $doctype ) {
		if ( is_admin() || wp_doing_ajax() || wp_is_json_request() ) {
			return $output;
		}

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

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

		$lang    = '';
		$req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );

		if ( is_string( $req_raw ) && '' !== $req_raw ) {
			$request_uri = wp_unslash( $req_raw );
			$path        = wp_parse_url( $request_uri, PHP_URL_PATH );

			if ( is_string( $path ) && preg_match( '#^/([a-z]{2})(?:/|$)#i', $path, $m ) ) {
				$lang = sanitize_key( strtolower( $m[1] ) );
			}
		}

		if ( '' === $lang ) {
			return $output;
		}

		if ( preg_match( '/\blang=("|\')[^"\']+\1/i', $output ) ) {
			return preg_replace(
				'/\blang=("|\')[^"\']+\1/i',
				'lang="' . esc_attr( $lang ) . '"',
				$output,
				1
			);
		}

		return 'lang="' . esc_attr( $lang ) . '" ' . $output;
	},
	20,
	2
);