<?php
/**
 * Cache Plugin Compatibility — ensure Mersal features work with caching plugins.
 *
 * Excludes Mersal admin pages, REST API, and AJAX from page caching.
 * Provides nonce refresh endpoint for front-end nonce validity.
 * Handles WP-Cron heartbeat for reliable cron execution.
 *
 * @package Mersal_Notif
 */

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

class Mersal_Notif_Cache_Compat {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		// Exclude Mersal pages from caching.
		add_action( 'init', array( $this, 'exclude_from_cache' ) );

		// Nonce refresh endpoint (authenticated users only).
		add_action( 'wp_ajax_mnotif_refresh_nonce', array( $this, 'ajax_refresh_nonce' ) );

		// Inject nonce refresh script on front-end when caching is active.
		add_action( 'wp_footer', array( $this, 'inject_nonce_refresh' ) );
	}

	/**
	 * Exclude Mersal pages from popular caching plugins.
	 */
	public function exclude_from_cache() {
		// WP Rocket (admin only).
		if ( is_admin() && function_exists( 'rocket_add_url_not_to_cache' ) ) {
			rocket_add_url_not_to_cache( admin_url( 'admin.php?page=mersal-notifications' ) );
			rocket_add_url_not_to_cache( admin_url( 'admin.php?page=mersal-campaign' ) );
			rocket_add_url_not_to_cache( admin_url( 'admin.php?page=mersal-otp' ) );
		}

		// LiteSpeed Cache (front-end).
		if ( ! is_admin() ) {
			add_filter( 'litespeed_exclude_urls', function ( $urls ) {
				$urls[] = '/wp-admin/admin-ajax.php';
				$urls[] = '/wp-json/mnotif/';
				return $urls;
			} );
		}

		// W3 Total Cache (front-end).
		if ( ! is_admin() ) {
			add_filter( 'w3tc_pgcache_reject_uri', function ( $uri ) {
				if ( false !== strpos( $uri, 'mnotif' ) || false !== strpos( $uri, 'mersal' ) ) {
					$uri .= '|mnotif|mersal';
				}
				return $uri;
			} );
		}
	}

	/**
	 * AJAX: Return a fresh nonce for front-end use.
	 */
	public function ajax_refresh_nonce() {
		wp_send_json_success( array(
			'nonce' => wp_create_nonce( 'wp_rest' ),
		) );
	}

	/**
	 * Inject nonce refresh script when caching plugins are active.
	 */
	public function inject_nonce_refresh() {
		if ( is_admin() ) {
			return;
		}

		// Check if any caching plugin is active.
		$caching_active = defined( 'WP_ROCKET_VERSION' )
			|| defined( 'LITESPEED_CACHE_VERSION' )
			|| defined( 'W3TC_VERSION' )
			|| defined( 'WP_SUPER_CACHE_VERSION' )
			|| defined( 'WP_FASTEST_CACHE_VERSION' );

		if ( ! $caching_active ) {
			return;
		}
		?>
		<script>
		(function(){
			// Refresh nonce every 10 minutes.
			setInterval(function(){
				fetch('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>?action=mnotif_refresh_nonce')
					.then(function(r){return r.json();})
					.then(function(d){if(d.data&&d.data.nonce){window.mnotifNonce=d.data.nonce;}});
			},600000);
		})();
		</script>
		<?php
	}
}
