<?php
/**
 * User Sitemap
 *
 * Generates author/user sub-sitemaps.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Sitemap;

use SEOvaultSEO\Core\Options;

/**
 * Builds author sub-sitemaps
 */
class User {

	/**
	 * Output a user sub-sitemap.
	 *
	 * @param string $slug Sitemap slug.
	 * @param int    $page Page number.
	 */
	public static function output( $slug, $page ) {
		if ( ! Options::is_sitemap_users_enabled() ) {
			Router::send_404();
			return;
		}

		$slug = Sanitizer::slug( $slug );
		if ( 'users' !== $slug && 0 !== strpos( $slug, 'users-' ) ) {
			Router::send_404();
			return;
		}

		$page = max( 1, (int) $page );

		$cache_key = 'sitemap/users-page-' . $page . '.xml';
		$cached    = Cache::get( $cache_key );
		if ( false !== $cached ) {
			Renderer::set_stylesheet_url( home_url( '/seovault-sitemap.xsl' ) );
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-built XML sitemap output.
			echo $cached;
			return;
		}

		$urls = self::build_urls( $page );
		$xml  = self::render( $urls );
		Cache::store( $cache_key, $xml );
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-built XML sitemap output.
		echo $xml;
	}

	/**
	 * Build URL array for the requested page.
	 *
	 * @param int $page Page.
	 * @return array
	 */
	public static function build_urls( $page ) {
		$per_page = Options::get_sitemap_entries_per_page();
		$ids      = Query::get_user_ids( $page, $per_page );
		$urls     = array();

		$allow_empty = apply_filters( 'seovaultseo_sitemap_users_allow_empty', false );

		foreach ( $ids as $user_id ) {
			if ( ! $allow_empty ) {
				$count = count_user_posts( $user_id, 'post', true );
				if ( empty( $count ) ) {
					continue;
				}
			}
			$url = get_author_posts_url( $user_id );
			if ( empty( $url ) ) {
				continue;
			}
			$urls[] = array(
				'loc'     => $url,
				'lastmod' => gmdate( 'Y-m-d\TH:i:sP' ),
			);
		}

		return $urls;
	}

	/**
	 * Render URLs to XML.
	 *
	 * @param array $urls URLs.
	 * @return string
	 */
	private static function render( $urls ) {
		Renderer::set_stylesheet_url( home_url( '/seovault-sitemap.xsl' ) );
		return Renderer::urlset( $urls );
	}
}
