<?php
/**
 * Recovery Component
 *
 * Handles all recovery-related cron jobs (Immediate Recovery, Value Reinforcement, Final Attempt).
 *
 * @package EDD\Pro\CartRecovery\Cron\Components
 * @copyright Copyright (c) 2026, Sandhills Development, LLC
 * @license https://opensource.org/licenses/GPL-3.0 GNU General Public License v3.0
 * @since   3.6.5
 */

namespace EDD\Pro\CartRecovery\Cron\Components;

use EDD\Cron\Components\Component;
use EDD\Pro\CartRecovery\Jobs\RecoveryEmail;
use EDD\Pro\CartRecovery\Jobs\BatchRecovery;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

/**
 * Recovery Component Class
 *
 * Subscribes to recovery-related cron hooks and delegates to job classes.
 *
 * @since 3.6.5
 */
class Recovery extends Component {

	/**
	 * The unique identifier for this component.
	 *
	 * @since 3.6.5
	 * @var string
	 */
	protected static $id = 'acr_recovery';

	/**
	 * Get the subscribed events for recovery jobs.
	 *
	 * @since 3.6.5
	 *
	 * @return array The array of hook => method mappings.
	 */
	public static function get_subscribed_events(): array {
		return array(
			'edd_acr_recovery_email'          => 'handle_recovery_email',
			'edd_acr_recovery_email_retry'    => array( 'handle_recovery_email_retry', 10, 2 ),
			'edd_acr_process_abandoned_batch' => array( 'handle_batch_recovery', 10, 2 ),
		);
	}

	/**
	 * Handle recovery email job.
	 *
	 * @since 3.6.5
	 *
	 * @param int $cart_id The cart ID.
	 * @return void
	 */
	public function handle_recovery_email( int $cart_id = 0 ): void {
		$recovery_email = new RecoveryEmail();
		$recovery_email->handle( $cart_id, 1 );
	}

	/**
	 * Handle recovery email retry job.
	 *
	 * @since 3.6.5
	 *
	 * @param int $cart_id        The cart ID.
	 * @param int $attempt_number The attempt number.
	 * @return void
	 */
	public function handle_recovery_email_retry( int $cart_id = 0, int $attempt_number = 2 ): void {
		$recovery_email = new RecoveryEmail();
		$recovery_email->handle( $cart_id, $attempt_number );
	}

	/**
	 * Handle batch recovery job.
	 *
	 * WordPress passes action arguments as separate parameters, not as a single array.
	 * We need to accept them individually and then construct the array for BatchRecovery::handle().
	 *
	 * @since 3.6.5
	 *
	 * @param string $batch_hash    The batch hash (first arg from scheduled action).
	 * @param string $cart_ids_json The JSON-encoded array of cart IDs (second arg from scheduled action).
	 * @return void
	 */
	public function handle_batch_recovery( string $batch_hash = '', string $cart_ids_json = '' ): void {
		// Decode the JSON-encoded cart IDs (Action Scheduler doesn't handle nested arrays).
		$cart_ids = json_decode( $cart_ids_json, true );

		if ( ! is_array( $cart_ids ) || empty( $cart_ids ) ) {
			return;
		}

		// Construct the args array that BatchRecovery::handle() expects.
		$args = array(
			'batch_hash' => $batch_hash,
			'cart_ids'   => $cart_ids,
		);
		BatchRecovery::handle( $args );
	}
}
