<?php
/**
 * Scheduler wrapper.
 *
 * @package CartNinjaRecovery
 */

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

class CARTNINJA_Scheduler {

	const GROUP = 'cartninja';

	public function schedule_cart_abandonment( $cart_id, $minutes ) {
		$timestamp = time() + ( absint( $minutes ) * MINUTE_IN_SECONDS );
		$args      = array( absint( $cart_id ) );

		if ( function_exists( 'as_unschedule_all_actions' ) ) {
			as_unschedule_all_actions( 'cartninja_mark_cart_abandoned', $args, self::GROUP );
		}

		if ( function_exists( 'as_schedule_single_action' ) ) {
			as_schedule_single_action( $timestamp, 'cartninja_mark_cart_abandoned', $args, self::GROUP );
			return;
		}

		wp_schedule_single_event( $timestamp, 'cartninja_mark_cart_abandoned', $args );
	}

	public function schedule_notification( $cart_id, $channel ) {
		$timestamp = time() + MINUTE_IN_SECONDS;
		$args      = array( absint( $cart_id ), sanitize_key( $channel ) );

		if ( function_exists( 'as_schedule_single_action' ) ) {
			as_schedule_single_action( $timestamp, 'cartninja_send_cart_notification', $args, self::GROUP );
			return;
		}

		wp_schedule_single_event( $timestamp, 'cartninja_send_cart_notification', $args );
	}

	public function sync_cleanup_schedule( $enabled ) {
		$timestamp = wp_next_scheduled( 'cartninja_cleanup_tracking_data' );

		if ( $enabled ) {
			if ( ! $timestamp ) {
				wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'cartninja_cleanup_tracking_data' );
			}
			return;
		}

		if ( $timestamp ) {
			wp_clear_scheduled_hook( 'cartninja_cleanup_tracking_data' );
		}
	}
}
