<?php

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


/**
 * REEID — Own Sitemaps (isolated, optional exposure)
 *
 * Endpoints (always available once file is loaded + rewrites flushed):
 * - /reeid-sitemap.xml              (index)
 * - /reeid-sitemap-pages.xml        (pages)
 * - /reeid-sitemap-posts.xml        (posts)
 *
 * Exposure rules:
 * - We do NOT touch RankMath/Yoast/etc sitemap internals here.
 * - robots.txt exposure is intentionally not modified by this file.
 *
 * URL building:
 * - If a post has _reeid_translation_lang = $lang and $lang != source_lang,
 *   we output a language-prefixed URL: /{lang}/{slug}/
 * - If it is source_lang (or missing meta), we output normal permalink (no prefix).
 */



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

		// Rank Math
		if ( defined( 'RANK_MATH_VERSION' ) ) {
			return true;
		}

		// Yoast SEO
		if ( defined( 'WPSEO_VERSION' ) ) {
			return true;
		}

		// SEOPress
		if ( defined( 'SEOPRESS_VERSION' ) ) {
			return true;
		}

		// AIOSEO
		if ( defined( 'AIOSEO_VERSION' ) ) {
			return true;
		}

		return false;
	}
}

add_filter( 'wp_sitemaps_enabled', function( $enabled ) {

	// If external SEO plugin active → let WP core sitemap live
	if ( reeid__external_sitemap_provider_active() ) {
		return $enabled;
	}

	// Otherwise REEID is authoritative
	return false;

}, 10 );


if ( ! function_exists( 'reeid__sitemap_source_lang' ) ) {
	function reeid__sitemap_source_lang(): string {
		$cur = get_option( 'reeid_translation_source_lang', 'en' );
		$cur = is_string( $cur ) ? strtolower( sanitize_key( $cur ) ) : 'en';
		return $cur !== '' ? $cur : 'en';
	}
}

if ( ! function_exists( 'reeid__sitemap_encode_segments' ) ) {
	/**
	 * Encode each path segment RFC3986-safe, preserving UTF-8 characters.
	 */
	function reeid__sitemap_encode_segments( string $path ): string {
		$path = '/' . ltrim( $path, '/' );
		$segs = explode( '/', trim( $path, '/' ) );
		$out  = [];
		foreach ( $segs as $seg ) {
			$seg = (string) $seg;
			if ( $seg === '' ) {
				continue;
			}
			// Decode any existing encoding then re-encode safely.
			$seg = rawurldecode( $seg );
			$out[] = rawurlencode( $seg );
		}
		return '/' . implode( '/', $out ) . '/';
	}
}

if ( ! function_exists( 'reeid__sitemap_url_for_post' ) ) {
	function reeid__sitemap_url_for_post( int $post_id ): string {
		$src_lang = reeid__sitemap_source_lang();
		$lang     = (string) get_post_meta( $post_id, '_reeid_translation_lang', true );
		$lang     = strtolower( sanitize_key( $lang ) );

		// If no lang meta -> treat as source (unprefixed).
		if ( $lang === '' || $lang === $src_lang ) {
			return (string) get_permalink( $post_id );
		}

		$post = get_post( $post_id );
		if ( ! $post ) {
			return (string) get_permalink( $post_id );
		}

		// Pages can be hierarchical; build full path.
		$path = get_page_uri( $post_id ); // returns decoded-ish path
		if ( ! is_string( $path ) || $path === '' ) {
			$path = $post->post_name;
		}

		$encoded = reeid__sitemap_encode_segments( $path );
		$lang    = rawurlencode( $lang );

		return home_url( '/' . $lang . $encoded );
	}
}

if ( ! function_exists( 'reeid__sitemap_is_request' ) ) {
	function reeid__sitemap_is_request(): bool {
		if ( is_admin() || wp_doing_ajax() || wp_is_json_request() ) {
			return false;
		}

		$req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );
		$req     = is_string( $req_raw ) ? wp_unslash( $req_raw ) : '';

		$path = (string) wp_parse_url( $req, PHP_URL_PATH );
		$path = '/' . ltrim( (string) $path, '/' );

		return (bool) preg_match( '~^/(reeid-sitemap(?:-(?:pages|posts))?\.xml)$~i', $path );
	}
}

