<?php
/**
 * The wp-rocket compatibility functionality.
 *
 * @since      3.2.3
 * @package    Rank Math
 * @subpackage RankMath\Compatibility
 * @author     MyThemeShop <admin@mythemeshop.com>
 */

defined( 'ABSPATH' ) || exit;

// Ealry Bail!!
if ( ! defined( 'RANK_MATH_FILE' ) || ! \RankMath\Helper::is_module_active( 'sitemap' ) ) {
	return;
}

/**
 * Add sitemap option to WP Rocket settings
 *
 * @since 3.2.3
 *
 * @param array $options WP Rocket settings array.
 * @return array Updated WP Rocket settings array
 */
function rank_math_rocket_sitemap_preload_option( $options ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
	$options['rank_math_xml_sitemap'] = [
		'type'              => 'checkbox',
		'container_class'   => [
			'wpr-field--children',
		],
		'label'             => __( 'Rank Math XML sitemap', 'rocket' ),
		// translators: %s = Name of the plugin.
		'description'       => sprintf( __( 'We automatically detected the sitemap generated by the %s plugin. You can check the option to preload it.', 'rocket' ), 'Rank Math SEO' ),
		'parent'            => 'sitemap_preload',
		'section'           => 'preload_section',
		'page'              => 'preload',
		'default'           => 0,
		'sanitize_callback' => 'sanitize_checkbox',
	];

	return $options;
}
add_filter( 'rocket_sitemap_preload_options', 'rank_math_rocket_sitemap_preload_option' );

/**
 * Add sitemap option to WP Rocket default options
 *
 * @since 3.2.3
 *
 * @param array $options WP Rocket options array.
 * @return array Updated WP Rocket options array
 */
function rank_math_rocket_add_sitemap_option( $options ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
	$options['rank_math_xml_sitemap'] = 0;

	return $options;
}
add_filter( 'rocket_first_install_options', 'rank_math_rocket_add_sitemap_option' );

/**
 * Sanitize SEO sitemap option value
 *
 * @since 3.2.3
 *
 * @param array $inputs WP Rocket inputs array.
 * @return array Sanitized WP Rocket inputs array
 */
function rank_math_rocket_sitemap_option_sanitize( $inputs ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
	$inputs['rank_math_xml_sitemap'] = ! empty( $inputs['rank_math_xml_sitemap'] ) ? 1 : 0;

	return $inputs;
}
add_filter( 'rocket_inputs_sanitize', 'rank_math_rocket_sitemap_option_sanitize' );

/**
 * Add SEO sitemap URL to the sitemaps to preload
 *
 * @since 3.2.3
 *
 * @param array $sitemaps Sitemaps to preload.
 * @return array Updated Sitemaps to preload
 */
function rank_math_rocket_sitemap( $sitemaps ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals
	if ( get_rocket_option( 'rank_math_xml_sitemap', false ) ) {
		$sitemaps[] = \RankMath\Sitemap\Router::get_base_url( 'sitemap_index.xml' );
	}

	return $sitemaps;
}
add_filter( 'rocket_sitemap_preload_list', 'rank_math_rocket_sitemap' );
