<?php
/**
 * Sitemap Scheduler
 *
 * Registers cron schedules and rebuild events.
 *
 * @package SEOvaultSEO
 */

namespace SEOvaultSEO\Sitemap;

use SEOvaultSEO\Core\Options;

/**
 * Cron scheduling for sitemap rebuilds
 */
class Scheduler {

	/**
	 * Cron schedule name.
	 *
	 * @var string
	 */
	const SCHEDULE_NAME = 'seovaultseo_sitemap_every_six_hours';

	/**
	 * Cron event name.
	 *
	 * @var string
	 */
	const EVENT_NAME = 'seovaultseo_sitemap_rebuild';

	/**
	 * Initialize scheduler.
	 */
	public static function init() {
		add_filter( 'cron_schedules', array( __CLASS__, 'add_schedule' ) );
		add_action( 'wp_loaded', array( __CLASS__, 'ensure_scheduled' ) );
		add_action( self::EVENT_NAME, array( __CLASS__, 'run_rebuild' ) );
	}

	/**
	 * Add the custom cron schedule.
	 *
	 * @param array $schedules Existing schedules.
	 * @return array
	 */
	public static function add_schedule( $schedules ) {
		$schedules[ self::SCHEDULE_NAME ] = array(
			'interval' => 6 * HOUR_IN_SECONDS,
			// WP 6.7+: do not call __() while cron_schedules may run before init.
			'display'  => did_action( 'init' )
				? __( 'Every 6 Hours', 'seovault-ai' )
				: 'Every 6 Hours',
		);
		return $schedules;
	}

	/**
	 * Schedule the rebuild event if not already scheduled.
	 */
	public static function schedule() {
		if ( ! wp_next_scheduled( self::EVENT_NAME ) ) {
			$frequency = Options::get_sitemap_cron_frequency();
			wp_schedule_event( time(), $frequency, self::EVENT_NAME );
		}
	}

	/**
	 * Unschedule all rebuild events (recurring and single).
	 */
	public static function unschedule() {
		// CRON-002: clear every scheduled occurrence, not only the next one.
		wp_clear_scheduled_hook( self::EVENT_NAME );
	}

	/**
	 * Ensure the event is scheduled when sitemap is enabled.
	 */
	public static function ensure_scheduled() {
		if ( ! Options::is_sitemap_enabled() ) {
			self::unschedule();
			return;
		}
		self::schedule();
	}

	/**
	 * Run the scheduled rebuild.
	 */
	public static function run_rebuild() {
		Builder::rebuild();
	}
}
