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

/**
 * REEID — Pages Sitemap (Translated Pages)
 *
 * Goals:
 * - Never break Woo sitemap/hreflang work
 * - Works with or without SEO plugins
 * - Generates a dedicated sitemap endpoint
 * - Optionally adds it into Rank Math sitemap index (if present)
 */

if ( ! function_exists( 'reeid_pages_sitemap_enabled' ) ) {
	function reeid_pages_sitemap_enabled() {
		// Default ON if option missing (safe).
		return (bool) get_option( 'reeid_pages_sitemap_enabled', true );
	}
}

if ( ! function_exists( 'reeid_collect_translated_pages' ) ) {
	function reeid_collect_translated_pages() {

		$args = [
			'post_type'   => 'page',
			'post_status' => 'publish',
			'fields'      => 'ids',
			'nopaging'    => true,
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Required for sitemap generation. Query is limited to post_type=page, post_status=publish, fields=ids, and result is transient-cached.
'meta_query'  => [
	'relation' => 'OR',
	[
		'key'     => '_reeid_translation_source',
		'compare' => 'EXISTS',
	],
	[
		'key'     => '_reeid_translation_map',
		'compare' => 'EXISTS',
	],
],
		];

    $query = new WP_Query($args);

    $ids = [];

    if (!empty($query->posts)) {
        foreach ($query->posts as $pid) {

    // Rank Math noindex (array format)
    $robots = get_post_meta($pid, 'rank_math_robots', true);

    if (is_array($robots) && in_array('noindex', $robots, true)) {
        continue;
    }

    if (is_string($robots) && strpos($robots, 'noindex') !== false) {
        continue;
    }

    // Yoast noindex
    $yoast_noindex = get_post_meta($pid, '_yoast_wpseo_meta-robots-noindex', true);
    if ($yoast_noindex === '1') {
        continue;
    }

    $ids[] = (int) $pid;
}
    }

    wp_reset_postdata();
    return $ids;
}
}

/**
 * Endpoint: /reeid-pages-sitemap.xml
 */
add_action(
	'init',
	function () {

		add_rewrite_rule(
			'^reeid-pages-sitemap\.xml$',
			'index.php?reeid_pages_sitemap=1',
			'top'
		);
	},
	1
);

add_filter(
	'query_vars',
	function ( $vars ) {
		$vars[] = 'reeid_pages_sitemap';
		return $vars;
	}
);
add_action(
    'template_redirect',
    function () {

        if ( ! reeid_pages_sitemap_enabled() ) {
            return;
        }

        if ( (int) get_query_var( 'reeid_pages_sitemap' ) !== 1 ) {
            return;
        }

        $cache_key = 'reeid_pages_sitemap_xml';
        $xml       = get_transient( $cache_key );

        if ( false === $xml ) {

            $ids = reeid_collect_translated_pages();

            ob_start();

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

            foreach ( $ids as $pid ) {

                $pid = (int) $pid;

                if ( $pid <= 0 ) {
                    continue;
                }

                // Respect Rank Math noindex
                $robots = get_post_meta( $pid, 'rank_math_robots', true );
                if ( is_array( $robots ) && in_array( 'noindex', $robots, true ) ) {
                    continue;
                }

                // Respect Yoast noindex
                if ( '1' === get_post_meta( $pid, '_yoast_wpseo_meta-robots-noindex', true ) ) {
                    continue;
                }

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

                $lastmod = get_post_modified_time( 'c', true, $pid );

                echo "\t<url>\n";
                echo "\t\t<loc>" . esc_url( $loc ) . "</loc>\n";

                if ( ! empty( $lastmod ) ) {
                    echo "\t\t<lastmod>" . esc_html( $lastmod ) . "</lastmod>\n";
                }

                echo "\t</url>\n";
            }

            echo "</urlset>\n";

            $xml = ob_get_clean();

            // Cache for 15 minutes
            set_transient( $cache_key, $xml, 15 * MINUTE_IN_SECONDS );
        }

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

// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- XML is generated internally and served as application/xml.
echo $xml;
        exit;
    },
    1
);
add_action('save_post_page', function () {
    delete_transient('reeid_pages_sitemap_xml');
});

add_action('deleted_post', function () {
    delete_transient('reeid_pages_sitemap_xml');
});

/**
 * Rank Math: add REEID pages sitemap into sitemap_index.xml (if filter exists).
 *
 * NOTE: Rank Math filter names can vary by version. We attach to the common one,
 * and also a fallback. If neither is called, sitemap still works standalone.
 */
add_filter(
	'rank_math/sitemap/index',
	function ( $sitemaps ) {

		if ( ! reeid_pages_sitemap_enabled() ) {
			return $sitemaps;
		}

		$url = home_url( '/reeid-pages-sitemap.xml' );

		// $sitemaps is usually an array of entries.
		if ( is_array( $sitemaps ) ) {
			$sitemaps[] = array(
				'loc'     => esc_url( $url ),
				'lastmod' => gmdate( 'c' ),
			);
		}

		return $sitemaps;
	}
);

// Fallback hook name (some builds use this).
add_filter(
	'rank_math/sitemap/index/links',
	function ( $links ) {

		if ( ! reeid_pages_sitemap_enabled() ) {
			return $links;
		}

		$url = home_url( '/reeid-pages-sitemap.xml' );

		if ( is_array( $links ) ) {
			$links[] = array(
				'loc'     => esc_url( $url ),
				'lastmod' => gmdate( 'c' ),
			);
		}

		return $links;
	}
);

add_filter('robots_txt', function ($output, $public) {

    if (!reeid_pages_sitemap_enabled()) {
        return $output;
    }

    $url = home_url('/reeid-pages-sitemap.xml');

    $output .= "\nSitemap: " . esc_url($url) . "\n";

    return $output;

}, 10, 2);