<?php
/**
 * ACR Cron Loader
 *
 * Registers ACR schedules, events, and components with the core EDD cron system.
 *
 * @package EDD\Pro\CartRecovery\Cron
 * @copyright Copyright (c) 2026, Sandhills Development, LLC
 * @license https://opensource.org/licenses/GPL-3.0 GNU General Public License v3.0
 * @since   3.6.5
 */

namespace EDD\Pro\CartRecovery\Cron;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

use EDD\EventManagement\SubscriberInterface;

/**
 * Cron Loader Class
 *
 * Integrates ACR cron functionality with the core EDD cron system via filters.
 *
 * @since 3.6.5
 */
class Loader implements SubscriberInterface {

	/**
	 * Get the events that this class is subscribed to.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	public static function get_subscribed_events(): array {
		if ( ! edd_get_option( 'acr_enabled', false ) ) {
			return array(
				'shutdown' => 'unschedule_all',
			);
		}

		return array(
			'edd_cron_schedules'  => 'register_schedules',
			'edd_cron_events'     => 'register_events',
			'edd_cron_components' => 'register_components',
		);
	}

	/**
	 * Register ACR custom schedules.
	 *
	 * @since 3.6.5
	 *
	 * @param array $schedules The existing registered schedules.
	 * @return array The schedules with ACR schedules added.
	 */
	public function register_schedules( array $schedules ): array {
		$schedules[] = new Schedules\Detection();

		return $schedules;
	}

	/**
	 * Register ACR cron events.
	 *
	 * @since 3.6.5
	 *
	 * @param array $events The existing registered events.
	 * @return array The events with ACR events added.
	 */
	public function register_events( array $events ): array {
		$events[] = new Events\DetectionHeartbeat();
		$events[] = new Events\DailyCleanup();
		$events[] = new Events\MaintenanceSweep();

		return $events;
	}

	/**
	 * Register ACR cron components.
	 *
	 * @since 3.6.5
	 *
	 * @param array $components The existing registered component classes.
	 * @return array The components with ACR components added.
	 */
	public function register_components( array $components ): array {
		$components[] = Components\Recovery::class;
		$components[] = Components\Detection::class;
		$components[] = Components\Cleanup::class;
		$components[] = Components\Maintenance::class;

		return $components;
	}

	/**
	 * Unschedule all cart recovery cron jobs.
	 *
	 * @since 3.6.5
	 */
	public function unschedule_all(): void {
		if ( edd_get_option( 'acr_enabled', false ) ) {
			return;
		}

		$scheduler = \EDD\Cron\Schedulers\Handler::get_scheduler();
		$scheduler->unschedule_all( null, array(), 'edd_acr' );
	}
}
