<?php
/**
 * WP-Cron scheduling: verification batches + daily maintenance.
 *
 * @package RedirectZen
 */

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

class RDZ_Cron {

	const VERIFY_HOOK      = 'rdz_verify_batch';
	const MAINTENANCE_HOOK = 'rdz_daily_maintenance';
	const DIGEST_HOOK      = 'rdz_weekly_digest';

	/**
	 * Hooks.
	 */
	public static function init() {
		add_filter( 'cron_schedules', array( __CLASS__, 'add_schedules' ) ); // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval

		add_action( self::VERIFY_HOOK, array( 'RDZ_Verifier', 'run_batch' ) );
		add_action( self::MAINTENANCE_HOOK, array( __CLASS__, 'daily_maintenance' ) );

		// Self-heal: cron events can be lost (e.g. by cache resets).
		add_action( 'admin_init', array( __CLASS__, 'ensure_scheduled' ) );
	}

	/**
	 * Adds the 5-minute batch interval.
	 *
	 * @param array $schedules Cron schedules.
	 * @return array
	 */
	public static function add_schedules( $schedules ) {
		if ( ! isset( $schedules['rdz_five_minutes'] ) ) {
			$schedules['rdz_five_minutes'] = array(
				'interval' => 5 * MINUTE_IN_SECONDS,
				'display'  => __( 'Every 5 minutes (RedirectZen verification batches)', 'redirectzen-301-redirect-manager' ),
			);
		}

		return $schedules;
	}

	/**
	 * Schedules the recurring events.
	 */
	public static function schedule_events() {
		// The activation hook runs after plugins_loaded, so make sure the
		// custom interval is registered before scheduling against it.
		add_filter( 'cron_schedules', array( __CLASS__, 'add_schedules' ) ); // phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval

		if ( ! wp_next_scheduled( self::VERIFY_HOOK ) ) {
			wp_schedule_event( time() + MINUTE_IN_SECONDS, 'rdz_five_minutes', self::VERIFY_HOOK );
		}

		if ( ! wp_next_scheduled( self::MAINTENANCE_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::MAINTENANCE_HOOK );
		}
	}

	/**
	 * Re-schedules events if they went missing.
	 */
	public static function ensure_scheduled() {
		self::schedule_events();
	}

	/**
	 * Daily housekeeping: prune the 404 log.
	 */
	public static function daily_maintenance() {
		RDZ_404_Log::prune();
	}

	/**
	 * Removes all recurring events.
	 */
	public static function clear_events() {
		wp_clear_scheduled_hook( self::VERIFY_HOOK );
		wp_clear_scheduled_hook( self::MAINTENANCE_HOOK );
		wp_clear_scheduled_hook( self::DIGEST_HOOK );
	}
}
