<?php
/**
 * Cron Scheduler Service
 *
 * Handles WordPress cron job registration and execution for plugin features.
 *
 * @package AIPT\Core\Services
 * @since 2.4.0
 */

namespace AIPT\Core\Services;

use AIPT\Api\AutomationJobs\AutomationJobManager;
use AIPT\Api\AutomationJobs\JobLogger;
use AIPT\Api\AutomationJobs\JobScheduler;

/**
 * Manages WP-Cron schedules for plugin
 *
 * @internal Used by Init
 */
class CronScheduler {

	/**
	 * Init instance
	 *
	 * @var \AIPT\Core\Init
	 */
	private $init;

	/**
	 * Constructor
	 *
	 * @param \AIPT\Core\Init $init Init instance.
	 */
	public function __construct( \AIPT\Core\Init $init ) {
		$this->init = $init;
	}

	/**
	 * Add automation jobs cron intervals
	 *
	 * @param array $schedules Existing schedules.
	 * @return array Modified schedules.
	 */
	public function addAutomationIntervals( array $schedules ): array {

		if ( ! isset( $schedules['aipt_two_minutes'] ) ) {
			$schedules['aipt_two_minutes'] = array(
				'interval' => 120,
				'display'  => __( 'Every 2 Minutes', 'ai-product-tools' ),
			);
		}

		if ( ! isset( $schedules['aipt_five_minutes'] ) ) {
			$schedules['aipt_five_minutes'] = array(
				'interval' => 300,
				'display'  => __( 'Every 5 Minutes', 'ai-product-tools' ),
			);
		}

		return $schedules;
	}

	/**
	 * Process automation jobs cron callback
	 */
	public function processAutomationJobs(): void {
		try {

			if ( ! class_exists( '\AIPT\Api\AutomationJobs\AutomationJobManager' ) ) {
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				}
				return;
			}

			$job_manager = new AutomationJobManager();
			$logger      = new JobLogger();
			$scheduler   = new JobScheduler( $job_manager, $logger );

			$processed = $scheduler->processPendingJobs();

		} catch ( \Exception $e ) {

			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			}
		}
	}

	/**
	 * Monitor automation jobs cron callback
	 */
	public function monitorAutomationJobs(): void {
		try {

			if ( ! class_exists( '\AIPT\Api\AutomationJobs\AutomationJobManager' ) ) {
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				}
				return;
			}

			$job_manager = new AutomationJobManager();
			$logger      = new JobLogger();
			$scheduler   = new JobScheduler( $job_manager, $logger );

			$monitored = $scheduler->monitorRunningJobs();

		} catch ( \Exception $e ) {

			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			}
		}
	}

	/**
	 * Setup automation jobs cron schedules
	 */
	public function setupAutomationSchedules(): void {
		try {
			JobScheduler::setupCronSchedules();
		} catch ( \Exception $e ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
			}
		}
	}
}
