<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Background {

	private static $queue = array();

	public static function add_to_queue( $hook, $args = array() ) {
		$queue = get_option( 'zacls_background_queue', array() );
		$queue[] = array(
			'hook'      => sanitize_key( $hook ),
			'args'      => $args,
			'added'     => current_time( 'mysql' ),
		);

		$queue = array_slice( $queue, -100 );
		update_option( 'zacls_background_queue', $queue, false );

		if ( ! wp_next_scheduled( 'zacls_process_queue' ) ) {
			wp_schedule_single_event( time() + 30, 'zacls_process_queue' );
		}

		return true;
	}

	public static function process_queue() {
		$queue = get_option( 'zacls_background_queue', array() );
		if ( empty( $queue ) ) {
			return;
		}

		$batch    = array_splice( $queue, 0, 10 );
		$executed = 0;

		foreach ( $batch as $job ) {
			if ( empty( $job['hook'] ) ) {
				continue;
			}

			$args = isset( $job['args'] ) ? (array) $job['args'] : array();

			switch ( $job['hook'] ) {
				case 'geoip_lookup':
					if ( ! empty( $args['ip'] ) ) {
						ZACLS_Main::lookup_country( $args['ip'] );
						$executed++;
					}
					break;

				case 'file_scan':
					ZACLS_File_Monitor::run_full_scan();
					$executed++;
					break;

				case 'vuln_scan':
					ZACLS_Vulnerability_Scanner::scan_plugins();
					$executed++;
					break;

				case 'send_notification':
					if ( ! empty( $args['type'] ) && ! empty( $args['message'] ) ) {
						ZACLS_Notifications::add( $args['type'], $args['message'] );
						$executed++;
					}
					break;

				case 'generate_report':
					ZACLS_Main::send_scheduled_report();
					$executed++;
					break;

				case 'cleanup':
					ZACLS_Main::cleanup_expired_data();
					$executed++;
					break;

				default:
					do_action( 'zacls_background_' . $job['hook'], $args );
					$executed++;
					break;
			}
		}

		update_option( 'zacls_background_queue', $queue, false );

		if ( ! empty( $queue ) ) {
			wp_schedule_single_event( time() + 30, 'zacls_process_queue' );
		}

		return $executed;
	}
}
