<?php
/**
 * Abandoned Cart Recovery admin asset registration.
 *
 * @package EDD\Pro\CartRecovery\Admin
 */

namespace EDD\Pro\CartRecovery\Admin;

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

use EDD\EventManagement\SubscriberInterface;

/**
 * Handles registering and enqueueing admin assets for ACR screens.
 */
final class Assets implements SubscriberInterface {

	/**
	 * Returns the subscribed events.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	public static function get_subscribed_events(): array {
		return array(
			'admin_enqueue_scripts' => 'enqueue',
		);
	}

	/**
	 * Enqueues assets for the Abandoned Cart Recovery admin screens.
	 *
	 * @since 3.6.5
	 */
	public function enqueue( $hook_suffix ): void {
		if ( 'download_page_edd-cart-recovery' !== $hook_suffix ) {
			return;
		}

		// Ensure assets are registered first.
		$this->register();

		// Core EDD admin assets ensure consistent styling and utilities.
		wp_enqueue_script( 'edd-cart-recovery' );

		// Localize script with AJAX settings.
		$this->localize_script();

		// Enqueue cart list styles on Carts tab.
		$tab = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_SPECIAL_CHARS );
		if ( ! $tab || in_array( $tab, array( 'carts', 'activity' ), true ) ) {
			wp_enqueue_style( 'edd-cart-recovery' );
		}
	}

	/**
	 * Localizes script data for cart recovery functionality.
	 *
	 * @since 3.6.5
	 */
	private function localize_script(): void {
		$script_settings = array(
			'nonce'    => wp_create_nonce( 'edd_acr_nonce' ),
			'ajaxurl'  => admin_url( 'admin-ajax.php' ),
			'messages' => array(
				'loadError'      => __( 'Failed to load cart details.', 'easy-digital-downloads' ),
				'genericFailure' => __( 'The request could not be completed.', 'easy-digital-downloads' ),
				'networkError'   => __( 'Network request failed.', 'easy-digital-downloads' ),
				'recovered'      => __( 'Recovered', 'easy-digital-downloads' ),
				'emailSent'      => __( 'Recovery email sent successfully.', 'easy-digital-downloads' ),
				'items'          => __( 'items', 'easy-digital-downloads' ),
			),
		);

		wp_localize_script(
			'edd-cart-recovery',
			'eddAcrAdmin',
			$script_settings
		);
	}

	/**
	 * Registers script and style handles for later enqueueing.
	 *
	 * @since 3.6.5
	 */
	public function register(): void {
		$css_suffix = is_rtl() ? '-rtl.min.css' : '.min.css';

		// Register ACR cart list styles.
		wp_register_style(
			'edd-cart-recovery',
			edd_get_assets_url( 'pro/css/recovery-list' ) . 'style' . $css_suffix,
			array( 'edd-admin' ),
			edd_admin_get_script_version()
		);

		wp_register_script(
			'edd-cart-recovery',
			edd_get_assets_url( 'pro/js/admin' ) . 'cart-recovery.js',
			array( 'edd-admin-settings' ),
			edd_admin_get_script_version()
		);
	}
}
