<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * REEID — Woo Inline Product Sitemap (INSULATED)
 *
 * Purpose:
 * - Emit a standalone XML sitemap for Woo inline/virtual product translations.
 * - Designed for compatibility with major SEO plugins (Yoast can index external sitemaps).
 * - MUST NOT affect normal pages SEO under any condition.
 *
 * URL:
 *   https://example.com/reeid-wc-product-sitemap.xml
 *
 * Notes:
 * - No rewrites, no flush needed. Uses REQUEST_URI match only.
 * - Output includes EN (source) + each inline language URL for products with _reeid_wc_inline_langs.
 */



if ( ! function_exists( 'reeid_wc_inline_sitemap__is_request' ) ) {
	function reeid_wc_inline_sitemap__is_request(): bool {

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

		if ( ! is_string( $req_raw ) || $req_raw === '' ) {
			return false;
		}

		$request_uri = wp_unslash( $req_raw );
		$parsed_path = wp_parse_url( $request_uri, PHP_URL_PATH );

		if ( ! is_string( $parsed_path ) ) {
			return false;
		}

		$path = (string) $parsed_path;

		return (bool) preg_match( '~/(reeid-wc-product-sitemap\.xml)$~i', $path );
	}
}

if ( ! function_exists( 'reeid_wc_inline_sitemap__encode_loc' ) ) {
	function reeid_wc_inline_sitemap__encode_loc( string $url ): string {
		// Prefer your canonical encoder if available.
		if ( function_exists( 'reeid_seo__encode_url_path' ) ) {
			return (string) reeid_seo__encode_url_path( $url );
		}

		$parts = wp_parse_url( $url );
		if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) ) {
			return $url;
		}

		$path = (string) ( $parts['path'] ?? '/' );
		$path = implode( '/', array_map( 'rawurlencode', array_map( 'rawurldecode', explode( '/', $path ) ) ) );

		$out  = $parts['scheme'] . '://' . $parts['host'];
		$out .= isset( $parts['port'] ) ? ':' . (int) $parts['port'] : '';
		$out .= $path;

		if ( ! empty( $parts['query'] ) ) {
			$out .= '?' . $parts['query'];
		}

		return $out;
	}
}

if ( ! function_exists( 'reeid_wc_inline_sitemap__product_base' ) ) {
	function reeid_wc_inline_sitemap__product_base(): string {
		$wc   = get_option( 'woocommerce_permalinks', array() );
		$base = ( is_array( $wc ) && ! empty( $wc['product_base'] ) ) ? trim( (string) $wc['product_base'], '/' ) : 'product';
		return $base !== '' ? $base : 'product';
	}
}

if ( ! function_exists( 'reeid_wc_inline_sitemap__build_lang_url' ) ) {
	function reeid_wc_inline_sitemap__build_lang_url( int $product_id, string $lang ): string {
		$lang = strtolower( sanitize_key( $lang ) );
		if ( $lang === '' ) {
			return get_permalink( $product_id );
		}

		$packet = get_post_meta( $product_id, '_reeid_wc_tr_' . $lang, true );
		$slug   = '';

		if ( is_array( $packet ) && ! empty( $packet['slug'] ) ) {
			$slug = (string) $packet['slug'];
		}

		// Fallback: if packet missing slug, fall back to EN slug (keeps sitemap complete, avoids 404 spam).
		if ( $slug === '' ) {
			$slug = (string) get_post_field( 'post_name', $product_id );
		}

		$base = reeid_wc_inline_sitemap__product_base();

		// Build: /{lang}/{product_base}/{slug}/  (slug is encoded later by encoder)
		$path = '/' . trim( $lang, '/' ) . '/' . trim( $base, '/' ) . '/' . trim( $slug, '/' ) . '/';

		return home_url( $path );
	}
}

/**
 * Emit sitemap on request (NO side effects elsewhere).
 */
add_action(
	'template_redirect',
	function () {
		if ( is_admin() || wp_doing_ajax() || wp_is_json_request() ) {
			return;
		}
		if ( ! reeid_wc_inline_sitemap__is_request() ) {
			return;
		}

		$q = new WP_Query(
    array(
        'post_type'      => 'product',
        'post_status'    => 'publish',
        'posts_per_page' => 5000,
        'fields'         => 'ids',
        // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- required to find products with inline language metadata
        'meta_query'     => array(
            array(
                'key'     => '_reeid_wc_inline_langs',
                'compare' => 'EXISTS',
            ),
        ),
        'no_found_rows'  => true,
    )
);

		$urls = array();

		if ( ! empty( $q->posts ) && is_array( $q->posts ) ) {
			foreach ( $q->posts as $pid ) {
				$pid = (int) $pid;
				if ( $pid <= 0 ) {
					continue;
				}

				$inline = get_post_meta( $pid, '_reeid_wc_inline_langs', true );
				if ( ! is_array( $inline ) || empty( $inline ) ) {
					continue;
				}

				// Always include source EN product URL (no /en/ prefix).
				$urls[] = get_permalink( $pid );

				foreach ( $inline as $lang ) {
					$lang = strtolower( sanitize_key( (string) $lang ) );
					if ( $lang === '' ) {
						continue;
					}
					$urls[] = reeid_wc_inline_sitemap__build_lang_url( $pid, $lang );
				}
			}
		}

		$urls = array_values( array_unique( array_filter( $urls ) ) );

		status_header( 200 );
		header( 'Content-Type: application/xml; charset=UTF-8' );

		echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";

		$now = gmdate( 'c' );

		foreach ( $urls as $u ) {
			$loc = reeid_wc_inline_sitemap__encode_loc( (string) $u );
			echo "  <url>\n";
			echo '    <loc>' . esc_html( $loc ) . "</loc>\n";
			echo '    <lastmod>' . esc_html( $now ) . "</lastmod>\n";
			echo "  </url>\n";
		}

		echo "</urlset>\n";
		exit;
	},
	0
);

/**
 * Yoast compatibility:
 * Add this sitemap to Yoast sitemap index *if Yoast is active*.
 */
add_filter(
	'wpseo_sitemap_index',
	function ( $xml ) {
		if ( ! defined( 'WPSEO_VERSION' ) ) {
			return $xml;
		}
		$loc = home_url( '/reeid-wc-product-sitemap.xml' );
		$loc = reeid_wc_inline_sitemap__encode_loc( $loc );
		$xml .= "\n<sitemap>\n";
		$xml .= '  <loc>' . esc_html( $loc ) . "</loc>\n";
		$xml .= '  <lastmod>' . esc_html( gmdate( 'c' ) ) . "</lastmod>\n";
		$xml .= "</sitemap>\n";
		return $xml;
	},
	50
);
