<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class LVSW_Cron {
	public static function init() {
		add_filter( 'cron_schedules', array( __CLASS__, 'add_cron_intervals' ) );
		add_action( LVSW_Plugin::CRON_HOOK, array( __CLASS__, 'cron_handler' ) );
	}

	public static function add_cron_intervals( $schedules ) {
		$schedules['lvsw_6h'] = array(
			'interval' => 6 * HOUR_IN_SECONDS,
			'display'  => esc_html__( 'Every 6 hours', LVSW_Plugin::TEXT_DOMAIN ),
		);
		$schedules['lvsw_12h'] = array(
			'interval' => 12 * HOUR_IN_SECONDS,
			'display'  => esc_html__( 'Every 12 hours', LVSW_Plugin::TEXT_DOMAIN ),
		);
		$schedules['lvsw_daily'] = array(
			'interval' => DAY_IN_SECONDS,
			'display'  => esc_html__( 'Every 24 hours', LVSW_Plugin::TEXT_DOMAIN ),
		);
		if ( ! isset( $schedules['six_hours'] ) ) {
			$schedules['six_hours'] = $schedules['lvsw_daily'];
		} else {
			$schedules['six_hours']['interval'] = DAY_IN_SECONDS;
			$schedules['six_hours']['display']  = esc_html__( 'Every 24 hours', LVSW_Plugin::TEXT_DOMAIN );
		}
		return $schedules;
	}

	public static function schedule_key_from_opts( $opts ) {
		$interval = isset( $opts['scan_interval_hours'] ) ? (int) $opts['scan_interval_hours'] : 24;
		if ( 6 === $interval ) {
			return 'lvsw_6h';
		}
		if ( 12 === $interval ) {
			return 'lvsw_12h';
		}
		return 'lvsw_daily';
	}

	public static function ensure_cron_scheduled() {
		$opts   = LVSW_Plugin::get_opts();
		$wanted = self::schedule_key_from_opts( $opts );
		$event  = function_exists( 'wp_get_scheduled_event' ) ? wp_get_scheduled_event( LVSW_Plugin::CRON_HOOK ) : null;

		if ( ! $event ) {
			self::reschedule_cron( true );
			return;
		}

		if ( ! empty( $event->schedule ) && $event->schedule !== $wanted ) {
			self::reschedule_cron( true );
		}
	}

	public static function reschedule_cron( $force = false ) {
		if ( $force ) {
			wp_clear_scheduled_hook( LVSW_Plugin::CRON_HOOK );
		}
		if ( ! wp_next_scheduled( LVSW_Plugin::CRON_HOOK ) ) {
			$opts     = LVSW_Plugin::get_opts();
			$schedule = self::schedule_key_from_opts( $opts );
			wp_schedule_event( time() + 60, $schedule, LVSW_Plugin::CRON_HOOK );
			LVSW_Helpers::log_event( 'Cron scheduled (' . $schedule . ')' );
		}
	}

	public static function cron_handler() {
		try {
			LVSW_Scanner::do_scan();
		} catch ( Throwable $e ) {
			LVSW_Helpers::log_event( 'cron_handler exception: ' . $e->getMessage() );
		}
	}
}
