<?php
/**
 * Batch Recovery Job handler for ActionScheduler.
 *
 * @package EDD\Pro\CartRecovery\Jobs
 * @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\Jobs;

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

use EDD\Pro\CartRecovery\Cron\SingleEventScheduler;

/**
 * Processes a batch of abandoned carts for recovery.
 * This replaces individual cart scheduling with optimized batch processing.
 */
final class BatchRecovery {

	/**
	 * Job entry point: process a batch of abandoned cart IDs.
	 *
	 * @since 3.6.5
	 * @param array $args Array containing 'cart_ids' key with array of cart IDs.
	 * @throws \Exception If the query preparation fails.
	 */
	public static function handle( array $args ): void {
		if ( empty( $args['cart_ids'] ) || ! is_array( $args['cart_ids'] ) ) {
			return;
		}

		$cart_ids = array_map( 'intval', $args['cart_ids'] );
		$cart_ids = array_filter(
			$cart_ids,
			function ( $id ) {
				return $id > 0;
			}
		);

		if ( empty( $cart_ids ) ) {
			return;
		}

		$processed = 0;
		$failed    = 0;

		foreach ( $cart_ids as $cart_id ) {
			try {
				// Schedule recovery email for each cart.
				$result = SingleEventScheduler::schedule_recovery_email( $cart_id );

				if ( $result ) {
					++$processed;
				} else {
					++$failed;
					edd_debug_log( sprintf( '[EDD ACR] BatchRecovery: Failed to schedule cart %d', $cart_id ) );
				}
			} catch ( \Exception $e ) {
				++$failed;
				edd_debug_log(
					sprintf(
						'[EDD ACR] BatchRecovery: Exception for cart %d: %s',
						$cart_id,
						$e->getMessage()
					)
				);
			}
		}
	}
}
