<?php
/**
 * Cron scheduling facade.
 *
 * @package LocalGuardScanner
 */

namespace LocalGuardScanner\Infrastructure\WordPress;

/**
 * Owns every cron hook registered by the plugin.
 */
final class CronScheduler {
	const DAILY_HOOK    = 'lgs_daily_scan';
	const CONTINUE_HOOK = 'lgs_continue_scan';
	const CLEANUP_HOOK  = 'lgs_cleanup';

	/**
	 * Schedule the daily event once.
	 *
	 * @param int $hour Local site hour.
	 * @return void
	 */
	public static function schedule_daily( $hour = 2 ) {
		if ( wp_next_scheduled( self::DAILY_HOOK ) ) {
			return;
		}
		$timezone = wp_timezone();
		$now      = new \DateTimeImmutable( 'now', $timezone );
		$next     = $now->setTime( max( 0, min( 23, (int) $hour ) ), 0 );
		if ( $next <= $now ) {
			$next = $next->modify( '+1 day' );
		}
		wp_schedule_event( $next->getTimestamp(), 'daily', self::DAILY_HOOK );
	}

	/** @return void */
	public static function schedule_continuation() {
		if ( ! wp_next_scheduled( self::CONTINUE_HOOK ) ) {
			wp_schedule_single_event( time() + 15, self::CONTINUE_HOOK );
		}
	}

	/** @return void */
	public static function schedule_cleanup() {
		if ( ! wp_next_scheduled( self::CLEANUP_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::CLEANUP_HOOK );
		}
	}

	/**
	 * Remove all scheduled hooks owned by the plugin.
	 *
	 * @return void
	 */
	public static function clear_all() {
		foreach ( array( self::DAILY_HOOK, self::CONTINUE_HOOK, self::CLEANUP_HOOK ) as $hook ) {
			wp_clear_scheduled_hook( $hook );
		}
	}
}
