<?php
/**
 * WP-Cron scheduling.
 *
 * @package 404Zen
 */

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

class LGBF_Cron {

	const BATCH_HOOK  = 'lgbf_scan_batch';
	const DIGEST_HOOK = 'lgbf_weekly_digest';

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

		// 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['lgbf_five_minutes'] ) ) {
			$schedules['lgbf_five_minutes'] = array(
				'interval' => 5 * MINUTE_IN_SECONDS,
				'display'  => __( 'Every 5 minutes (404Zen batches)', '404zen-broken-link-fixer' ),
			);
		}

		return $schedules;
	}

	/**
	 * Schedules both 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::BATCH_HOOK ) ) {
			wp_schedule_event( time() + MINUTE_IN_SECONDS, 'lgbf_five_minutes', self::BATCH_HOOK );
		}

		if ( ! wp_next_scheduled( self::DIGEST_HOOK ) ) {
			wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', self::DIGEST_HOOK );
		}
	}

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

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