<?php

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

		add_action( 'ithemes_sync_register_verbs', array( $this, 'register_sync_verbs' ) );
		add_filter( 'itsec-filter-itsec-get-everything-verbs', array( $this, 'register_sync_get_everything_verbs' ) );
		add_action( 'itsec_change_admin_user_id', array( $this, 'update_notification_user_id_on_admin_change' ) );
	}

	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 verbs for Sync.
	 *
	 * @since 3.6.0
	 *
	 * @param Ithemes_Sync_API $api Sync API object.
	 */
	public function register_sync_verbs( $api ) {
		$api->register( 'itsec-get-malware-schedule-settings', 'Ithemes_Sync_Verb_ITSEC_Get_Malware_Schedule_Settings', dirname( __FILE__ ) . '/sync-verbs/itsec-get-malware-schedule-settings.php' );
		$api->register( 'itsec-manage-malware-schedule-settings', 'Ithemes_Sync_Verb_ITSEC_Manage_Malware_Schedule_Settings', dirname( __FILE__ ) . '/sync-verbs/itsec-manage-malware-schedule-settings.php' );
	}

	/**
	 * Filter to add verbs to the response for the itsec-get-everything verb.
	 *
	 * @since 3.6.0
	 *
	 * @param array $verbs
	 *
	 * @return array Array of verbs.
	 */
	public function register_sync_get_everything_verbs( $verbs ) {
		$verbs['malware_scheduling'][] = 'itsec-get-malware-schedule-settings';

		return $verbs;
	}

	/**
	 * Update the notification settings when the admin user id changes.
	 *
	 * @since 4.1.0
	 *
	 * @param int $new_user_id
	 */
	public function update_notification_user_id_on_admin_change( $new_user_id ) {

		$settings = ITSEC_Modules::get_settings_obj( 'malware-scheduling' );
		$contacts = $settings->get( 'email_contacts' );

		if ( ! is_array( $contacts ) ) {
			return;
		}

		$changed = false;

		foreach ( $contacts as $i => $contact ) {
			if ( is_numeric( $contact ) && 1 === (int) $contact ) {
				$contacts[ $i ] = $new_user_id;
				$changed = true;
				break;
			}
		}

		if ( $changed ) {
			$settings->set( 'email_contacts', $contacts );
		}
	}
}
