<?php
/**
 * Enqueue scripts and styles.
 *
 * @package automation-web-platform
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Class WAWP_Enqueue_Scripts
 * Handles enqueuing of scripts and styles.
 */
class WAWP_Enqueue_Scripts {

	/**
	 * Enqueue admin styles and scripts.
	 */
	public static function enqueue_admin_styles_scripts() {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		$page_param   = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS ) ? filter_input( INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS ) : '';
		$is_wawp_page = strpos( $screen->id, 'wawp' ) !== false || ( $page_param && strpos( $page_param, 'wc-abandoned-cart' ) !== false );

		$section_raw = filter_input( INPUT_GET, 'wawp_section', FILTER_SANITIZE_SPECIAL_CHARS );
		$section     = $section_raw ? sanitize_key( $section_raw ) : 'dashboard';

		if ( $is_wawp_page ) {
			if ( in_array( $section, array( 'dashboard', 'senders', 'activity_hub', 'system_info', 'account', 'notifications', 'email_templates', 'campaigns', 'campaigns_new', 'chat_widget', 'country-code', 'google_recaptcha', 'authentication-pages', 'otp_messages', 'checkout-verification', 'registration-form', 'passwordless-login', 'abandoned_carts_settings', 'abandoned_carts', 'whatsapp-web-sender', 'meta-api-sender', 'firebase-sender', 'smtp-sender', 'block-manager', 'orders-status', 'setup_wizard' ), true ) ) {
				// List core WP dependencies.
				$dependencies = array( 'jquery', 'wp-polyfill', 'wp-element', 'wp-i18n', 'wp-api-fetch', 'wp-hooks', 'wp-data', 'wp-util', 'wp-api', 'wp-components', 'wp-url', 'underscore', 'backbone' );

				// Dequeue WP Auth Check to prevent "hasClass of undefined" errors in SPA context.
				wp_dequeue_script( 'wp-auth-check' );
				wp_dequeue_script( 'heartbeat' );

				wp_enqueue_style( 'wawp-local-fonts', WAWP_PLUGIN_URL . 'assets/css/wawp-fonts.css', array(), '1.0.0' );

				// Load React Application.
				// Find the hashed index file (e.g. index-AbCdEf.js) generated by Vite.
				$dist_assets_dir = WAWP_PLUGIN_DIR . 'app/dist/assets/';
				$index_js_file   = self::find_hashed_asset( $dist_assets_dir, 'index', 'js' );
				$index_css_file  = self::find_hashed_asset( $dist_assets_dir, 'index', 'css' );

				$index_js_path  = $dist_assets_dir . $index_js_file;
				$index_css_path = $dist_assets_dir . $index_css_file;

				// Use filemtime as version — the hashed filename already ensures cache busting,
				// so we don't need wawp_force_cache_bust_version for the entry file anymore.
				$js_ver  = file_exists( $index_js_path ) ? filemtime( $index_js_path ) : WAWP_PLUGIN_VERSION;
				$css_ver = file_exists( $index_css_path ) ? filemtime( $index_css_path ) : WAWP_PLUGIN_VERSION;

				wp_enqueue_media();
				wp_enqueue_script( 'wawp-react-dashboard', WAWP_PLUGIN_URL . 'app/dist/assets/' . $index_js_file, $dependencies, $js_ver, true );
				wp_enqueue_style( 'wawp-react-dashboard-css', WAWP_PLUGIN_URL . 'app/dist/assets/' . $index_css_file, array(), $css_ver );
				wp_enqueue_style( 'wawp-remix-icon', WAWP_PLUGIN_URL . 'assets/css/resources/remixicon.css', array(), '4.6.0' );
				wp_enqueue_style( 'wawp-chat-widget-style', WAWP_PLUGIN_URL . 'assets/css/style.css', array(), WAWP_PLUGIN_VERSION );

				add_filter(
					'script_loader_tag',
					function ( $tag, $handle ) {
						if ( 'wawp-react-dashboard' === $handle ) {
							return str_replace( '<script ', '<script type="module" ', $tag );
						}
						return $tag;
					},
					10,
					2
				);

				if ( function_exists( 'wp_set_script_translations' ) ) {
					wp_set_script_translations( 'wawp-react-dashboard', 'automation-web-platform', WAWP_PLUGIN_DIR . 'languages' );
				}

				self::localize_react_dashboard_data( $section );
			}
		}

		// 3. Order Edit & List Actions
		$is_hpos_list   = ( 'woocommerce_page_wc-orders' === $screen->id && ! filter_input( INPUT_GET, 'action' ) );
		$is_legacy_list = ( 'edit-shop_order' === $screen->id );
		$is_order_edit  = ( 'post.php' === $screen->base && 'shop_order' === $screen->post_type );
		$is_hpos_edit   = ( 'woocommerce_page_wc-orders' === $screen->id && filter_input( INPUT_GET, 'action' ) === 'edit' );

		if ( $is_order_edit || $is_hpos_edit || $is_hpos_list || $is_legacy_list ) {
			wp_enqueue_style( 'wawp-order-actions', WAWP_PLUGIN_URL . 'assets/css/admin/wawp-order-actions.css', array(), WAWP_PLUGIN_VERSION );
			wp_enqueue_script( 'wawp-order-actions', WAWP_PLUGIN_URL . 'assets/js/admin/wawp-order-actions.js', array( 'jquery' ), WAWP_PLUGIN_VERSION . '.' . time(), true );
			wp_localize_script(
				'wawp-order-actions',
				'wawp_order_actions',
				array(
					'ajax_url' => admin_url( 'admin-ajax.php' ),
					'nonce'    => wp_create_nonce( 'wawp_order_actions_nonce' ),
					'sending'  => esc_html__( 'Sending...', 'automation-web-platform' ),
					/* translators: %s: details location */
					'success'  => sprintf(
						/* translators: %s: details location */
						esc_html__( 'Notification sent successfully! Check %s for details.', 'automation-web-platform' ),
						'<a href="' . esc_url( admin_url( 'admin.php?page=wawp&wawp_section=activity_hub' ) ) . '">' . esc_html__( 'Activity Hub', 'automation-web-platform' ) . '</a>'
					),
					'error'    => esc_html__( 'Failed to send notification. Please try again.', 'automation-web-platform' ),
				)
			);
		}

		// 3b. Orders List Table (not edit).
		$is_hpos_list   = ( 'woocommerce_page_wc-orders' === $screen->id && ! filter_input( INPUT_GET, 'action' ) );
		$is_legacy_list = ( 'edit-shop_order' === $screen->id );

