<?php
/**
 * Enqueue Class
 *
 * Handles asset enqueuing for the Shop Explorer plugin
 *
 * @package SHOPEXPLORER\Inc
 * @since 1.0.0
 */

namespace SHOPEXPLORER\Inc;

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

/**
 * Enqueue class for handling assets
 *
 * @since 1.0.0
 */
class SHOPEX_Enqueue {

	/**
	 * Register hooks
	 *
	 * @since 1.0.0
	 */
	public function register() {
		add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'frontend_enqueue' ] );
	}

	/**
	 * Enqueue admin assets
	 *
	 * @param string $hook_suffix Current admin page hook suffix
	 * @since 1.0.0
	 */
	public function admin_enqueue( $hook_suffix ) {
		// Always enqueue admin CSS globally for menu icon
		wp_enqueue_style(
			'shop-explorer-admin-global',
			SHOPEX_URL . 'assets/css/admin.css',
			[],
			SHOPEX_VERSION
		);

		// Skip React app enqueuing for Shop Explorer admin page - AdminDashboard.php handles it
		if ( 'toplevel_page_shop-explorer' === $hook_suffix ) {
			// AdminDashboard.php handles the React app enqueuing and localization
			return;
		}

		// Maybe enqueue WooCommerce tracking scripts on admin pages too
		$this->maybe_enqueue_woo_tracking_admin( $hook_suffix );
	}

	/**
	 * Maybe enqueue WooCommerce tracking scripts in admin
	 *
	 * @param string $hook_suffix Current admin page hook suffix
	 * @since 1.0.0
	 */
	private function maybe_enqueue_woo_tracking_admin( $hook_suffix ) {
		// Check if WooCommerce is active
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		// Get WooCommerce settings
		$woo_settings = get_option( 'wpnts_schedules_interval_woocommerce_settings', [] );
		if ( is_string( $woo_settings ) ) {
			$woo_settings = json_decode( $woo_settings, true );
		}

		// Check if analytics is enabled
		$analytics_enabled = isset( $woo_settings['wooanalytics'] ) && $woo_settings['wooanalytics'];
		$incomplete_orders_enabled = isset( $woo_settings['incomplete_orders_tracking'] ) && $woo_settings['incomplete_orders_tracking'];
		$cart_interactions_enabled = isset( $woo_settings['cart_interactions_tracking'] ) && $woo_settings['cart_interactions_tracking'];

		// Only load if tracking is enabled
		if ( ! $analytics_enabled && ! $incomplete_orders_enabled && ! $cart_interactions_enabled ) {
			return;
		}

		// Check if we're on a WooCommerce admin page
		if ( ! $this->is_woocommerce_admin_page( $hook_suffix ) ) {
			return;
		}

		// Enqueue jQuery if not already loaded
		wp_enqueue_script( 'jquery' );

		// Enqueue cart session tracker for admin
		if ( $analytics_enabled || $cart_interactions_enabled ) {
			wp_enqueue_script(
				'wpnts-cart-session-tracker-admin',
				SHOPEX_URL . 'assets/js/wpnts-cart-session-tracker.js',
				[ 'jquery' ],
				SHOPEX_VERSION,
				true
			);

			wp_localize_script( 'wpnts-cart-session-tracker-admin', 'wpnts_cart_session_ajax', [
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'wpnts_checkout_tracking' ),
			]);
		}
	}

	/**
	 * Check if current admin page is a WooCommerce page
	 *
	 * @param string $hook_suffix Current admin page hook suffix
	 * @return bool
	 */
	private function is_woocommerce_admin_page( $hook_suffix ) {
		// WooCommerce admin pages
		$woo_pages = [
			'woocommerce_page_wc-orders',
			'woocommerce_page_wc-settings',
			'edit.php?post_type=shop_order',
			'edit.php?post_type=product',
			'post.php',
			'post-new.php',
		];

		// Check if it's a WooCommerce page
		foreach ( $woo_pages as $page ) {
			if ( strpos( $hook_suffix, $page ) !== false ) {
				return true;
			}
		}

		// Check if editing WooCommerce post types
		global $post_type;
		if ( in_array( $post_type, [ 'shop_order', 'product', 'shop_coupon' ] ) ) {
			return true;
		}

		// Check by screen
		$screen = get_current_screen();
		if ( $screen && in_array( $screen->post_type, [ 'shop_order', 'product', 'shop_coupon' ] ) ) {
			return true;
		}

		return false;
	}

	/**
	 * Enqueue React application
	 *
	 * @since 1.0.0
	 */
	private function enqueue_react_app() {
		// Check if build files exist
		$build_js_file = SHOPEX_PATH . 'build/index.bundle.js';

		if ( ! file_exists( $build_js_file ) ) {
			// Show admin notice if build file doesn't exist
			add_action( 'admin_notices', function () {
				echo '<div class="notice notice-error"><p>';
				esc_html_e( 'Shop Explorer: React build files not found. Please run "npm run build" to compile the assets.', 'shop-explorer' );
				echo '</p></div>';
			});
			return;
		}

		// Enqueue React dependencies
		wp_enqueue_script( 'wp-element' );
		wp_enqueue_script( 'wp-util' );

		// Enqueue WordPress Media Library
		wp_enqueue_media();

		// Try to find and enqueue CSS file (webpack may generate different names)
		$possible_css_files = [
			'build/index.bundle.css',
			'build/index.css',
			'build/style-index.css',
		];

		foreach ( $possible_css_files as $css_file ) {
			if ( file_exists( SHOPEX_PATH . $css_file ) ) {
				wp_enqueue_style(
					'shop-explorer-app-styles',
					SHOPEX_URL . $css_file,
					[],
					SHOPEX_VERSION
				);
				break;
			}
		}

		// Enqueue additional WordPress media dependencies
		wp_enqueue_script( 'media-models' );
		wp_enqueue_script( 'media-views' );
		wp_enqueue_script( 'media-editor' );

		// Enqueue main React app
		wp_enqueue_script(
			'shop-explorer-app',
			SHOPEX_URL . 'build/index.bundle.js',
			[ 'jquery', 'wp-element', 'wp-util', 'media-models', 'media-views', 'media-editor' ],
			SHOPEX_VERSION,
			true
		);

		// Get database instance and pro status
		$shopex_db_instance = new \SHOPEXPLORER\Database\DatabaseManager();
		$is_pro_active = $shopex_db_instance->is_pro_active();
	
		// Prepare localization data
		$localization_data = [
			'nonce' => wp_create_nonce( 'wp_rest' ),
			'apiUrl' => home_url( '/wp-json/shop-explorer/v1' ),
			'adminUrl' => admin_url(),
			'ajaxUrl' => admin_url( 'admin-ajax.php' ),
			'logoutUrl' => wp_logout_url( home_url( '/shop-explorer-dashboard' ) ),
			'currentUser' => $this->get_current_user_data(),
			'settings' => $this->get_plugin_settings(),
			'strings' => $this->get_localized_strings(),
			'notice_settings' => $this->get_notice_settings(),
			'isPro' => $is_pro_active,

			'mediaLibrary' => [
				'enabled' => true,
				'uploadUrl' => admin_url( 'async-upload.php' ),
			],
			'nonces' => [
				'wp_rest' => wp_create_nonce( 'wp_rest' ),
				'upload_image' => wp_create_nonce( 'shopex_upload_image' ),
				'media_nonce' => wp_create_nonce( 'shopex_media_nonce' ),
				'create_category' => wp_create_nonce( 'shopex_create_category' ),
				'create_tag' => wp_create_nonce( 'shopex_create_tag' ),
				'create_brand' => wp_create_nonce( 'shopex_create_brand' ),
			],
		];

		// Localize script with data (create both for compatibility)
		wp_localize_script( 'shop-explorer-app', 'shopLocalizer', $localization_data );
		wp_localize_script( 'shop-explorer-app', 'shopExplorerData', $localization_data );
	}

	/**
	 * Enqueue frontend assets
	 *
	 * @since 1.0.0
	 */
	public function frontend_enqueue() {
		// Only enqueue on frontend dashboard pages
		if ( ! $this->is_frontend_dashboard_page() ) {
			// Check if we should load WooCommerce tracking scripts on other pages
			$this->maybe_enqueue_woo_tracking();
			return;
		}

		// Always load frontend CSS for login page
		wp_enqueue_style(
			'shop-explorer-frontend-css',
			SHOPEX_URL . 'assets/css/frontend.css',
			[],
			SHOPEX_VERSION
		);

		// Check if user is logged in before loading React app
		if ( ! is_user_logged_in() ) {
			return;
		}

		// Note: We load the React app regardless of Quick Actions settings
		// The React app itself can handle showing/hiding features based on settings

		// Enqueue WordPress media scripts
		wp_enqueue_media();

		// Enqueue React app (same as admin)
		$this->enqueue_react_app();

		// Add inline script to verify loading
		wp_add_inline_script( 'shop-explorer-app', 'console.log("Shop Explorer frontend scripts loaded");', 'after' );
	}

	/**
	 * Maybe enqueue WooCommerce tracking scripts
	 *
	 * @since 1.0.0
	 */
	private function maybe_enqueue_woo_tracking() {
		// Check if WooCommerce is active
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		// Get WooCommerce settings
		$woo_settings = get_option( 'wpnts_schedules_interval_woocommerce_settings', [] );
		if ( is_string( $woo_settings ) ) {
			$woo_settings = json_decode( $woo_settings, true );
		}

		// Check if analytics is enabled
		$analytics_enabled = isset( $woo_settings['wooanalytics'] ) && $woo_settings['wooanalytics'];
		$incomplete_orders_enabled = isset( $woo_settings['incomplete_orders_tracking'] ) && $woo_settings['incomplete_orders_tracking'];
		$cart_interactions_enabled = isset( $woo_settings['cart_interactions_tracking'] ) && $woo_settings['cart_interactions_tracking'];

		// Only load on WooCommerce pages if tracking is enabled
		if ( ! $analytics_enabled && ! $incomplete_orders_enabled && ! $cart_interactions_enabled ) {
			return;
		}

		// Check if we're on a WooCommerce page
		if ( ! $this->is_woocommerce_page() ) {
			return;
		}

		// Enqueue jQuery if not already loaded
		wp_enqueue_script( 'jquery' );

		// Enqueue cart session tracker
		if ( $analytics_enabled || $cart_interactions_enabled ) {
			wp_enqueue_script(
				'wpnts-cart-session-tracker',
				SHOPEX_URL . 'assets/js/wpnts-cart-session-tracker.js',
				[ 'jquery' ],
				SHOPEX_VERSION,
				true
			);

			wp_localize_script( 'wpnts-cart-session-tracker', 'wpnts_cart_session_ajax', [
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'wpnts_checkout_tracking' ),
			]);
		}

		// Enqueue checkout tracking scripts
		if ( $incomplete_orders_enabled ) {
			// Basic checkout tracking
			wp_enqueue_script(
				'wpnts-checkout-tracking',
				SHOPEX_URL . 'assets/js/wpnts-checkout-tracking.js',
				[ 'jquery' ],
				SHOPEX_VERSION,
				true
			);

			// Enhanced checkout tracking
			wp_enqueue_script(
				'wpnts-enhanced-checkout-tracking',
				SHOPEX_URL . 'assets/js/wpnts-enhanced-checkout-tracking.js',
				[ 'jquery', 'wpnts-checkout-tracking' ],
				SHOPEX_VERSION,
				true
			);

			// Localize checkout tracking scripts
			wp_localize_script( 'wpnts-checkout-tracking', 'wpnts_checkout_ajax', [
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'wpnts_checkout_tracking' ),
			]);

			wp_localize_script( 'wpnts-enhanced-checkout-tracking', 'wpnts_checkout_ajax', [
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce' => wp_create_nonce( 'wpnts_checkout_tracking' ),
			]);
		}
	}

	/**
	 * Check if current page is a WooCommerce page
	 *
	 * @return bool
	 */
	private function is_woocommerce_page() {
		// Check if it's a WooCommerce page
		if ( function_exists( 'is_woocommerce' ) && is_woocommerce() ) {
			return true;
		}

		// Check specific WooCommerce pages
		if ( is_shop() || is_product_category() || is_product_tag() || is_product() ) {
			return true;
		}

		// Check cart and checkout pages
		if ( function_exists( 'is_cart' ) && is_cart() ) {
			return true;
		}

		if ( function_exists( 'is_checkout' ) && is_checkout() ) {
			return true;
		}

		// Check account pages
		if ( function_exists( 'is_account_page' ) && is_account_page() ) {
			return true;
		}

		// Check by body class
		global $post;
		if ( $post ) {
			$post_classes = get_post_class( '', $post->ID );
			$woo_classes = [ 'woocommerce', 'woocommerce-page', 'woocommerce-cart', 'woocommerce-checkout' ];
			
			if ( array_intersect( $woo_classes, $post_classes ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Get current user data for React app
	 *
	 * @return array
	 */
	private function get_current_user_data() {
		$current_user = wp_get_current_user();

		return [
			'id' => $current_user->ID,
			'name' => $current_user->display_name,
			'email' => $current_user->user_email,
			'roles' => $current_user->roles,
			'capabilities' => [
				'manage_woocommerce' => current_user_can( 'manage_woocommerce' ),
				'manage_options' => current_user_can( 'manage_options' ),
				'edit_shop_orders' => current_user_can( 'edit_shop_orders' ),
				'edit_products' => current_user_can( 'edit_products' ),
			],
		];
	}

	/**
	 * Get plugin settings for React app
	 *
	 * @return array
	 */
	private function get_plugin_settings() {
		// Get configuration manager instance
		$config_manager = null;
		if ( class_exists( 'SHOPEXPLORER\\Core\\SHOPEX_ShopExplorer' ) ) {
			$shop_explorer = \SHOPEXPLORER\Core\SHOPEX_ShopExplorer::get_instance();
			$config_manager = $shop_explorer->get_config_manager();
		}

		if ( ! $config_manager ) {
			return [];
		}

		return [
			'modes' => $config_manager->get_mode_settings(),
			'syncPreferences' => $config_manager->get_sync_preferences(),
			'isDualMode' => $config_manager->is_dual_mode_enabled(),
		];
	}

	/**
	 * Get localized strings for React app
	 *
	 * @return array
	 */
	private function get_localized_strings() {
		return [
			'dashboard' => __( 'Dashboard', 'shop-explorer' ),
			'orders' => __( 'Orders', 'shop-explorer' ),
			'products' => __( 'Products', 'shop-explorer' ),
			'vendors' => __( 'Vendors', 'shop-explorer' ),
			'settings' => __( 'Settings', 'shop-explorer' ),
			'loading' => __( 'Loading...', 'shop-explorer' ),
			'error' => __( 'Error', 'shop-explorer' ),
			'success' => __( 'Success', 'shop-explorer' ),
			'save' => __( 'Save', 'shop-explorer' ),
			'cancel' => __( 'Cancel', 'shop-explorer' ),
			'delete' => __( 'Delete', 'shop-explorer' ),
			'edit' => __( 'Edit', 'shop-explorer' ),
			'view' => __( 'View', 'shop-explorer' ),
		];
	}

	/**
	 * Get notice settings for React app
	 *
	 * @return array
	 */
	private function get_notice_settings() {
		// Get WooCommerce settings
		$woo_settings = get_option( 'wpnts_schedules_interval_woocommerce_settings', [] );
		if ( is_string( $woo_settings ) ) {
			$woo_settings = json_decode( $woo_settings, true );
		}
		if ( ! is_array( $woo_settings ) ) {
			$woo_settings = [];
		}

		return [
			'wpnts_schedules_interval_woocommerce_settings' => $woo_settings
		];
	}

	/**
	 * Check if current page is frontend dashboard
	 *
	 * @return bool
	 */
	private function is_frontend_dashboard_page() {
		global $post;

		// Check if we're on the shop-explorer-dashboard page
		if ( is_page( 'shop-explorer-dashboard' ) ) {
			return true;
		}

		// Check by page template
		if ( $post ) {
			$page_template = get_page_template_slug( $post->ID );
			if ( $page_template === 'shop-explorer-dashboard' ||
				 $page_template === 'shop-explorer-frontend-dashboard' ||
				 $page_template === 'templates/shop-explorer-dashboard.php' ) {
				return true;
			}
		}

		// Check by page ID stored in options
		$dashboard_page_id = get_option( 'shop_explorer_dashboard_page_id' );
		if ( $dashboard_page_id && is_page( $dashboard_page_id ) ) {
			return true;
		}

		return false;
	}

	/**
	 * Get frontend settings for React app
	 *
	 * @return array
	 */
	private function get_frontend_settings() {
		$settings = get_option( 'shop_explorer_frontend_settings', [] );

		return [
			'orders_management' => isset( $settings['orders_management'] ) ? $settings['orders_management'] : [
				'enabled' => false,
				'default_statuses' => [],
				'custom_statuses' => [],
				'filter_settings' => [],
				'filter_sections' => [],
			],
			'products_management' => isset( $settings['products_management'] ) ? $settings['products_management'] : [
				'enabled' => false,
			],
		];
	}
}
