<?php
/**
 * Pro: schedule-based rule gating.
 *
 * Hooks into `esrn_should_apply_rule` and returns false when the current
 * moment is outside the rule's configured window.
 *
 * @package EasySearchReplace
 */

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

/**
 * Check schedule (date range, time-of-day, day-of-week) for a rule.
 *
 * All comparisons use WordPress site time (current_time() with a 'timestamp'
 * request) so behavior follows whatever timezone the admin set.
 */
class ESRN_Pro_Scheduler {

	/**
	 * Register the filter. Called from the main plugin file only when Pro is active.
	 */
	public static function register() {
		add_filter( 'esrn_should_apply_rule', array( __CLASS__, 'check' ), 10, 3 );
	}

	/**
	 * Filter callback.
	 *
	 * @param bool  $apply   Current decision from earlier filters.
	 * @param array $rule    Normalized rule.
	 * @param array $context Request context (includes 'timestamp' in site tz).
	 * @return bool
	 */
	public static function check( $apply, $rule, $context ) {
		if ( ! $apply ) {
			return false;
		}

		$sched = isset( $rule['schedule'] ) && is_array( $rule['schedule'] ) ? $rule['schedule'] : array();

		// If schedule is disabled, nothing to check.
		if ( empty( $sched['enabled'] ) ) {
			return true;
		}

		$now = isset( $context['timestamp'] ) ? (int) $context['timestamp'] : current_time( 'timestamp' );

		// Date window.
		if ( ! empty( $sched['start_date'] ) ) {
			$start = strtotime( $sched['start_date'] . ' 00:00:00' );
			if ( false !== $start && $now < $start ) {
				return false;
			}
		}
		if ( ! empty( $sched['end_date'] ) ) {
			$end = strtotime( $sched['end_date'] . ' 23:59:59' );
			if ( false !== $end && $now > $end ) {
				return false;
			}
		}

		// Day of week (0 = Sunday .. 6 = Saturday).
		if ( ! empty( $sched['days'] ) && is_array( $sched['days'] ) ) {
			$today = (int) gmdate( 'w', $now );
			if ( ! in_array( $today, array_map( 'intval', $sched['days'] ), true ) ) {
				return false;
			}
		}

		// Time of day.
		$has_start_t = ! empty( $sched['start_time'] );
		$has_end_t   = ! empty( $sched['end_time'] );
		if ( $has_start_t || $has_end_t ) {
			$now_hm = gmdate( 'H:i', $now );
			if ( $has_start_t && $has_end_t && $sched['start_time'] <= $sched['end_time'] ) {
				// Same-day window, e.g. 09:00 - 17:00.
				if ( $now_hm < $sched['start_time'] || $now_hm > $sched['end_time'] ) {
					return false;
				}
			} elseif ( $has_start_t && $has_end_t ) {
				// Overnight window, e.g. 22:00 - 02:00 - inside means
				// (after start) OR (before end).
				if ( $now_hm < $sched['start_time'] && $now_hm > $sched['end_time'] ) {
					return false;
				}
			} elseif ( $has_start_t && $now_hm < $sched['start_time'] ) {
				return false;
			} elseif ( $has_end_t && $now_hm > $sched['end_time'] ) {
				return false;
			}
		}

		return true;
	}
}