		if ( $is_hpos_list || $is_legacy_list ) {
			wp_enqueue_style( 'wawp-remix-icon', WAWP_PLUGIN_URL . 'assets/css/resources/remixicon.css', array(), '4.6.0' );
			wp_enqueue_style( 'wawp-orders-list', WAWP_PLUGIN_URL . 'assets/css/admin/wawp-orders-list.css', array(), WAWP_PLUGIN_VERSION );
			wp_enqueue_script( 'wawp-orders-list', WAWP_PLUGIN_URL . 'assets/js/admin/wawp-orders-list.js', array( 'jquery' ), WAWP_PLUGIN_VERSION, true );
			wp_localize_script(
				'wawp-orders-list',
				'wawp_orders_list',
				array(
					'ajax_url' => admin_url( 'admin-ajax.php' ),
					'nonce'    => wp_create_nonce( 'wawp_orders_list_nonce' ),
					'sending'  => esc_html__( 'Sending...', 'automation-web-platform' ),
					'sent'     => esc_html__( 'Sent!', 'automation-web-platform' ),
					'error'    => esc_html__( 'Failed to send.', 'automation-web-platform' ),
				)
			);
		}

		// 4. Custom Messages (Users/Profile)
		if ( in_array( $screen->base, array( 'users', 'profile', 'user-edit' ), true ) ) {
			wp_enqueue_style( 'wawp-badges', WAWP_PLUGIN_URL . 'assets/css/wawp-badges.css', array(), WAWP_PLUGIN_VERSION );

			if ( WAWP_Connector()->is_whatsapp_active() ) {
				wp_enqueue_script( 'wawp-send-msg', WAWP_PLUGIN_URL . 'assets/js/wawp-send-msg.js', array( 'jquery' ), WAWP_PLUGIN_VERSION, true );

				$online_instances = WAWP()->instance_manager->get_online_instances_cached();
				$online           = array();
				if ( $online_instances ) {
					foreach ( $online_instances as $inst ) {
						$online[] = array(
							'instance_id' => $inst->instance_id,
							'name'        => $inst->name,
						);
					}
				}

				wp_localize_script(
					'wawp-send-msg',
					'wawpSendMsgData',
					array(
						'ajaxUrl'          => admin_url( 'admin-ajax.php' ),
						'security'         => wp_create_nonce( 'wawp_send_msg_nonce' ),
						'onlineInstances'  => $online,
						'noOnlineInstance' => esc_html__( 'No online instances found.', 'automation-web-platform' ),
					)
				);
			}
		}

