<?php
/**
 * Background Processing for Coupon Updates
 *
 * @package Echo_Rewards
 */

namespace ECRE;

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

/**
 * Class Ecre_Background_Processor
 */
class Ecre_Background_Processor {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Register Action Scheduler hook.
		add_action( 'ecre_background_update_coupons', array( $this, 'process_coupon_updates' ), 10, 2 );
	}

	/**
	 * Background processor for coupon updates using Action Scheduler
	 *
	 * @param array  $settings Settings data.
	 * @param string $process_id Unique process identifier.
	 */
	public function process_coupon_updates( $settings, $process_id ) {
		// Check if this process should run.
		$current_process = get_option( 'ecre_current_coupon_process' );
		if ( $current_process !== $process_id ) {
			// Process was cancelled.
			$this->log_process_cancelled( $process_id );
			return;
		}

		// Set processing flag.
		update_option(
			'ecre_coupon_update_in_progress',
			array(
				'process_id' => $process_id,
				'started_at' => current_time( 'mysql' ),
				'status'     => 'processing',
			)
		);

		// Call the main update function with cancellation support.
		ecre_update_referral_coupons( $settings, $process_id );

		// Check if process completed or was cancelled.
		$final_check = get_option( 'ecre_current_coupon_process' );
		if ( $final_check === $process_id ) {
			// Process completed successfully.
			$this->log_process_completed( $process_id );
		} else {
			// Process was cancelled.
			$this->log_process_cancelled( $process_id );
		}
	}

	/**
	 * Log process completion
	 *
	 * @param string $process_id Process identifier.
	 */
	private function log_process_completed( $process_id ) {
		$progress = get_option( 'ecre_coupon_update_in_progress', array() );
		update_option(
			'ecre_coupon_update_in_progress',
			array(
				'process_id'   => $process_id,
				'started_at'   => isset( $progress['started_at'] ) ? $progress['started_at'] : current_time( 'mysql' ),
				'completed_at' => current_time( 'mysql' ),
				'status'       => 'completed',
			)
		);
	}

	/**
	 * Log process cancellation
	 *
	 * @param string $process_id Process identifier.
	 */
	private function log_process_cancelled( $process_id ) {
		$progress = get_option( 'ecre_coupon_update_in_progress', array() );
		update_option(
			'ecre_coupon_update_in_progress',
			array(
				'process_id'   => $process_id,
				'started_at'   => isset( $progress['started_at'] ) ? $progress['started_at'] : current_time( 'mysql' ),
				'cancelled_at' => current_time( 'mysql' ),
				'status'       => 'cancelled',
			)
		);
	}
}