if ( ! function_exists( 'reeid__sitemap_send_xml' ) ) {
	function reeid__sitemap_send_xml( string $xml ): void {
		nocache_headers();
		header( 'Content-Type: text/xml; charset=UTF-8', true );
		echo $xml; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}
}

if ( ! function_exists( 'reeid__sitemap_index_xml' ) ) {
	function reeid__sitemap_index_xml(): string {
		$now = gmdate( 'c' );
		$base = home_url( '/' );

		$items = [
			[ 'loc' => $base . 'reeid-sitemap-pages.xml', 'lastmod' => $now ],
			[ 'loc' => $base . 'reeid-sitemap-posts.xml', 'lastmod' => $now ],
		];

		$xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
		$xml .= '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
		foreach ( $items as $it ) {
			$xml .= "  <sitemap>\n";
			$xml .= '    <loc>' . esc_url( $it['loc'] ) . "</loc>\n";
			$xml .= '    <lastmod>' . esc_html( $it['lastmod'] ) . "</lastmod>\n";
			$xml .= "  </sitemap>\n";
		}
		$xml .= "</sitemapindex>\n";
		return $xml;
	}
}

if ( ! function_exists( 'reeid__sitemap_urlset_xml' ) ) {
	function reeid__sitemap_urlset_xml( array $urls ): string {

		$xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
		$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ';
		$xml .= 'xmlns:xhtml="http://www.w3.org/1999/xhtml" ';
		$xml .= 'xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">' . "\n";


		foreach ( $urls as $loc ) {

			$loc = (string) $loc;
			if ( $loc === '' ) {
				continue;
			}

			$post_id = url_to_postid( $loc );
			if ( $post_id <= 0 ) {
				continue;
			}

			// Exclude utility slugs
			$slug = basename( untrailingslashit( $loc ) );
			$exclude = [
				'cart',
				'checkout',
				'my-account',
				'customer-cabinet',
				'customer-cabinet-2',
			];
			if ( in_array( $slug, $exclude, true ) ) {
				continue;
			}

			// Respect noindex (generic)
			if ( get_post_meta( $post_id, '_yoast_wpseo_meta-robots-noindex', true ) === '1' ) {
				continue;
			}
			if ( get_post_meta( $post_id, 'rank_math_robots', true ) ) {
				$robots = (array) get_post_meta( $post_id, 'rank_math_robots', true );
				if ( in_array( 'noindex', $robots, true ) ) {
					continue;
				}
			}

			$xml .= "  <url>\n";
			$xml .= '    <loc>' . esc_url( $loc ) . "</loc>\n";
			$lastmod = get_post_modified_time( 'c', true, $post_id );
if ( $lastmod ) {
	$xml .= '    <lastmod>' . esc_html( $lastmod ) . "</lastmod>\n";
}


			// Inject hreflang cluster
			$source_id = (int) get_post_meta( $post_id, '_reeid_translation_source', true );
			if ( $source_id <= 0 ) {
				$source_id = $post_id;
			}

			$map = get_post_meta( $source_id, '_reeid_translation_map', true );
			if ( is_array( $map ) ) {

				foreach ( $map as $lang => $pid ) {

					$pid = (int) $pid;
					if ( $pid <= 0 || get_post_status( $pid ) !== 'publish' ) {
						continue;
					}

					$href = get_permalink( $pid );
					if ( ! $href ) {
						continue;
					}

					$lang = strtolower( trim( (string) $lang ) );

					$xml .= '    <xhtml:link rel="alternate" hreflang="' .
						esc_attr( $lang ) .
						'" href="' .
						esc_url( $href ) .
						"\" />\n";
				}

				// x-default = source language
				$src_lang = reeid__sitemap_source_lang();
				$src_url  = get_permalink( $source_id );

				if ( $src_url ) {
					$xml .= '    <xhtml:link rel="alternate" hreflang="x-default" href="' .
						esc_url( $src_url ) .
						"\" />\n";
				}
			}

			$thumb_id = get_post_thumbnail_id( $post_id );
if ( $thumb_id ) {
	$img_url = wp_get_attachment_url( $thumb_id );
	if ( $img_url ) {
		$xml .= "    <image:image>\n";
		$xml .= '      <image:loc>' . esc_url( $img_url ) . "</image:loc>\n";
		$xml .= "    </image:image>\n";
	}
}


			$xml .= "  </url>\n";
		}

		$xml .= "</urlset>\n";
		return $xml;
	}
}