		// 5. Deactivation Survey
		if ( 'plugins' === $screen->base ) {
			$plugin_file   = plugin_basename( WAWP_PLUGIN_FILE );
			$deact_pattern = 'plugin=' . rawurlencode( $plugin_file );

			wp_enqueue_style( 'wawp-deactivation-survey', WAWP_PLUGIN_URL . 'assets/css/admin/wawp-deactivation-survey.css', array(), WAWP_PLUGIN_VERSION );
			wp_enqueue_script( 'wawp-deactivation-survey', WAWP_PLUGIN_URL . 'assets/js/admin/wawp-deactivation-survey.js', array( 'jquery' ), WAWP_PLUGIN_VERSION, true );
			wp_localize_script(
				'wawp-deactivation-survey',
				'wawpDeactData',
				array(
					'deactPattern' => $deact_pattern,
					'nonce'        => wp_create_nonce( 'wawp_deact_survey' ),
					'title'        => esc_html__( 'Quick feedback before deactivating Wawp?', 'automation-web-platform' ),
					'desc'         => esc_html__( 'Choose a reason (optional) — it really helps us improve.', 'automation-web-platform' ),
					'opt_test'     => esc_html__( 'I am just testing / temporary', 'automation-web-platform' ),
					'opt_bug'      => esc_html__( 'Found a bug / not working', 'automation-web-platform' ),
					'opt_feature'  => esc_html__( 'Missing a feature I need', 'automation-web-platform' ),
					'opt_complex'  => esc_html__( 'Too complex / hard to use', 'automation-web-platform' ),
					'opt_switch'   => esc_html__( 'Switched to another plugin', 'automation-web-platform' ),
					'opt_other'    => esc_html__( 'Other', 'automation-web-platform' ),
					'placeholder'  => esc_html__( 'Type your reason...', 'automation-web-platform' ),
					'btn_cancel'   => esc_html__( 'Cancel', 'automation-web-platform' ),
					'btn_skip'     => esc_html__( 'Deactivate without feedback', 'automation-web-platform' ),
					'btn_submit'   => esc_html__( 'Submit & Deactivate', 'automation-web-platform' ),
				)
			);
		}
	}

	/**
	 * Cleanup admin styles and scripts.
	 */
	public static function enqueue_admin_styles_scripts_cleanup() {
		$screen = get_current_screen();
		if ( ! $screen ) {
			return;
		}

		$page_param   = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS ) ? filter_input( INPUT_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS ) : '';
		$is_wawp_page = strpos( $screen->id, 'wawp' ) !== false || ( $page_param && strpos( $page_param, 'wc-abandoned-cart' ) !== false );

		if ( ! $is_wawp_page ) {
			return;
		}
	}

	/**
	 * Enqueue frontend styles and scripts.
	 */
	public static function enqueue_frontend_styles_scripts() {
		$is_custom_pages_enabled      = WAWP()->get_wawp_setting( WAWP_Settings_Registry::CUSTOM_PAGES_ENABLED, 1 );
		$is_replace_wc_forms          = WAWP()->get_wawp_setting( WAWP_Settings_Registry::REPLACE_WC_FORMS );
		$is_replace_wc_checkout_login = WAWP()->get_wawp_setting( WAWP_Settings_Registry::REPLACE_WC_CHECKOUT_LOGIN );

		if ( $is_custom_pages_enabled && ! is_admin() ) {
			$enqueue_overrides = false;

			if ( $is_replace_wc_forms && function_exists( 'is_account_page' ) && is_account_page() ) {
				$enqueue_overrides = true;
			}

			if ( $is_replace_wc_checkout_login && function_exists( 'is_checkout' ) && is_checkout() ) {
				$enqueue_overrides = true;
			}

			if ( $enqueue_overrides ) {
				wp_enqueue_style( 'wawp-frontend-overrides', WAWP_PLUGIN_URL . 'assets/css/wawp-frontend-overrides.css', array(), WAWP_PLUGIN_VERSION );
			}
		}

		// Central Data Hub for all frontend localized variables.
		$global_vars = apply_filters( 'wawp_frontend_global_vars', array() );
		if ( ! empty( $global_vars ) ) {
			$inline_script = '';
			foreach ( $global_vars as $var_name => $data ) {
				$inline_script .= 'var ' . esc_js( $var_name ) . ' = ' . wp_json_encode( $data ) . ";\n";
			}
			wp_register_script( 'wawp-global-data-hub', false, array(), WAWP_PLUGIN_VERSION, true );
			wp_enqueue_script( 'wawp-global-data-hub' );
			wp_add_inline_script( 'wawp-global-data-hub', $inline_script );
		}
	}

	/**
	 * Localize React dashboard data.
	 *
	 * @param string $section Current section.
	 */
	public static function localize_react_dashboard_data( $section ) {
		$user_id   = get_current_user_id();
		$locale    = get_user_locale();
		$cache_key = 'wawp_dashboard_data_full_' . $user_id . '_' . $locale;

		if ( filter_input( INPUT_GET, 'force_refresh' ) ) {
			delete_transient( $cache_key );
			wp_cache_delete( $cache_key, 'wawp_database' );
			delete_transient( 'wawp_latest_plugin_version' );
		}

		$data = wp_cache_get( $cache_key, 'wawp_database' );

		if ( false === $data ) {
			$data = get_transient( $cache_key );
			if ( false === $data ) {
				$data = self::prepare_dashboard_data( $section, true );
				set_transient( $cache_key, $data, 60 ); // Short transient for live data.

				// Track keys for mass clearing without direct SQL.
				$keys = get_option( 'wawp_dashboard_transient_keys', array() );
				if ( ! is_array( $keys ) ) {
					$keys = array();
				}
				if ( ! in_array( $cache_key, $keys, true ) ) {
					$keys[] = $cache_key;
					update_option( 'wawp_dashboard_transient_keys', $keys, false );
				}
			}
			wp_cache_set( $cache_key, $data, 'wawp_database', 60 );
		}

		// Dynamically override the active section for the SPA to know where we landed.
		// Also override popupStep from the live URL — cache always stores 0, so we must re-read it here.
		if ( isset( $data['global'] ) ) {
			$data['global']['section']   = $section;
			$data['global']['popupStep'] = (int) filter_input( INPUT_GET, 'wawp_popup_step', FILTER_SANITIZE_NUMBER_INT );
		}

		wp_localize_script( 'wawp-react-dashboard', 'wawpDashboardData', $data );
	}

	/**
	 * Prepare data for the dashboard.
	 *
	 * @param string $section Current section.
	 * @param bool   $is_full Whether to return full data.
	 * @return array Dashboard data.
	 */
	public static function prepare_dashboard_data( $section, $is_full = false ) {
		try {
			// Dynamic Translation Reloader for user locale (to support REST API requests loaded under user locale).
			if ( function_exists( 'get_user_locale' ) ) {
				$user_locale = get_user_locale();
				if ( $user_locale && get_locale() !== $user_locale ) {
					$mofile = WAWP_PLUGIN_DIR . 'languages/automation-web-platform-' . $user_locale . '.mo';
					if ( file_exists( $mofile ) ) {
						load_textdomain( 'automation-web-platform', $mofile );
					} else {
						$parts = explode( '_', $user_locale );
						if ( count( $parts ) > 1 ) {
							$fallback_mofile = WAWP_PLUGIN_DIR . 'languages/automation-web-platform-' . $parts[0] . '.mo';
							if ( file_exists( $fallback_mofile ) ) {
								load_textdomain( 'automation-web-platform', $fallback_mofile );
							}
						}
					}
				}
			}

			if ( ! function_exists( 'is_plugin_active' ) ) {
				require_once ABSPATH . 'wp-admin/includes/plugin.php';
			}

			$user_data    = wawp_get_user_data();
			$connector    = WAWP_Connector();
			$is_connected = $connector->is_connected();
			$is_free_user = ! empty( $user_data['is_free_user'] );
			$is_sso       = ( ! empty( $connector->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN ) ) && ! empty( $user_data ) && isset( $user_data['user_email'] ) );
			$icons_url    = WAWP_PLUGIN_URL . 'assets/icons/';

			// Determine domain status robustly, distinguishing overload, blocked, and active/not connected states.
			$token = $connector->get_wawp_setting( WAWP_Settings_Registry::ACCESS_TOKEN );
			if ( empty( $token ) ) {
				$token = $connector->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
			}
			$banned        = get_transient( 'wawp_site_b_banned_msg' );
			$not_logged_in = get_transient( 'wawp_site_b_not_logged_in_msg' );

			if ( ! $token || $not_logged_in ) {
				$domain_status = 'not connected';
			} elseif ( $banned ) {
				$domain_status = 'blocked';
			} else {
				$current_domain = $connector->get_site_domain();
				$sites          = isset( $user_data['sites'] ) && is_array( $user_data['sites'] ) ? $user_data['sites'] : array();
				$domain_status  = isset( $sites[ $current_domain ] ) ? $sites[ $current_domain ] : 'active';
				if ( empty( $domain_status ) ) {
					$domain_status = 'active';
				}
			}

			// Sidebar logic.
			$issues_count = 0;
			if ( WAWP()->system_info ) {
				$issues_count = WAWP()->system_info->get_cached_issue_count();
			}

			$plan_text = esc_html__( 'Free', 'automation-web-platform' );
			$is_pro    = false;
			if ( ! empty( $user_data['is_lifetime'] ) ) {
				$is_pro    = true;
				$plan_text = ! empty( $user_data['plan_name'] ) ? str_ireplace( 'Lifetime', '', $user_data['plan_name'] ) : esc_html__( 'Pro', 'automation-web-platform' );
			} elseif ( ! empty( $user_data['subscriptions'] ) && is_array( $user_data['subscriptions'] ) ) {
				foreach ( $user_data['subscriptions'] as $sub ) {
					if ( ! empty( $sub['status'] ) && 'active' === $sub['status'] ) {
						$is_pro    = true;
						$plan_text = ! empty( $user_data['plan_name'] ) ? str_ireplace( 'Lifetime', '', $user_data['plan_name'] ) : esc_html__( 'Pro', 'automation-web-platform' );
						break;
					}
				}
			}

			// Notices.
			$notices = array();
			if ( class_exists( 'WAWP_Admin_Notices' ) ) {
				if ( method_exists( 'WAWP_Admin_Notices', 'is_wa_offline' ) && WAWP_Admin_Notices::is_wa_offline() ) {
					$notices[] = array(
						'type' => 'offline',
						'url'  => admin_url( 'admin.php?page=wawp&wawp_section=whatsapp-web-sender' ),
					);
				}
			}

			$country_options = WAWP()->get_wawp_setting( 'woo_intl_tel_options', array() );
			$default_country = ! empty( $country_options['default_country_code'] ) ? strtoupper( $country_options['default_country_code'] ) : 'US';

			// Detect if any caching plugin is active.
			$cache_plugins        = array(
				'wp-rocket/wp-rocket.php'             => 'WP Rocket',
				'litespeed-cache/litespeed-cache.php' => 'LiteSpeed Cache',
				'w3-total-cache/w3-total-cache.php'   => 'W3 Total Cache',
				'wp-super-cache/wp-cache.php'         => 'WP Super Cache',
				'wp-fastest-cache/wpFastestCache.php' => 'WP Fastest Cache',
				'sg-cachepress/sg-cachepress.php'     => 'SG Optimizer',
				'breeze/breeze.php'                   => 'Breeze',
				'autoptimize/autoptimize.php'         => 'Autoptimize',
				'cache-enabler/cache-enabler.php'     => 'Cache Enabler',
				'wp-hummingbird/wp-hummingbird.php'   => 'Hummingbird',
				'hummingbird-performance/wp-hummingbird.php' => 'Hummingbird',
				'swift-performance-lite/swift-performance-lite.php' => 'Swift Performance',
				'flying-press/flying-press.php'       => 'FlyingPress',
				'nitropack/nitropack.php'             => 'NitroPack',
			);
			$active_cache_plugins = array();
			foreach ( $cache_plugins as $plugin_path => $plugin_name ) {
				if ( is_plugin_active( $plugin_path ) ) {
					$active_cache_plugins[] = $plugin_name;
				}
			}
			$has_active_cache = ! empty( $active_cache_plugins );

			// 1. Base Global Data (Always present)
			$data = array(
				'notices'      => $notices,
				'global'       => array(
					'wpRestNonce'         => wp_create_nonce( 'wp_rest' ),
					'apiRestUrl'          => get_rest_url( null, 'wawp/v1' ),
					'restUrl'             => get_rest_url( null, 'wawp/v1' ),
					'settingsRestUrl'     => get_rest_url( null, 'wawp/v1/settings' ),
					'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
					'nonce'               => wp_create_nonce( 'wawp_nonce' ),
					'isRtl'               => is_rtl() || ( function_exists( 'get_user_locale' ) && 'ar' === substr( get_user_locale(), 0, 2 ) ),
					'version'             => WAWP_PLUGIN_VERSION,
					'pluginUrl'           => WAWP_PLUGIN_URL,
					'popupStep'           => (int) filter_input( INPUT_GET, 'wawp_popup_step', FILTER_SANITIZE_NUMBER_INT ),
					'section'             => $section,
					'country'             => $default_country,
					'isFreeUser'          => $is_free_user,
					'domainStatus'        => $domain_status,
					'adminEmail'          => wp_get_current_user()->user_email,
					'currentLocale'       => get_locale(),
					'currentUserLocale'   => get_user_locale(),
					'availableLanguages'  => self::get_site_available_languages(),
					'languageSwitchNonce' => wp_create_nonce( 'wawp_switch_language' ),
					'flushCacheNonce'     => wp_create_nonce( 'wawp_flush_cache' ),
					'updaterStatus'       => self::get_updater_status(),
					'latestVersion'       => self::get_latest_version_from_transient(),
					'hasActiveCache'      => $has_active_cache,
					'activeCachePlugins'  => $active_cache_plugins,
				),
				'nonce'        => wp_create_nonce( 'wawp_nonce' ),
				'isFreeUser'   => $is_free_user,
				'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
				'domainStatus' => $domain_status,
				'rtl'          => is_rtl() || ( function_exists( 'get_user_locale' ) && 'ar' === substr( get_user_locale(), 0, 2 ) ),
				'i18n'         => array(),
			);

			// 2. Full Sidebar and Stats (If full load or dashboard)
			if ( $is_full || 'dashboard' === $section ) {
				$dashboard              = WAWP_Dashboard::get_instance();
				$dashboard_data         = $dashboard->get_dashboard_data();
				$data['sidebarData']    = array(
					'isConnected'       => $is_sso,
					'userEmail'         => $is_sso ? $user_data['user_email'] : '',
					'userAvatar'        => ( $is_sso && ! empty( $user_data['avatar'] ) ) ? $user_data['avatar'] : '',
					'planName'          => $is_pro ? $plan_text : esc_html__( 'Free', 'automation-web-platform' ),
					'isPro'             => $is_pro,
					'issuesCount'       => $issues_count,
					'loginUrl'          => admin_url( 'admin.php?page=wawp&wawp_section=account&wawp_popup_step=1' ),
					'disconnectUrl'     => wp_nonce_url( admin_url( 'admin-post.php?action=wawp_disconnect_sso' ), 'wawp_disconnect_sso' ),
					'enabledSections'   => $dashboard_data['features'] ?? array(),
					'enabledSenders'    => array(
						'email'    => $connector->is_email_sender_enabled(),
						'wa'       => $connector->is_whatsapp_sender_enabled(),
						'meta'     => $connector->is_meta_sender_enabled(),
						'firebase' => $connector->is_firebase_sender_enabled(),
						'block'    => $connector->is_block_manager_active(),
					),
					'allowedSenders'    => array(
						'email'    => true,
						'wa'       => true,
						'block'    => true,
						'meta'     => wawp_is_feature_allowed( 'meta_api_sender', $user_data ),
						'firebase' => wawp_is_feature_allowed( 'firebase_sms', $user_data ),
					),
					'isProPluginActive' => $is_pro,
				);
				$data['i18n']           = $dashboard_data['i18n'] ?? array();
				$data['urls']           = $dashboard_data['urls'] ?? array();
				$data['features']       = $dashboard_data['features'] ?? array();
				$data['isGuest']        = $dashboard_data['isGuest'] ?? false;
				$data['stats']          = $dashboard_data['stats'] ?? array();
				$data['wooStatus']      = $dashboard_data['wooStatus'] ?? array();
				$data['whatsappLimits'] = array(
					'limit'           => 100,
					'subscriptionUrl' => ( ! empty( $user_data['is_lifetime'] ) || $is_connected ) ? 'https://wawp.net/account/subscription' : 'https://wawp.net/',
				);
				$data['icons']          = array(
					'baseUrl'    => $icons_url,
					'successGif' => WAWP_PLUGIN_URL . 'assets/img/success.gif',
					'errorGif'   => WAWP_PLUGIN_URL . 'assets/img/error.gif',
				);
			}

			// 3. Section Specific Data (Always include if mapped)
			$mapped_section = $section;
			if ( 'activity_hub' === $section ) {
				$mapped_section = 'activity-hub';
			} elseif ( 'email_templates' === $section ) {
				$mapped_section = 'email-templates';
			} elseif ( 'abandoned_carts_settings' === $section ) {
				$mapped_section = 'abandoned_carts_settings';
			} elseif ( 'campaigns_new' === $section ) {
				$mapped_section = 'campaigns';
			} elseif ( 'otp_messages' === $section ) {
				$mapped_section = 'passwordless-login';
			}

			// 3. Section Specific Data Dispatch (Registry Pattern - Point 4)
			$handlers = array(
				'account'                  => array( 'WAWP_Connector', 'get_instance' ),
				'senders'                  => array( 'WAWP_Senders', 'get_instance' ),
				'whatsapp-web-sender'      => array( 'WAWP_Senders', 'get_instance' ),
				'registration-form'        => array( 'WAWP_Signup', 'get_instance' ),
				'checkout-verification'    => array( 'WAWP_Checkout_Otp', 'get_instance' ),
				'passwordless-login'       => array( 'WAWP_Otp_Login', 'get_instance' ),
				'system_info'              => array( 'WAWP_System_Info', 'get_instance' ),
				'notifications'            => array( 'WAWP_Flow_Builder', 'get_instance' ),
				'activity-hub'             => array( 'WAWP_Unified_Log', 'get_instance' ),
				'google_recaptcha'         => array( 'WAWP_Google_Recaptcha', 'get_instance' ),
				'chat_widget'              => array( 'WAWP_Chat_Widget', 'get_instance' ),
				'abandoned_carts_settings' => array( 'WAWP_Abandoned_Carts', 'get_instance' ),
				'abandoned_carts'          => array( 'WAWP_Abandoned_Carts', 'get_instance' ),
				'meta-api-sender'          => array( 'WAWP_Meta_Sender', 'get_instance' ),
				'firebase-sender'          => array( 'WAWP_Firebase_Sender', 'get_instance' ),
				'smtp-sender'              => array( 'WAWP_Email_Sender', 'get_instance' ),
				'block-manager'            => array( 'WAWP_Block_Manager', 'get_instance' ),
				'email-templates'          => array( 'WAWP_Email_Templates', 'get_instance' ),
				'campaigns'                => array( 'WAWP_Campaigns_Advanced', 'get_instance' ),
				'authentication-pages'     => array( 'WAWP_Custom_Pages_Settings', 'get_instance' ),
				'country-code'             => array( 'WAWP_CountryCode', 'get_instance' ),
				'orders-status'            => array( 'WAWP_Orders_Status_Settings', 'get_instance' ),
			);

			// Key Mapping for the localized object.
			$key_map = array(
				'account'                  => 'connector',
				'senders'                  => 'sendersData',
				'whatsapp-web-sender'      => 'instancesData',
				'registration-form'        => 'registrationForm',
				'checkout-verification'    => 'checkoutVerificationSettings',
				'passwordless-login'       => 'passwordlessLoginSettings',
				'system_info'              => 'systemInfo',
				'notifications'            => 'notificationsData',
				'activity-hub'             => 'logsData',
				'google_recaptcha'         => 'recaptchaData',
				'chat_widget'              => 'chatWidgetData',
				'abandoned_carts_settings' => 'abandonedCartsSettings',
				'abandoned_carts'          => 'abandonedCartSessions',
				'meta-api-sender'          => 'metaApiSenderData',
				'firebase-sender'          => 'firebaseSenderData',
				'smtp-sender'              => 'smtpSenderData',
				'block-manager'            => 'blockManagerData',
				'email-templates'          => 'emailTemplatesData',
				'campaigns'                => 'campaignsData',
				'authentication-pages'     => 'authPages',
				'country-code'             => 'phoneFieldData',
				'orders-status'            => 'ordersStatusSettings',
			);

			if ( 'setup_wizard' === $section ) {
				$sections_to_load = array( 'account', 'whatsapp-web-sender', 'smtp-sender' );
			} else {
				$sections_to_load = $is_full ? array_keys( $handlers ) : array( $mapped_section );
			}

			foreach ( $sections_to_load as $current_section ) {
				if ( ! isset( $handlers[ $current_section ] ) ) {
					continue;
				}

				$class    = $handlers[ $current_section ][0];
				$instance = null;

				// Point 1: Get existing singleton instance instead of 'new Class()'.
				switch ( $class ) {
					case 'WAWP_Connector':
						$instance = WAWP()->connector;
						break;
					case 'WAWP_Senders':
						$instance = WAWP()->senders;
						break;
					case 'WAWP_System_Info':
						$instance = WAWP()->system_info;
						break;
					case 'WAWP_Flow_Builder':
						$instance = WAWP()->flow_builder;
						break;
					case 'WAWP_Unified_Log':
						$instance = WAWP()->unified_log;
						break;
					case 'WAWP_Chat_Widget':
						$instance = WAWP()->chat_widget;
						break;
					case 'WAWP_Abandoned_Carts':
						$instance = WAWP()->abandoned_carts;
						break;
					case 'WAWP_Block_Manager':
						$instance = WAWP()->block_manager;
						break;
					case 'WAWP_Campaigns_Advanced':
						$instance = WAWP()->campaigns;
						break;
					default:
						if ( method_exists( $class, 'get_instance' ) ) {
							$instance = call_user_func( array( $class, 'get_instance' ) );
						}
						break;
				}

				if ( $instance ) {
					$method = 'get_react_settings_data';
					// Handle special method names for legacy support.
					if ( 'whatsapp-web-sender' === $current_section ) {
						$method = 'get_whatsapp_react_settings_data';
					} elseif ( 'account' === $current_section ) {
						$method = 'get_react_connector_data';
					} elseif ( 'system_info' === $current_section ) {
						$method = 'get_react_system_info_data';
					} elseif ( 'activity-hub' === $current_section ) {
						$method = 'get_hub_data';
					} elseif ( 'abandoned_carts' === $current_section ) {
						$method = 'get_sessions_return';
					} elseif ( 'block-manager' === $current_section ) {
						$method = 'get_data';
					}

					if ( method_exists( $instance, $method ) ) {
						$key          = $key_map[ $current_section ] ?? $current_section;
						$section_data = $instance->$method();
						$data[ $key ] = $section_data;

							// Merge translations if provided.
						// During a full load, section-specific pageTitle/pageSubtitle must NOT
						// overwrite the dashboard's own pageTitle/pageSubtitle that was already set.
						if ( isset( $section_data['i18n'] ) ) {
							$preserved_page_title    = $data['i18n']['pageTitle'] ?? '';
							$preserved_page_subtitle = $data['i18n']['pageSubtitle'] ?? '';
							$data['i18n']            = array_merge( $data['i18n'], $section_data['i18n'] );
							// Restore the dashboard-level page title/subtitle so no section overwrites them.
							if ( '' !== $preserved_page_title ) {
								$data['i18n']['pageTitle'] = $preserved_page_title;
							}
							if ( '' !== $preserved_page_subtitle ) {
								$data['i18n']['pageSubtitle'] = $preserved_page_subtitle;
							}
						}

						// Merge status messages if provided.
						if ( isset( $section_data['status_messages'] ) ) {
							$data['status_messages'] = array_merge( $data['status_messages'] ?? array(), $section_data['status_messages'] );
						}
					}
				}

				// Special additions for specific sections.
				if ( 'whatsapp-web-sender' === $current_section ) {
					// OTP Settings & Status.
					$otp_settings                     = WAWP()->from_db( WAWP()->get_wawp_setting( WAWP_Settings_Registry::OTP_SETTINGS, array() ) );
					$otp_settings['enabled']          = (int) WAWP()->get_wawp_setting( WAWP_Settings_Registry::OTP_ENABLED, 0 );
					$otp_settings['login_enabled']    = (int) WAWP()->get_wawp_setting( WAWP_Settings_Registry::PASSWORDLESS_LOGIN_ENABLED, 0 );
					$otp_settings['signup_enabled']   = (int) WAWP()->get_wawp_setting( WAWP_Settings_Registry::SIGNUP_ENABLED, 0 );
					$otp_settings['checkout_enabled'] = (int) WAWP()->get_wawp_setting( WAWP_Settings_Registry::CHECKOUT_OTP_ENABLED, 0 );
					$data['otp']                      = $otp_settings;

					// Signup Settings.
					$signup_settings            = WAWP()->from_db( WAWP()->get_wawp_setting( WAWP_Settings_Registry::REGISTRATION_FORM_SETTINGS, array() ) );
					$signup_settings['enabled'] = (int) WAWP()->get_wawp_setting( WAWP_Settings_Registry::SIGNUP_ENABLED, 0 );
					$data['signup']             = $signup_settings;

					// Checkout Settings.
					if ( class_exists( 'WAWP_Checkout_Otp' ) ) {
						$checkout_settings            = WAWP_Checkout_Otp::get_instance()->get_settings();
						$checkout_settings['enabled'] = (int) WAWP()->get_wawp_setting( WAWP_Settings_Registry::CHECKOUT_OTP_ENABLED, 0 );
						$data['checkout']             = $checkout_settings;
						$data['checkout_instance']    = $checkout_settings[ WAWP_Settings_Registry::CHECKOUT_SELECTED_INSTANCE ] ?? '';
					}

					// Notifications Settings.
					$notif_settings                                = WAWP()->from_db( WAWP()->get_wawp_setting( WAWP_Settings_Registry::NOTIFICATIONS_RULES, array() ) );
					$notif_settings['enabled']                     = (int) WAWP()->get_wawp_setting( WAWP_Settings_Registry::NOTIFICATIONS_ENABLED, 0 );
					$notif_settings['selected_instance_ids']       = WAWP()->get_wawp_setting( WAWP_Settings_Registry::NOTIF_SELECTED_INSTANCE_IDS, '' );
					$notif_settings['admin_selected_instance_ids'] = WAWP()->get_wawp_setting( WAWP_Settings_Registry::NOTIF_ADMIN_SELECTED_INSTANCE_IDS, '' );
					$data['notif']                                 = $notif_settings;

					$data['general_instance'] = WAWP()->get_wawp_setting( WAWP_Settings_Registry::GENERAL_INSTANCE, '' );
				}

				// Activity Hub: inject Meta templates, placeholders, instances & sender status for the Send Message drawer.
				if ( 'activity-hub' === $current_section ) {
					$data['metaTemplates']     = class_exists( 'WAWP_Meta_Sender' ) ? WAWP_Meta_Sender::get_meta_templates_grouped() : array();
					$data['placeholders']      = ( class_exists( 'WAWP_Flow_Builder' ) && method_exists( 'WAWP_Flow_Builder', 'get_available_placeholders' ) )
						? WAWP_Flow_Builder::get_instance()->get_available_placeholders()
						: array();
					$data['placeholderGroups'] = ( class_exists( 'WAWP_Flow_Builder' ) && method_exists( 'WAWP_Flow_Builder', 'get_grouped_placeholders' ) )
						? WAWP_Flow_Builder::get_instance()->get_grouped_placeholders()
						: array();

					// Online Wawp instances for instance picker.
					$raw_instances          = class_exists( 'WAWP_Instance_Manager' ) ? WAWP()->instance_manager->get_online_instances_cached() : array();
					$online_instances_clean = array();
					if ( ! empty( $raw_instances ) ) {
						foreach ( $raw_instances as $inst ) {
							$online_instances_clean[] = array(
								'instance_id' => is_object( $inst ) ? $inst->instance_id : ( $inst['instance_id'] ?? '' ),
								'name'        => is_object( $inst ) ? $inst->name : ( $inst['name'] ?? '' ),
							);
						}
					}
					$data['onlineInstances'] = $online_instances_clean;

					// Enabled senders for showing active status.
					$connector              = WAWP_Connector();
					$data['enabledSenders'] = array(
						'wa'    => $connector->is_whatsapp_sender_enabled(),
						'meta'  => $connector->is_meta_sender_enabled(),
						'email' => $connector->is_email_sender_enabled(),
					);
				}
			}

			$data = self::decode_translations_recursive( $data );
			return $data;
		} catch ( \Exception $e ) {
			return array(
				'error'   => true,
				'message' => $e->getMessage(),
				'global'  => array( 'section' => $section ),
			);
		}
	}

	/**
	 * Decode HTML entities recursively in translation arrays.
	 *
	 * @param array $data_array Input array.
	 * @return array Decoded array.
	 */
	public static function decode_translations_recursive( $data_array ) {
		if ( ! is_array( $data_array ) ) {
			return $data_array;
		}
		foreach ( $data_array as $key => $value ) {
			if ( 'i18n' === $key || 'status_messages' === $key ) {
				$data_array[ $key ] = self::decode_all_strings_recursive( $value );
			} elseif ( is_array( $value ) ) {
				$data_array[ $key ] = self::decode_translations_recursive( $value );
			}
		}
		return $data_array;
	}

	/**
	 * Decode HTML entities recursively for all string values in an array.
	 *
	 * @param mixed $value Input value.
	 * @return mixed Decoded value.
	 */
	private static function decode_all_strings_recursive( $value ) {
		if ( is_array( $value ) ) {
			foreach ( $value as $k => $v ) {
				$value[ $k ] = self::decode_all_strings_recursive( $v );
			}
		} elseif ( is_string( $value ) ) {
			$value = html_entity_decode( $value, ENT_QUOTES, 'UTF-8' );
		}
		return $value;
	}

	/**
	 * Get metadata templates for Meta API integration.
	 *
	 * @return array List of templates.
	 */
	public static function get_meta_templates() {
		if ( class_exists( 'WAWP_Meta_Sender' ) ) {
			return WAWP_Meta_Sender::get_meta_templates();
		}
		return array();
	}

	/**
	 * Find a Vite-hashed asset file in the dist/assets directory.
	 *
	 * Vite generates filenames like index-AbCdEfGh.js. This method
	 * scans the directory for a file matching the pattern [name]-[hash].[ext]
	 * so PHP doesn't need to hardcode the hash.
	 *
	 * Falls back to [name].[ext] (legacy builds without hash) if not found.
	 *
	 * @param string $dir  Absolute path to the dist/assets directory (with trailing slash).
	 * @param string $name Base name without hash (e.g. 'index').
	 * @param string $ext  File extension without dot (e.g. 'js').
	 * @return string The matched filename (basename only), or fallback.
	 */
	private static function find_hashed_asset( $dir, $name, $ext ) {
		if ( is_dir( $dir ) ) {
			$pattern = $dir . $name . '-*.' . $ext;
			$files   = glob( $pattern );
			if ( ! empty( $files ) ) {
				// Sort by modification time DESC so the newest build wins.
				usort(
					$files,
					function ( $a, $b ) {
						return filemtime( $b ) - filemtime( $a );
					}
				);
				return basename( $files[0] );
			}
		}
		// Fallback: legacy build without hash in filename.
		return $name . '.' . $ext;
	}

	/**
	 * Check if the WAWP core service is active.
	 *
	 * @return bool
	 */
	private static function is_wawp_active() {
		return WAWP_Connector()->is_connected();
	}

	/**
	 * Get a snapshot of dashboard statistics for UI rendering.
	 *
	 * @return array Stats array.
	 */
	private static function get_snapshot_stats() {
		return WAWP_Dashboard::get_snapshot_stats();
	}

	/**
	 * Handle REST API requests for dashboard data fetching.
	 *
	 * @param \WP_REST_Request $request REST request object.
	 * @return \WP_REST_Response REST response.
	 */
	public static function handle_rest_fetch_data( $request ) {
		$section       = $request->get_param( 'section' );
		$data          = self::prepare_dashboard_data( $section, false );
		$data['nonce'] = wp_create_nonce( 'wawp_nonce' );
		return new WP_REST_Response( $data, 200 );
	}

	/**
	 * Get the list of languages available/installed on this WordPress site.
	 * Returns English (default) plus every language whose .mo file is present.
	 *
	 * @return array<string, array{locale: string, name: string, nativeName: string, isRtl: bool}>
	 */
	public static function get_site_available_languages() {
		// WordPress RTL locales (partial list covering the most common ones).
		$rtl_locales = array( 'ar', 'ar_EG', 'ar_MA', 'ar_SA', 'fa_IR', 'he_IL', 'ug', 'ps', 'sd_PK', 'ku_IQ', 'ckb' );

		$languages = array();

		// Always include English as the default fallback.
		$languages['en_US'] = array(
			'locale'     => 'en_US',
			'name'       => 'English (US)',
			'nativeName' => 'English',
			'isRtl'      => false,
		);

		// get_available_languages() returns locale slugs that have a .mo file installed.
		if ( function_exists( 'get_available_languages' ) ) {
			$installed = get_available_languages( WP_LANG_DIR );

			// Load the WordPress translation installation API if not already loaded.
			if ( ! function_exists( 'wp_get_available_translations' ) && file_exists( ABSPATH . 'wp-admin/includes/translation-install.php' ) ) {
				require_once ABSPATH . 'wp-admin/includes/translation-install.php';
			}

			// Try to enrich with native names from the translations API cache.
			$translations = array();
			if ( function_exists( 'wp_get_available_translations' ) ) {
				$translations = wp_get_available_translations();
			}

			// Standard common locales fallback.
			$common_locales = array(
				'ar'    => array(
					'name'       => 'Arabic',
					'nativeName' => 'العربية',
				),
				'ar_EG' => array(
					'name'       => 'Arabic (Egypt)',
					'nativeName' => 'العربية (مصر)',
				),
				'ar_SA' => array(
					'name'       => 'Arabic (Saudi Arabia)',
					'nativeName' => 'العربية (السعودية)',
				),
				'fr_FR' => array(
					'name'       => 'French (France)',
					'nativeName' => 'Français',
				),
				'fr'    => array(
					'name'       => 'French',
					'nativeName' => 'Français',
				),
				'es_ES' => array(
					'name'       => 'Spanish (Spain)',
					'nativeName' => 'Español',
				),
				'es'    => array(
					'name'       => 'Spanish',
					'nativeName' => 'Español',
				),
				'de_DE' => array(
					'name'       => 'German',
					'nativeName' => 'Deutsch',
				),
				'de'    => array(
					'name'       => 'German',
					'nativeName' => 'Deutsch',
				),
				'it_IT' => array(
					'name'       => 'Italian',
					'nativeName' => 'Italiano',
				),
				'it'    => array(
					'name'       => 'Italian',
					'nativeName' => 'Italiano',
				),
				'pt_BR' => array(
					'name'       => 'Portuguese (Brazil)',
					'nativeName' => 'Português do Brasil',
				),
				'pt'    => array(
					'name'       => 'Portuguese',
					'nativeName' => 'Português',
				),
				'hi'    => array(
					'name'       => 'Hindi',
					'nativeName' => 'हिन्दी',
				),
				'ja'    => array(
					'name'       => 'Japanese',
					'nativeName' => '日本語',
				),
				'ko_KR' => array(
					'name'       => 'Korean',
					'nativeName' => '한국어',
				),
				'tr_TR' => array(
					'name'       => 'Turkish',
					'nativeName' => 'Türkçe',
				),
				'tr'    => array(
					'name'       => 'Turkish',
					'nativeName' => 'Türkçe',
				),
				'ru_RU' => array(
					'name'       => 'Russian',
					'nativeName' => 'Русский',
				),
				'ru'    => array(
					'name'       => 'Russian',
					'nativeName' => 'Русский',
				),
				'zh_CN' => array(
					'name'       => 'Chinese (China)',
					'nativeName' => '简体中文',
				),
				'zh_TW' => array(
					'name'       => 'Chinese (Taiwan)',
					'nativeName' => '繁體中文',
				),
				'nl_NL' => array(
					'name'       => 'Dutch',
					'nativeName' => 'Nederlands',
				),
				'nl'    => array(
					'name'       => 'Dutch',
					'nativeName' => 'Nederlands',
				),
			);

			foreach ( $installed as $locale ) {
				if ( 'en_US' === $locale ) {
					continue; // Already added.
				}

				$lang_prefix = substr( $locale, 0, 2 );
				$is_rtl      = in_array( $locale, $rtl_locales, true ) || in_array( $lang_prefix, array( 'ar', 'fa', 'he', 'ur' ), true );

				if ( isset( $translations[ $locale ] ) ) {
					$t           = $translations[ $locale ];
					$native_name = ! empty( $t['native_name'] ) ? $t['native_name'] : $locale;
					$name        = ! empty( $t['english_name'] ) ? $t['english_name'] : $locale;
				} elseif ( isset( $common_locales[ $locale ] ) ) {
					$native_name = $common_locales[ $locale ]['nativeName'];
					$name        = $common_locales[ $locale ]['name'];
				} elseif ( isset( $common_locales[ $lang_prefix ] ) ) {
					$native_name = $common_locales[ $lang_prefix ]['nativeName'];
					$name        = $common_locales[ $lang_prefix ]['name'];
				} else {
					// Fallback: pretty-print the locale slug.
					$name        = str_replace( '_', ' ', $locale );
					$native_name = $name;
				}

				$languages[ $locale ] = array(
					'locale'     => $locale,
					'name'       => $name,
					'nativeName' => $native_name,
					'isRtl'      => $is_rtl,
				);
			}
		}

		return array_values( $languages );
	}

	/**
	 * AJAX handler: switch the current WordPress admin UI language for this user.
	 */
	public static function handle_switch_language() {
		check_ajax_referer( 'wawp_switch_language', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) && ! current_user_can( WAWP_CAPABILITY ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied.' ), 403 );
			return;
		}

		$locale = isset( $_POST['locale'] ) ? sanitize_text_field( wp_unslash( $_POST['locale'] ) ) : '';

		if ( empty( $locale ) ) {
			wp_send_json_error( array( 'message' => 'Invalid locale.' ), 400 );
			return;
		}

		// Validate: make sure the locale is actually installed.
		$installed = function_exists( 'get_available_languages' ) ? get_available_languages( WP_LANG_DIR ) : array();
		if ( 'en_US' !== $locale && 'en' !== $locale && ! in_array( $locale, $installed, true ) ) {
			wp_send_json_error( array( 'message' => 'Locale not available.' ), 400 );
			return;
		}

		$user_id = get_current_user_id();

		if ( 'en' === $locale ) {
			$locale = 'en_US';
		}

		// Store the chosen locale in the user meta.
		update_user_meta( $user_id, 'locale', $locale );

		// Clear WordPress internal user locale cache.
		wp_cache_delete( $user_id, 'users' );

		// Bust the WAWP dashboard transient for this user so the next page load
		// fetches fresh data (with the correct i18n strings for the new locale).
		$cache_key = 'wawp_dashboard_data_full_' . $user_id;
		delete_transient( $cache_key );
		wp_cache_delete( $cache_key, 'wawp_database' );

		// Also clear any tracked transient keys for this user.
		$keys = get_option( 'wawp_dashboard_transient_keys', array() );
		if ( is_array( $keys ) ) {
			foreach ( $keys as $key ) {
				if ( false !== strpos( $key, (string) $user_id ) ) {
					delete_transient( $key );
					wp_cache_delete( $key, 'wawp_database' );
				}
			}
		}

		wp_send_json_success( array( 'locale' => $locale ) );
	}

	/**
	 * AJAX handler: flush WordPress and React assets cache.
	 */
	public static function handle_flush_cache() {
		check_ajax_referer( 'wawp_flush_cache', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) && ! current_user_can( WAWP_CAPABILITY ) ) {
			wp_send_json_error( array( 'message' => 'Permission denied.' ), 403 );
			return;
		}

		// 1. Force bust React cache (updates asset version query args).
		update_option( 'wawp_force_cache_bust_version', time(), false );

		// 2. Clear WordPress Transients & Object Cache.
		wp_cache_flush();
		if ( function_exists( 'delete_transient' ) ) {
			// Delete specific transients.
			delete_transient( 'wawp_last_db_check' );
			delete_transient( 'wawp_online_instances' );
			delete_transient( 'wawp_due_abandoned_notifs' );
			delete_transient( 'wawp_dashboard_transients' );

			$user_id = get_current_user_id();
			delete_transient( 'wawp_dashboard_data_full_' . $user_id );

			// Also delete any other cached dashboard transient keys.
			$keys = get_option( 'wawp_dashboard_transient_keys', array() );
			if ( is_array( $keys ) ) {
				foreach ( $keys as $key ) {
					delete_transient( $key );
					wp_cache_delete( $key, 'wawp_database' );
				}
				update_option( 'wawp_dashboard_transient_keys', array(), false );
			}
		}

		// 3. OPcache reset if available.
		if ( function_exists( 'opcache_reset' ) ) {
			opcache_reset();
		}

		// Flush rewrites just in case.
		flush_rewrite_rules( false );

		wp_send_json_success( array( 'message' => 'Cache cleared successfully.' ) );
	}

	/**
	 * Get the current Wawp Updater plugin activation status.
	 *
	 * @return string 'active'|'inactive'|'not_installed'
	 */
	public static function get_updater_status() {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		$slug        = 'wawp-updater/wawp-updater.php';
		$plugin_file = WP_PLUGIN_DIR . '/' . $slug;

		if ( ! file_exists( $plugin_file ) ) {
			return 'not_installed';
		}

		return is_plugin_active( $slug ) ? 'active' : 'inactive';
	}

	/**
	 * Get latest remote plugin version from transient or API.
	 *
	 * @return string
	 */
	public static function get_latest_version_from_transient() {
		$latest_version = get_transient( 'wawp_latest_plugin_version' );
		if ( false === $latest_version ) {
			$response = wp_remote_get(
				'https://app.wawp.net/api/external/plugin-version',
				array(
					'timeout'   => 3,
					'sslverify' => true,
					'headers'   => array(
						'Accept'     => 'application/json',
						'User-Agent' => 'Wawp-Plugin/' . WAWP_PLUGIN_VERSION . ' WordPress/' . get_bloginfo( 'version' ),
					),
				)
			);
			if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
				$body      = wp_remote_retrieve_body( $response );
				$body_data = json_decode( $body, true );
				if ( ! empty( $body_data['version'] ) ) {
					$latest_version = sanitize_text_field( $body_data['version'] );
					set_transient( 'wawp_latest_plugin_version', $latest_version, 43200 ); // Cache for 12 hours.
				}
			}
			if ( ! $latest_version ) {
				$latest_version = WAWP_PLUGIN_VERSION;
			}
		}
		return $latest_version;
	}
}

add_action( 'admin_enqueue_scripts', array( 'WAWP_Enqueue_Scripts', 'enqueue_admin_styles_scripts' ), 999 );
add_action( 'wp_enqueue_scripts', array( 'WAWP_Enqueue_Scripts', 'enqueue_frontend_styles_scripts' ) );
add_action( 'wp_ajax_wawp_switch_language', array( 'WAWP_Enqueue_Scripts', 'handle_switch_language' ) );
add_action( 'wp_ajax_wawp_flush_cache', array( 'WAWP_Enqueue_Scripts', 'handle_flush_cache' ) );
