<?php
/**
 * MindWebConcierge Sitemap Handler
 *
 * @package MindWebConcierge
 */

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

add_action( 'init', 'mindweco_maybe_render_sitemap' );

function mindweco_maybe_render_sitemap() {
	$mindweco_sitemap = isset( $_GET['mindweco_sitemap'] )
		? sanitize_text_field( wp_unslash( $_GET['mindweco_sitemap'] ) )
		: '';

	if ( '1' !== $mindweco_sitemap ) {
		return;
	}

	header( 'Content-Type: application/xml; charset=utf-8' );
	echo mindweco_get_sitemap_xml(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	exit;
}

/**
 * Builds and returns the full XML sitemap string.
 *
 * @return string
 */
function mindweco_get_sitemap_xml() {
	$sitemap  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
	$sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

	$sitemap .= '    <url>' . "\n";
	$sitemap .= '        <loc>' . esc_url( home_url( '/' ) ) . '</loc>' . "\n";
	$sitemap .= '        <lastmod>' . esc_attr( gmdate( 'c' ) ) . '</lastmod>' . "\n";
	$sitemap .= '        <changefreq>daily</changefreq>' . "\n";
	$sitemap .= '        <priority>1.0</priority>' . "\n";
	$sitemap .= '    </url>' . "\n";

	$menu_items = mindweco_get_all_menu_items();

	if ( ! empty( $menu_items ) ) {
		$sitemap .= mindweco_render_pages_xml( $menu_items );
	}

	$sitemap .= '</urlset>';

	return $sitemap;
}

/**
 * Returns a deduplicated list of all nav menu items belonging to this site.
 *
 * @return array
 */
function mindweco_get_all_menu_items() {
	$all_items = array();
	$locations = get_nav_menu_locations();

	if ( empty( $locations ) ) {
		$menus = wp_get_nav_menus();
		foreach ( $menus as $menu ) {
			$menu_items = wp_get_nav_menu_items( $menu->term_id );
			if ( ! $menu_items ) {
				continue;
			}
			foreach ( $menu_items as $item ) {
				mindweco_add_sitemap_item( $all_items, $item );
			}
		}
		return array_values( $all_items );
	}

	foreach ( $locations as $menu_id ) {
		if ( ! $menu_id ) {
			continue;
		}
		$menu_items = wp_get_nav_menu_items( $menu_id );
		if ( ! $menu_items ) {
			continue;
		}
		foreach ( $menu_items as $item ) {
			mindweco_add_sitemap_item( $all_items, $item );
		}
	}

	return array_values( $all_items );
}

/**
 * Adds a single nav menu item to the sitemap array if it belongs to this site
 * and has not already been added (deduplication by URL).
 *
 * @param array   $all_items Items array passed by reference.
 * @param WP_Post $item      Nav menu item object.
 */
function mindweco_add_sitemap_item( &$all_items, $item ) {
	$url  = $item->url;
	$home = trailingslashit( home_url() );

	if ( strpos( trailingslashit( $url ), $home ) !== 0 ) {
		return;
	}

	if ( isset( $all_items[ $url ] ) ) {
		return;
	}

	$lastmod = $item->object_id
		? get_post_modified_time( 'c', true, (int) $item->object_id )
		: gmdate( 'c' );

	$all_items[ $url ] = array(
		'url'      => $url,
		'lastmod'  => $lastmod ? $lastmod : gmdate( 'c' ),
		'title'    => $item->title,
		'priority' => 0.8,
	);
}

/**
 * Renders an array of sitemap page entries as XML <url> blocks.
 *
 * @param array $pages Array of page data arrays.
 * @return string
 */
function mindweco_render_pages_xml( $pages ) {
	$xml = '';

	foreach ( $pages as $page ) {
		$xml .= '    <url>' . "\n";
		$xml .= '        <loc>' . esc_url( $page['url'] ) . '</loc>' . "\n";
		$xml .= '        <lastmod>' . esc_attr( $page['lastmod'] ) . '</lastmod>' . "\n";
		$xml .= '        <changefreq>monthly</changefreq>' . "\n";
		$xml .= '        <priority>' . esc_attr( (string) $page['priority'] ) . '</priority>' . "\n";
		$xml .= '    </url>' . "\n";
	}

	return $xml;
}