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

/**
 * REEID Page SEO — <html lang> (NON-WOO ONLY)
 *
 * Rules:
 * - Pages & posts only
 * - Fully option-gated
 * - NEVER touches Woo
 * - NEVER hardcodes language
 * - NEVER duplicates lang attribute
 * - Source of truth:
 *   1) _reeid_translation_lang (post meta)
 *   2) reeid_translation_source_lang (plugin setting)
 */

// IMPORTANT:
// This file MUST be the ONLY language_attributes filter for NON-Woo pages.
// Woo html-lang is handled separately and MUST remain disabled.

add_filter('language_attributes', function ($output) {

    /* -------------------------------------------------
     * Global hard gates (timing-safe)
     * ------------------------------------------------- */
    if (
        is_admin()
        || wp_doing_ajax()
        || wp_is_json_request()
    ) {
        return $output;
    }
/* -------------------------------------------------
 * HARD Woo fence (URL-based, no query reliance)
 * ------------------------------------------------- */
$req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );
$uri     = is_string( $req_raw ) ? wp_unslash( $req_raw ) : '';
$path    = (string) wp_parse_url( $uri, PHP_URL_PATH );

// Never touch Woo URLs (product, product-category, etc.)
if ( preg_match( '~/(?:[a-z]{2}/)?product(?:/|$)~i', $path ) ) {
	return $output;
}

    /* -------------------------------------------------
     * Feature gate (shared with hreflang)
     * ------------------------------------------------- */
    if (! (bool) get_option('reeid_seo_override_hreflang')) {
        return $output;
    }

    /* -------------------------------------------------
     * Resolve current post safely
     * ------------------------------------------------- */
    $post_id = (int) get_queried_object_id();
    if ($post_id <= 0) {
        return $output;
    }

    /* -------------------------------------------------
     * Resolve language — SINGLE SOURCE OF TRUTH
     * ------------------------------------------------- */

    // 1) Explicit translation language on the post
    $lang = (string) get_post_meta($post_id, '_reeid_translation_lang', true);

    // 2) Fallback to plugin-configured default source language
    if ($lang === '') {
        $lang = (string) get_option('reeid_translation_source_lang');
    }

    // 3) Final safety guard (never inject invalid markup)
    if ($lang === '') {
        return $output;
    }

    // Normalize (BCP47-safe)
    $lang = strtolower(preg_replace('~[^a-z0-9\-]~i', '', $lang));
    if ($lang === '') {
        return $output;
    }

    /* -------------------------------------------------
     * CRITICAL: ensure EXACTLY ONE lang attribute
     * ------------------------------------------------- */

    // Remove ALL existing lang="..." first (RankMath / themes safe)
    $output = preg_replace('~\s*lang="[^"]*"~i', '', $output);

    // Inject exactly one lang
    return trim($output) . ' lang="' . esc_attr($lang) . '"';

}, 999);