/**
 * Add rewrite rules for REEID sitemaps.
 * (rules are lightweight and won’t affect other routing)
 */
add_action( 'init', function() {
	add_rewrite_rule( '^reeid-sitemap\.xml$', 'index.php?reeid_sitemap=index', 'top' );
	add_rewrite_rule( '^reeid-sitemap-pages\.xml$', 'index.php?reeid_sitemap=pages', 'top' );
	add_rewrite_rule( '^reeid-sitemap-posts\.xml$', 'index.php?reeid_sitemap=posts', 'top' );
}, 1 );

add_filter( 'query_vars', function( $vars ) {
	$vars   = is_array( $vars ) ? $vars : [];
	$vars[] = 'reeid_sitemap';
	return array_values( array_unique( $vars ) );
}, 1 );
/**
 * Serve REEID sitemaps.
 */
add_action( 'template_redirect', function() {

    if ( ! reeid__sitemap_is_request() ) {
        return;
    }

	// If external SEO plugin is active, do not serve REEID sitemap.
if ( reeid__external_sitemap_provider_active() ) {
    status_header( 404 );
    exit;
}


    $type = (string) get_query_var( 'reeid_sitemap', '' );

   if ( $type === '' ) {
	// Fallback if rewrites got bypassed somehow:
	$req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );
	$req     = is_string( $req_raw ) ? wp_unslash( $req_raw ) : '';

	$path = (string) wp_parse_url( $req, PHP_URL_PATH );
	$path = '/' . ltrim( (string) $path, '/' );

	if ( preg_match( '~^/reeid-sitemap-pages\.xml$~i', $path ) ) {
		$type = 'pages';
	} elseif ( preg_match( '~^/reeid-sitemap-posts\.xml$~i', $path ) ) {
		$type = 'posts';
	} else {
		$type = 'index';
	}
}

    // Only gate the PAGES sitemap (Tools tab toggle).
    if ( $type === 'pages' ) {
    status_header( 404 );
    exit;
}

    if ( $type === 'index' ) {
        reeid__sitemap_send_xml( reeid__sitemap_index_xml() );
    }

    $post_type = ( $type === 'posts' ) ? 'post' : 'page';

    $q = new WP_Query( [
	'post_type'              => $post_type,
	'post_status'            => 'publish',
	'posts_per_page'         => 5000,
	'no_found_rows'          => true,
	'update_post_meta_cache' => false,
	'update_post_term_cache' => false,
	'fields'                 => 'ids',

	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required to limit sitemap to REEID translated items only. Result set is bounded and cached.
	'meta_query' => [
		[
			'key'     => '_reeid_translation_lang',
			'compare' => 'EXISTS',
		],
	],
] );


    $urls = [];
    if ( ! empty( $q->posts ) ) {
        foreach ( $q->posts as $pid ) {
            $pid = (int) $pid;
            if ( $pid <= 0 ) {
                continue;
            }
            $urls[] = reeid__sitemap_url_for_post( $pid );
        }
    }

    reeid__sitemap_send_xml( reeid__sitemap_urlset_xml( $urls ) );

}, 0 );


/**
 * Authoritative mode:
 * Redirect default WP sitemap endpoint to REEID sitemap.
 */
add_action( 'template_redirect', function() {

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

	$req_raw = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_UNSAFE_RAW );
	$req     = is_string( $req_raw ) ? wp_unslash( $req_raw ) : '';
	$path    = (string) wp_parse_url( $req, PHP_URL_PATH );
	$path    = '/' . ltrim( (string) $path, '/' );

	if ( preg_match( '~^/wp-sitemap\.xml$~i', $path )
		&& ! reeid__external_sitemap_provider_active() ) {

		wp_safe_redirect( home_url( '/reeid-sitemap.xml' ), 301 );
		exit;
	}

}, 0 );



add_filter( 'robots_txt', function( $output, $public ) {
	return $output;
}, 20, 2 );