<?php

class ITSEC_Malware_Scheduling {
	public function run() {
		add_action( 'itsec_malware_scheduled_scan', array( $this, 'run_scan' ) );
		add_filter( 'itsec_sync_modules', array( $this, 'itsec_sync_modules' ) );
	}

	public function run_scan() {
		require_once( dirname( __FILE__ ) . '/class-itsec-malware-scheduling-scanner.php' );

		ITSEC_Malware_Scheduling_Scanner::scan();
	}

	public static function update_schedule() {
		$hook = 'itsec_malware_scheduled_scan';

		// Unschedule any existing schedules. This is to prevent faults from creating multiple schedules.
		$timestamp = wp_next_scheduled( $hook );
		$count = 0;

		while ( false !== $timestamp ) {
			wp_unschedule_event( $timestamp, $hook );

			$timestamp = wp_next_scheduled( $hook );

			if ( ++$count > 20 ) {
				// Prevent endless loops.
				break;
			}
		}

		wp_schedule_event( time(), 'twicedaily', $hook );
	}

	/**
	 * Register malware scheduling for Sync
	 *
	 * @param  array $sync_modules array of malware modules
	 *
	 * @return array                   array of logger modules
	 */
	public function itsec_sync_modules( $sync_modules ) {
		$sync_modules['malware_scheduling'] = array(
			'verbs'      => array(
				'itsec-get-malware-schedule-settings'    => 'Ithemes_Sync_Verb_ITSEC_Get_Malware_Schedule_Settings',
				'itsec-manage-malware-schedule-settings' => 'Ithemes_Sync_Verb_ITSEC_Manage_Malware_Schedule_Settings',
			),
			'everything' => 'itsec-get-malware-schedule-settings',
			'path'       => dirname( __FILE__ ),
		);

		return $sync_modules;
	}
}
