<?php
/**
 * Enqueue scripts and styles for the plugin.
 *
 * @package    MOMCS_Sync
 * @author     miniOrange
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Enqueue admin scripts and styles.
 *
 * @return void
 */
function momcs_sync_enqueue_admin_scripts() {
	$screen = get_current_screen();

	// Enqueue shipment sync assets on order edit screen (support both HPOS and legacy).
	if ( $screen && in_array( $screen->id, array( 'shop_order', 'woocommerce_page_wc-orders' ), true ) ) {
		wp_enqueue_style(
			'momcs-fulfillment-status',
			MOMCS_PLUGIN_URL . 'assets/css/amazon-fulfillment-status.css',
			array(),
			MOMCS_VERSION
		);

		wp_enqueue_script(
			'momcs-fulfillment-status',
			MOMCS_PLUGIN_URL . 'assets/js/amazon-fulfillment-status.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);

		wp_localize_script(
			'momcs-fulfillment-status',
			'momcsFulfillmentStatus',
			array(
				'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
				'strings'  => array(
					'retryQueued' => esc_html__( 'Retry queued successfully.', 'multi-channel-for-woocommerce' ),
					'retryFailed' => esc_html__( 'Failed to queue retry.', 'multi-channel-for-woocommerce' ),
				),
			)
		);

		// Get order ID based on screen type.
		$order_id = 0;
		if ( 'woocommerce_page_wc-orders' === $screen->id && isset( $_GET['id'] ) ) {
			// HPOS: Get ID from query string.
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action is being performed.
			$order_id = absint( $_GET['id'] );
		} elseif ( 'shop_order' === $screen->id && isset( $_GET['post'] ) ) {
			// Legacy: Get ID from post.
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- No action is being performed.
			$order_id = absint( $_GET['post'] );
		}

		if ( $order_id ) {
			$order = wc_get_order( $order_id );

			// Only enqueue if this is an Amazon order.
			if ( $order && $order->get_meta( '_amazon_order_id' ) ) {
				wp_enqueue_style(
					'momcs-shipment-sync',
					MOMCS_PLUGIN_URL . 'assets/css/amazon-shipment-sync.css',
					array(),
					MOMCS_VERSION
				);

				wp_enqueue_script(
					'momcs-shipment-sync',
					MOMCS_PLUGIN_URL . 'assets/js/amazon-shipment-sync.js',
					array( 'jquery' ),
					MOMCS_VERSION,
					true
				);

				wp_localize_script(
					'momcs-shipment-sync',
					'momcsShipmentSync',
					array(
						'ajaxUrl' => admin_url( 'admin-ajax.php' ),
						'strings' => array(
							'min_one_package'   => esc_html__( 'At least one package is required.', 'multi-channel-for-woocommerce' ),
							/* translators: %d: Package number */
							'required_fields'   => esc_html__( 'Please fill in all required fields for Package %d.', 'multi-channel-for-woocommerce' ),
							/* translators: %d: Package number */
							'no_items_selected' => esc_html__( 'Please select at least one item for Package %d.', 'multi-channel-for-woocommerce' ),
							'ajax_error'        => esc_html__( 'An error occurred', 'multi-channel-for-woocommerce' ),
						),
					)
				);
			}
		}
	}

	// Only load on plugin pages.
	if ( strpos( $screen->id, 'momcs-sync' ) !== false ) {
		// Enqueue fonts CSS first.
		wp_enqueue_style(
			'momcs-sync-fonts',
			MOMCS_PLUGIN_URL . 'assets/css/fonts.css',
			array(),
			MOMCS_VERSION
		);

		// Enqueue main admin CSS.
		wp_enqueue_style(
			'momcs-sync-admin',
			MOMCS_PLUGIN_URL . 'assets/css/admin.css',
			array( 'momcs-sync-fonts' ),
			MOMCS_VERSION
		);

		// Enqueue stepper CSS.
		wp_enqueue_style(
			'momcs-sync-stepper',
			MOMCS_PLUGIN_URL . 'assets/css/stepper.css',
			array( 'momcs-sync-admin' ),
			MOMCS_VERSION
		);

		// Enqueue attribute mapping CSS.
		wp_enqueue_style(
			'momcs-sync-attribute-mapping',
			MOMCS_PLUGIN_URL . 'assets/css/attribute-mapping.css',
			array( 'momcs-sync-admin', 'momcs-sync-stepper' ),
			MOMCS_VERSION
		);

		// Enqueue custom CSS for enhanced UI.
		wp_enqueue_style(
			'momcs-sync-custom',
			MOMCS_PLUGIN_URL . 'assets/css/custom.css',
			array( 'momcs-sync-admin', 'momcs-sync-stepper', 'momcs-sync-attribute-mapping' ),
			MOMCS_VERSION
		);

		// Dark mode loads in admin_footer after all page-rendered enqueues (class-enqueue-scripts.php).

		// Register additional extracted scripts so that view-specific code can enqueue them.
		wp_register_script(
			'momcs-sync-product-settings',
			MOMCS_PLUGIN_URL . 'assets/js/product-settings.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);
		wp_register_script(
			'momcs-field-mapping',
			MOMCS_PLUGIN_URL . 'assets/js/amazon-field-mapping.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);
		wp_register_script(
			'momcs-template-mapping',
			MOMCS_PLUGIN_URL . 'assets/js/amazon-template-mapping.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);
		wp_register_script(
			'momcs-marketplace-stepper',
			MOMCS_PLUGIN_URL . 'assets/js/marketplace-stepper.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);

		// Register Amazon Mapping View JS extracted from inline script.
		wp_register_script(
			'momcs-mapping-view',
			MOMCS_PLUGIN_URL . 'assets/js/amazon-mapping-view.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);

		// Enqueue admin JS.
		wp_enqueue_script(
			'momcs-sync-admin',
			MOMCS_PLUGIN_URL . 'assets/js/admin.js',
			array( 'jquery' ),
			MOMCS_VERSION,
			true
		);

		// Enqueue order-specific assets on orders page.
		if ( false !== strpos( $screen->id, 'momcs-sync-orders' ) ) {
			// Enqueue modern order list CSS.
			wp_enqueue_style(
				'momcs-order-list-modern',
				MOMCS_PLUGIN_URL . 'assets/css/order-list-modern.css',
				array( 'momcs-sync-admin' ),
				MOMCS_VERSION
			);

			// Enqueue order search JS.
			wp_enqueue_script(
				'momcs-order-search',
				MOMCS_PLUGIN_URL . 'assets/js/order-search.js',
				array( 'jquery', 'momcs-sync-admin' ),
				MOMCS_VERSION,
				true
			);

			// Localize order search script.
			wp_localize_script(
				'momcs-order-search',
				'momcs_sync',
				array(
					'ajax_url' => admin_url( 'admin-ajax.php' ),
					'nonce'    => wp_create_nonce( \MOMCS_Sync\Includes\Common\Constants\Plugin_Constants::NONCE_MAIN ),
				)
			);
		}

		// Enqueue account-specific assets on account page.
		if ( false !== strpos( $screen->id, 'momcs-sync-account' ) ) {
			// Enqueue modern account CSS.
			wp_enqueue_style(
				'momcs-account-modern',
				MOMCS_PLUGIN_URL . 'assets/css/account-modern.css',
				array( 'momcs-sync-admin' ),
				MOMCS_VERSION
			);
		}

		// Localize strings & nonces for the mapping view script and enqueue it when attribute mapping view is present.
		wp_localize_script(
			'momcs-mapping-view',
			'momcs_mapping_params',
			array(
				'ajaxurl'                     => admin_url( 'admin-ajax.php' ),
				'nonce_get_unified_mapping'   => wp_create_nonce( 'momcs_sync_get_unified_mapping_nonce' ),
				'i18n_fix_errors'             => esc_html__( 'Please fix the following errors before continuing:', 'multi-channel-for-woocommerce' ),
				'i18n_all_good'               => esc_html__( 'All required mappings are configured correctly.', 'multi-channel-for-woocommerce' ),
				'i18n_select_wc_category'     => esc_html__( 'Please select a WooCommerce category for all rows.', 'multi-channel-for-woocommerce' ),
				'i18n_select_amazon_category' => esc_html__( 'Please select an Amazon category.', 'multi-channel-for-woocommerce' ),
			)
		);
		wp_enqueue_script( 'momcs-mapping-view' );

	}
}

add_action( 'admin_enqueue_scripts', 'momcs_sync_enqueue_admin_scripts' );

/**
 * Whether a stylesheet handle is part of this plugin (or closely coupled vendor) UI.
 *
 * Used to determine dependency ordering for dark mode CSS so it prints last among plugin styles.
 *
 * @param string $handle Style handle.
 * @return bool
 */
function momcs_sync_is_plugin_related_style_handle( string $handle ): bool {
	if ( strpos( $handle, 'momcs' ) === 0 ) {
		return true;
	}

	if ( strpos( $handle, 'mo-lic' ) === 0 || strpos( $handle, 'momcs_license' ) === 0 ) {
		return true;
	}

	$vendor = array( 'tom-select', 'flag-icons' );
	return in_array( $handle, $vendor, true );
}

/**
 * Last enqueued plugin-related style handle on the current request (for dark mode dependency).
 *
 * @return string Empty string if none matched.
 */
function momcs_sync_get_last_plugin_style_dependency(): string {
	global $wp_styles;

	if ( ! $wp_styles instanceof WP_Styles ) {
		return '';
	}

	$last = '';
	foreach ( (array) $wp_styles->queue as $handle ) {
		if ( 'momcs-sync-dark-mode' === $handle ) {
			continue;
		}
		if ( momcs_sync_is_plugin_related_style_handle( $handle ) ) {
			$last = $handle;
		}
	}

	return $last;
}

/**
 * Enqueue dark mode stylesheet in the footer so it loads after styles queued during the page callback.
 *
 * @return void
 */
function momcs_sync_enqueue_dark_mode_in_admin_footer(): void {
	if ( ! function_exists( 'get_current_screen' ) ) {
		return;
	}

	$screen = get_current_screen();
	if ( ! $screen ) {
		return;
	}

	$is_momcs = strpos( $screen->id, 'momcs-sync' ) !== false;
	$is_order = in_array( $screen->id, array( 'shop_order', 'woocommerce_page_wc-orders' ), true );

	if ( ! $is_momcs && ! $is_order ) {
		return;
	}

	$dep = momcs_sync_get_last_plugin_style_dependency();

	if ( '' === $dep && wp_style_is( 'dashicons', 'enqueued' ) ) {
		$dep = 'dashicons';
	}

	$deps = '' !== $dep ? array( $dep ) : array();

	wp_enqueue_style(
		'momcs-sync-dark-mode',
		MOMCS_PLUGIN_URL . 'assets/css/dark-mode.css',
		$deps,
		defined( 'MOMCS_VERSION' ) ? MOMCS_VERSION : '1.0.0'
	);
}

add_action( 'admin_footer', 'momcs_sync_enqueue_dark_mode_in_admin_footer', 999 );
