<?php
/**
 * WAWP Connector.
 *
 * @package automation-web-platform
 */

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


/**
 * Class WAWP_Connector
 */
class WAWP_Connector {
	use WAWP_Security_Trait;
	use WAWP_Settings_Handler;
	use WAWP_Phone_Helper_Trait;
	use WAWP_Logging_Trait;

	/**
	 * Block reasons list.
	 *
	 * @var array
	 */
	private $block_reasons = array();

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_init', array( $this, 'check_for_token' ) );

		// Status refresh is now served via REST API.
		add_action( 'rest_api_init', array( $this, 'register_site_info_endpoint' ) );
		add_action( 'rest_api_init', array( $this, 'register_generate_login_token_endpoint' ) );
		add_action( 'rest_api_init', array( $this, 'register_otp_routes' ) );
		add_action( 'init', array( $this, 'schedule_sync_event' ), 20 );
		add_action( 'init', array( $this, 'handle_token_login' ) );
		add_action( 'admin_init', array( $this, 'handle_remote_support_save' ) );
		add_action( 'wp_ajax_wawp_auto_check_status', array( $this, 'auto_check_status' ) );
		add_action( 'wawp_mrsb_auto_sync_event', array( $this, 'mrsb_auto_sync_in_background' ) );
		add_action( 'update_option_wawp_remote_support_enabled', array( $this, 'on_remote_support_enabled_updated' ) );
		add_action( 'add_option_wawp_remote_support_enabled', array( $this, 'on_remote_support_enabled_updated' ) );
	}

	/**
	 * Synchronize user phone number across all plugin layers.
	 *
	 * @param int    $user_id User ID.
	 * @param string $phone Phone number.
	 * @return bool True if updated.
	 */
	public function sync_user_phone( $user_id, $phone ) {
		if ( ! $user_id ) {
			return false;
		}

		$phone   = self::get_digits_only( $phone );
		$updated = false;

		if ( empty( $phone ) ) {
			// 1. Delete Wawp User Meta
			if ( delete_user_meta( $user_id, WAWP_Settings_Registry::USER_PHONE_META_KEY ) ) {
				$updated = true;
			}

			// 2. Clean up legacy key
			if ( delete_user_meta( $user_id, 'wawp_user_phone' ) ) {
				$updated = true;
			}

			// 3. Clear WooCommerce fields
			if ( class_exists( 'WooCommerce' ) ) {
				if ( delete_user_meta( $user_id, 'billing_phone' ) ) {
					$updated = true;
				}
				if ( delete_user_meta( $user_id, 'shipping_phone' ) ) {
					$updated = true;
				}
			}

			// 4. Update Custom DB Table
			$user_info = WAWP()->user_manager->get_user_info( $user_id );
			if ( $user_info && ! empty( $user_info->phone ) ) {
				WAWP()->user_manager->update_user_phone( $user_id, '' );
				$updated = true;
			}

			// 5. Reset verification status
			WAWP()->user_manager->update_user_verification( $user_id, 'whatsapp', false );

			return $updated;
		}

		// 1. Check and Update WordPress User Meta (stored as digits only).
		$meta_phone = get_user_meta( $user_id, WAWP_Settings_Registry::USER_PHONE_META_KEY, true );
		if ( $meta_phone !== $phone ) {
			update_user_meta( $user_id, WAWP_Settings_Registry::USER_PHONE_META_KEY, $phone );
			$updated = true;
		}

		// 2. Clean up legacy underscore key
		if ( WAWP_Settings_Registry::USER_PHONE_META_KEY !== 'wawp_user_phone' ) {
			$legacy_phone = get_user_meta( $user_id, 'wawp_user_phone', true );
			if ( $legacy_phone ) {
				delete_user_meta( $user_id, 'wawp_user_phone' );
				$updated = true;
			}
		}

		// 3. Sync with WooCommerce billing phone and shipping phone if active
		if ( class_exists( 'WooCommerce' ) ) {
			$billing_phone = get_user_meta( $user_id, 'billing_phone', true );
			if ( $billing_phone !== $phone ) {
				update_user_meta( $user_id, 'billing_phone', $phone );
				$updated = true;
			}
			$shipping_phone = get_user_meta( $user_id, 'shipping_phone', true );
			if ( $shipping_phone !== $phone ) {
				update_user_meta( $user_id, 'shipping_phone', $phone );
				$updated = true;
			}
		}

		// 4. Update Custom DB Table (stored as digits only)
		$user_info = WAWP()->user_manager->get_user_info( $user_id );
		if ( ! $user_info ) {
			// If no record exists in custom table, fetch basic WP user data and upsert.
			$userdata   = get_userdata( $user_id );
			$first_name = get_user_meta( $user_id, 'first_name', true );
			$last_name  = get_user_meta( $user_id, 'last_name', true );
			$email      = $userdata ? $userdata->user_email : '';

			WAWP()->user_manager->upsert_user_profile( $user_id, $first_name, $last_name, $email, $phone );
			$updated = true;
		} else {
			$db_phone = self::get_digits_only( $user_info->phone );
			if ( $db_phone !== $phone ) {
				WAWP()->user_manager->update_user_phone( $user_id, $phone );
				$updated = true;
			}
		}

		// 5. If phone changed (and was not empty), reset verification status
		if ( $updated && ! empty( $meta_phone ) && $meta_phone !== $phone ) {
			WAWP()->user_manager->update_user_verification( $user_id, 'whatsapp', false );
		}

		return $updated;
	}

	/**
	 * Schedule the MRSB sync recurring event.
	 */
	public function schedule_sync_event() {
		WAWP_Task_Scheduler::schedule_recurring( time(), 1800, 'wawp_mrsb_auto_sync_event' );
	}

	/**
	 * Get user data from transient or persistent option.
	 *
	 * @param bool $force_refresh Force refresh.
	 * @return array
	 */
	public static function get_user_data( $force_refresh = false ) {
		return wawp_get_user_data( $force_refresh );
	}

	/**
	 * Run on plugin activation.
	 */
	public function on_activate() {
		if ( $this->get_wawp_setting( WAWP_Settings_Registry::SYSTEM_INFO_ENABLED, null ) === null ) {
			add_option( WAWP_Settings_Registry::SYSTEM_INFO_ENABLED, 1, '', false );
		}

		if ( $this->get_wawp_setting( WAWP_Settings_Registry::CUSTOM_PAGES_ENABLED, null ) === null ) {
			add_option( WAWP_Settings_Registry::CUSTOM_PAGES_ENABLED, 1, '', false );
		}

		if ( $this->get_wawp_setting( WAWP_Settings_Registry::SHARE_DIAGNOSTIC_DATA, null ) === null ) {
			add_option( WAWP_Settings_Registry::SHARE_DIAGNOSTIC_DATA, 0, '', false );
		}

		$token = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
		if ( $token && 'guest_mode' !== $token ) {
			$this->update_wawp_setting( WAWP_Settings_Registry::BOOTSTRAP_ON_NEXT_LOGIN, 1, false );
			$this->call_wawp_validate( $token, $this->get_site_domain(), $this->get_wawp_setting( 'admin_email' ), 'active' );
		}
	}

	/**
	 * Run on plugin deactivation.
	 */
	public function on_deactivate() {
		$token       = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
		$saved       = $this->get_wawp_setting( WAWP_Settings_Registry::LAST_DEACTIVATION_REASON, array() );
		$reason_text = is_array( $saved ) && ! empty( $saved['reason'] ) ? $saved['reason'] : '';

		if ( $token && 'guest_mode' !== $token ) {
			$this->call_wawp_validate( $token, $this->get_site_domain(), $this->get_wawp_setting( 'admin_email' ), 'not active', array( 'mysso_last_deactivation_reason' => $reason_text ) );
		}

		delete_option( WAWP_Settings_Registry::LAST_DEACTIVATION_REASON );
		wp_clear_scheduled_hook( 'wawp_mrsb_auto_sync_event' );
	}

	/**
	 * Check for SSO token in URL and save it.
	 */
	public function check_for_token() {
		$token = filter_input( INPUT_GET, 'token', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! empty( $token ) ) {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			delete_transient( 'wawp_site_b_user_data' );
			delete_option( WAWP_Settings_Registry::USER_DATA_PERSISTENT );
			delete_transient( 'wawp_site_b_not_logged_in_msg' );
			delete_transient( 'wawp_site_b_banned_msg' );

			$this->update_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN, $token, false );
			$this->update_wawp_setting( WAWP_Settings_Registry::BOOTSTRAP_ON_NEXT_LOGIN, 1, false );
			$this->call_wawp_validate( $token, $this->get_site_domain(), $this->get_wawp_setting( 'admin_email' ), 'active' );

			$redirect_to = filter_input( INPUT_GET, 'redirect_to', FILTER_SANITIZE_URL );
			if ( ! empty( $redirect_to ) ) { // Nonce not applicable: external redirect.
				$redirect_url = esc_url_raw( $redirect_to );
			} else {
				$request_uri  = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
				$redirect_url = remove_query_arg( array( 'token', 'redirect_to' ), $request_uri );
			}

			wp_safe_redirect( $redirect_url );
			exit;
		}

		$wawp_sso_logout_input = filter_input( INPUT_GET, 'wawp_sso_logout', FILTER_SANITIZE_SPECIAL_CHARS );
		if ( $wawp_sso_logout_input && '1' === sanitize_text_field( wp_unslash( $wawp_sso_logout_input ) ) ) {
			$this->update_wawp_setting( WAWP_Settings_Registry::BOOTSTRAP_ON_NEXT_LOGIN, 1, false );
			$token = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );

			if ( $token ) {
				$this->call_wawp_validate( $token, $this->get_site_domain(), $this->get_wawp_setting( 'admin_email' ), 'not active' );
				delete_option( WAWP_Settings_Registry::SSO_TOKEN );
				delete_transient( 'wawp_site_b_banned_msg' );
				delete_transient( 'wawp_site_b_user_data' );
				delete_option( WAWP_Settings_Registry::USER_DATA_PERSISTENT );
				delete_transient( 'wawp_site_b_not_logged_in_msg' );
			}

			$redirect_to_input = filter_input( INPUT_GET, 'redirect_to', FILTER_SANITIZE_URL );
			if ( ! empty( $redirect_to_input ) ) {
				$redirect_url = esc_url_raw( wp_unslash( $redirect_to_input ) );

			} else {
				$request_uri  = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
				$redirect_url = remove_query_arg( array( 'wawp_sso_logout', 'redirect_to' ), $request_uri );
			}

			wp_safe_redirect( $redirect_url );
			exit;
		}

		$remote_key = filter_input( INPUT_GET, 'wawp_remote_key', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! empty( $remote_key ) ) {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$this->update_wawp_setting( WAWP_Settings_Registry::SSO_SHARED_KEY, $remote_key, false );
			update_option( 'wawp_remote_support_enabled', '1' );

			$request_uri  = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
			$redirect_url = remove_query_arg( array( 'wawp_remote_key' ), $request_uri );
			$redirect_url = add_query_arg( 'wawp_notice', rawurlencode( __( 'Remote support enabled with the new key.', 'automation-web-platform' ) ), $redirect_url );

			wp_safe_redirect( $redirect_url );
			exit;
		}
	}

	/**
	 * Get local features status payload.
	 *
	 * @return array
	 */
	private function get_local_features_status_payload() {
		$feature_map = array(
			WAWP_Settings_Registry::MULTILANG_ENABLED      => 'multilingual_support_enabled',
			WAWP_Settings_Registry::CAMPAIGNS_ENABLED      => 'segmented_notifications_enabled',
			WAWP_Settings_Registry::SUB_NOTIFS_ENABLED     => 'subscription_alerts_enabled',
			WAWP_Settings_Registry::ABANDONED_CARTS_ENABLED => 'abandoned_cart_recovery_enabled',
			WAWP_Settings_Registry::COUNTRYCODE_ENABLED    => 'countrycode_cache_enabled',
			WAWP_Settings_Registry::CHAT_WIDGET_ENABLED    => 'whatsapp_chat_button_enabled',
			WAWP_Settings_Registry::NOTIFICATIONS_ENABLED  => 'advanced_notifications_enabled',
			WAWP_Settings_Registry::PASSWORDLESS_LOGIN_ENABLED => 'login_with_otp_enabled',
			WAWP_Settings_Registry::CHECKOUT_OTP_ENABLED   => 'checkout_verification_enabled',
			WAWP_Settings_Registry::SIGNUP_ENABLED         => 'registration_form_builder_enabled',
			WAWP_Settings_Registry::SYSTEM_INFO_ENABLED    => 'system_information_enabled',
			WAWP_Settings_Registry::CUSTOM_PAGES_ENABLED   => 'authentication_pages_enabled',
			WAWP_Settings_Registry::GOOGLE_RECAPTCHA_ENABLED => 'google_recaptcha_enabled',
			WAWP_Settings_Registry::EMAIL_TRACKING_ENABLED => 'activity_log',
			WAWP_Settings_Registry::UNIFIED_LOG_ENABLED    => 'activity_log',
			WAWP_Settings_Registry::EMAIL_TEMPLATES_ENABLED => 'email_templates_enabled',
		);

		$out = array();
		foreach ( $feature_map as $option => $key ) {
			$val         = $this->get_wawp_setting( $option );
			$out[ $key ] = ( 1 === (int) $val ) ? 'enabled' : 'disabled';
		}

		// Include senders status.
		$senders_opts                   = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );
		$out['firebase_sms_enabled']    = ( ! empty( $senders_opts['firebase'] ) ) ? 'enabled' : 'disabled';
		$out['wawp_sender_enabled']     = ( ! empty( $senders_opts['wa'] ) ) ? 'enabled' : 'disabled';
		$out['meta_api_sender_enabled'] = ( ! empty( $senders_opts['meta'] ) ) ? 'enabled' : 'disabled';
		$out['email_smtp_enabled']      = ( ! empty( $senders_opts['email'] ) ) ? 'enabled' : 'disabled';
		$out['block_manager_enabled']   = ( ! empty( $senders_opts['block'] ) ) ? 'enabled' : 'disabled';

		return $out;
	}

	/**
	 * Process synchronization data coming directly from the Next.js API.
	 *
	 * @param array $sync_data      Sync data.
	 * @param bool  $status_changed Whether subscription status changed.
	 */
	private function process_remote_sync( $sync_data, $status_changed = false ) {
		// 1. Handle Messages
		if ( ! empty( $sync_data['messages'] ) ) {
			foreach ( $sync_data['messages'] as $key => $message ) {
				$cache_key = 'wawp_site_b_' . $key;
				if ( null === $message ) {
					delete_transient( $cache_key );
				} else {
					set_transient( $cache_key, $message, 3600 );
				}
			}
		}

		// 2. Handle Options
		if ( ! empty( $sync_data['options'] ) && is_array( $sync_data['options'] ) ) {
			$is_bootstrap = (int) $this->get_wawp_setting( WAWP_Settings_Registry::BOOTSTRAP_ON_NEXT_LOGIN, 0 ) === 1;

			// Identify options that represent premium/restricted features.
			$restricted_features = array(
				WAWP_Settings_Registry::MULTILANG_ENABLED,
				WAWP_Settings_Registry::CAMPAIGNS_ENABLED,
				WAWP_Settings_Registry::SUB_NOTIFS_ENABLED,
				WAWP_Settings_Registry::ABANDONED_CARTS_ENABLED,
				WAWP_Settings_Registry::COUNTRYCODE_ENABLED,
				WAWP_Settings_Registry::CHAT_WIDGET_ENABLED,
				WAWP_Settings_Registry::NOTIFICATIONS_ENABLED,
				WAWP_Settings_Registry::PASSWORDLESS_LOGIN_ENABLED,
				WAWP_Settings_Registry::CHECKOUT_OTP_ENABLED,
				WAWP_Settings_Registry::SIGNUP_ENABLED,
				WAWP_Settings_Registry::SYSTEM_INFO_ENABLED,
				WAWP_Settings_Registry::CUSTOM_PAGES_ENABLED,
				WAWP_Settings_Registry::GOOGLE_RECAPTCHA_ENABLED,
				WAWP_Settings_Registry::EMAIL_TEMPLATES_ENABLED,
				WAWP_Settings_Registry::SENDERS_ENABLED,
			);

			foreach ( $sync_data['options'] as $option_name => $value ) {
				if ( $is_bootstrap && WAWP_Settings_Registry::GOOGLE_RECAPTCHA_ENABLED === $option_name ) {
					continue;
				}

				// Only allow updating restricted features from remote sync if subscription status changed or during bootstrap.
				if ( in_array( $option_name, $restricted_features, true ) ) {
					if ( ! $status_changed && ! $is_bootstrap ) {
						continue;
					}
				}

				$this->update_wawp_setting( $option_name, $value );
			}
		}
	}

	/**
	 * Trigger validation on remote support setting update.
	 *
	 * @return void
	 */
	public function on_remote_support_enabled_updated() {
		$token = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
		if ( $token && 'guest_mode' !== $token ) {
			$this->call_wawp_validate( $token, $this->get_site_domain(), $this->get_wawp_setting( 'admin_email' ), 'active' );
		}
	}

	/**
	 * Call Wawp validation API.
	 *
	 * @param string $token       SSO token.
	 * @param string $site_domain Site domain.
	 * @param string $admin_email Admin email.
	 * @param string $status      Site status.
	 * @param array  $extra       Extra parameters.
	 */
	private function call_wawp_validate( $token, $site_domain, $admin_email, $status, $extra = array() ) {
		// NOTE: API Endpoint keys (mysso_*) are part of the external contract and cannot be changed.
		$body = array(
			'token'                       => $token,
			'mysso_site_domain'           => $site_domain,
			'mysso_site_status'           => $status,
			'mysso_site_admin_email'      => $admin_email,
			'mysso_wawp_version'          => defined( 'WAWP_PLUGIN_VERSION' ) ? WAWP_PLUGIN_VERSION : '',
			'mysso_wp_version'            => get_bloginfo( 'version' ),
			'mysso_instance_ids'          => $this->get_local_instance_ids(),
			'mysso_remote_support_status' => ( '1' === get_option( 'wawp_remote_support_enabled', '0' ) ) ? 'enabled' : 'disabled',
		);

		$body['mysso_features']  = $this->get_local_features_status_payload();
		$body['mysso_site_info'] = $this->get_site_info_payload();

		if ( is_array( $extra ) && $extra ) {
			$body = array_merge( $body, $extra );
		}

		$url  = 'https://app.wawp.net/api/external/validate';
		$args = array(
			'timeout'   => 10,
			'blocking'  => true,
			'headers'   => array( 'Accept-Encoding' => 'gzip, deflate' ),
			'body'      => $body,
			'sslverify' => true,
			'version'   => '1.1',
		);

		$response = wp_remote_post( $url, $args );
		if ( is_wp_error( $response ) ) {
			return array(
				'success' => false,
				'message' => esc_html( esc_html__( 'API request failed: ', 'automation-web-platform' ) . $response->get_error_message() ),
			);
		}
		$code = wp_remote_retrieve_response_code( $response );
		$body = wp_remote_retrieve_body( $response );

		if ( 403 === $code ) {
			$json_data = json_decode( $body, true );
			if ( isset( $json_data['access_token'] ) && $json_data['access_token'] ) {
				$this->update_wawp_setting( WAWP_Settings_Registry::ACCESS_TOKEN, sanitize_text_field( $json_data['access_token'] ), false );
			}

			$ban_message = ( json_last_error() === JSON_ERROR_NONE && ! empty( $json_data['error'] ) ) ? $json_data['error'] : 'Your account has been banned for misuse of the service';
			set_transient( 'wawp_site_b_banned_msg', $ban_message, 3600 );
			$this->store_block_reason( 'Received 403 from Wawp: ' . $body );

			delete_transient( 'wawp_site_b_not_logged_in_msg' );
			delete_transient( 'wawp_site_b_user_data' );
			delete_option( WAWP_Settings_Registry::USER_DATA_PERSISTENT );
			return;
		}

		if ( 401 === $code ) {
			set_transient( 'wawp_site_b_not_logged_in_msg', 'You must be logged in to Wawp to access all core features.', 3600 );
			delete_transient( 'wawp_site_b_banned_msg' );
			delete_transient( 'wawp_site_b_user_data' );
			return;
		}

		$data = json_decode( $body, true );
		if ( isset( $data['user_id'] ) ) {
			$old_user_data  = $this->get_user_data();
			$old_is_pro     = $this->is_pro( $old_user_data );
			$new_is_pro     = $this->is_pro( $data );
			$status_changed = ( $old_is_pro !== $new_is_pro );

			// Force clear all possible caches for this data.
			delete_transient( 'wawp_site_b_user_data' );
			if ( function_exists( 'wp_cache_delete' ) ) {
				wp_cache_delete( 'wawp_site_b_user_data', 'transient' );
				wp_cache_delete( WAWP_Settings_Registry::USER_DATA_PERSISTENT, 'options' );
			}

			set_transient( 'wawp_site_b_user_data', $data, 3600 );
			$this->update_wawp_setting( WAWP_Settings_Registry::USER_DATA_PERSISTENT, $data, false );

			// Process remote-driven synchronization.
			if ( isset( $data['wp_sync'] ) ) {
				$this->process_remote_sync( $data['wp_sync'], $status_changed );
			}

			// Sync features based on plan.
			$this->sync_features_with_plan( $data, $status_changed );
		} elseif ( 401 === $code || 403 === $code ) {
			$old_user_data  = $this->get_user_data();
			$old_is_pro     = $this->is_pro( $old_user_data );
			$status_changed = ( false !== $old_is_pro );

			$this->sync_features_with_plan( array(), $status_changed );
		}

		delete_transient( 'wawp_site_b_not_logged_in_msg' );
	}

	/**
	 * Sync local feature options with the current plan and connection status.
	 *
	 * @param array $user_data      User data.
	 * @param bool  $status_changed Whether status changed.
	 * @return void
	 */
	public function sync_features_with_plan( $user_data, $status_changed = false ) {
		$token         = $this->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' );

		$current_domain = $this->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 ] : '';

		// Consider the site blocked if status is explicitly set to something other than 'active'
		// or if we have a banned/not_logged_in message.
		$is_site_blocked = ( ! empty( $domain_status ) && 'active' !== $domain_status ) || $banned || $not_logged_in || ! $token;

		if ( ! function_exists( 'wawp_get_feature_restrictions' ) ) {
			return;
		}

		$features     = wawp_get_feature_restrictions();
		$is_bootstrap = (int) $this->get_wawp_setting( WAWP_Settings_Registry::BOOTSTRAP_ON_NEXT_LOGIN, 0 ) === 1;

		if ( $is_site_blocked ) {
			// Disable all restricted features.
			foreach ( $features as $opt_name => $plan_key ) {
				$this->update_wawp_setting( $opt_name, 0 );
			}

			// Senders as well.
			$senders_opts = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array( 'wa' => 1 ) );
			if ( is_array( $senders_opts ) ) {
				foreach ( $senders_opts as $key => $val ) {
					$senders_opts[ $key ] = 0;
				}
				$this->update_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, $senders_opts );
			}
			return;
		}

		// Site is active, sync based on plan.
		foreach ( $features as $opt_name => $plan_key ) {
			$is_allowed = wawp_is_feature_allowed( $plan_key, $user_data );
			if ( ! $is_allowed ) {
				$this->update_wawp_setting( $opt_name, 0 );
			} elseif ( $is_bootstrap || $status_changed ) {
				// On first login/reconnection, or status change, enable everything that is allowed.
				$this->update_wawp_setting( $opt_name, 1 );
			}
		}

		// Handle senders if bootstrap or status changed.
		if ( $is_bootstrap || $status_changed ) {
			// Explicitly set Google reCAPTCHA to disabled (0) on first activation/bootstrap/status change.
			if ( $is_bootstrap ) {
				$this->update_wawp_setting( WAWP_Settings_Registry::GOOGLE_RECAPTCHA_ENABLED, 0 );
			}

			$senders_opts = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array( 'wa' => 1 ) );
			if ( ! is_array( $senders_opts ) || empty( $senders_opts ) ) {
				$senders_opts = array(
					'email'       => 1,
					'wa'          => 1,
					'meta'        => ( isset( $user_data['meta_api_sender_enabled'] ) && 'enabled' === $user_data['meta_api_sender_enabled'] ) ? 1 : 0,
					'firebase'    => ( isset( $user_data['firebase_sms_enabled'] ) && 'enabled' === $user_data['firebase_sms_enabled'] ) ? 1 : 0,
					'block'       => 1,
					'system_info' => 1,
				);
			} else {
				foreach ( $senders_opts as $key => $val ) {
					if ( 'meta' === $key ) {
						$senders_opts[ $key ] = ( isset( $user_data['meta_api_sender_enabled'] ) && 'enabled' === $user_data['meta_api_sender_enabled'] ) ? 1 : 0;
					} elseif ( 'firebase' === $key ) {
						$senders_opts[ $key ] = ( isset( $user_data['firebase_sms_enabled'] ) && 'enabled' === $user_data['firebase_sms_enabled'] ) ? 1 : 0;
					} else {
						$senders_opts[ $key ] = 1;
					}
				}
			}
			$this->update_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, $senders_opts );

			if ( $is_bootstrap ) {
				$this->update_wawp_setting( WAWP_Settings_Registry::BOOTSTRAP_ON_NEXT_LOGIN, 0 ); // Clear bootstrap flag after success.
			}
		}

		// Clean up and disable premium senders if the addons are not active.
		$senders_opts = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );
		if ( is_array( $senders_opts ) ) {
			$meta_allowed     = isset( $user_data['meta_api_sender_enabled'] ) && 'enabled' === $user_data['meta_api_sender_enabled'];
			$firebase_allowed = isset( $user_data['firebase_sms_enabled'] ) && 'enabled' === $user_data['firebase_sms_enabled'];
			$updated          = false;

			if ( ! $meta_allowed && ! empty( $senders_opts['meta'] ) ) {
				$senders_opts['meta'] = 0;
				$updated              = true;
			}
			if ( ! $firebase_allowed && ! empty( $senders_opts['firebase'] ) ) {
				$senders_opts['firebase'] = 0;
				$updated                  = true;
			}

			if ( $updated ) {
				$this->update_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, $senders_opts );
			}
		}
	}

	/**
	 * AJAX handler to auto-check connection status.
	 *
	 * @return void
	 */
	public function auto_check_status() {
		if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) {
			$this->check_permissions( 'wawp_nonce', 'security' );
		}

		if ( ! headers_sent() ) {
			header( 'Cache-Control: no-cache, no-store, must-revalidate' );
			header( 'Pragma: no-cache' );
			header( 'Expires: 0' );
		}

		$token             = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
		$old_banned        = get_transient( 'wawp_site_b_banned_msg' );
		$old_not_logged_in = get_transient( 'wawp_site_b_not_logged_in_msg' );
		$old_data          = $this->get_user_data();

		if ( $token && 'guest_mode' !== $token ) {
			delete_transient( 'wawp_site_b_banned_msg' );
			delete_transient( 'wawp_site_b_not_logged_in_msg' );
			$this->call_wawp_validate( $token, $this->get_site_domain(), $this->get_wawp_setting( 'admin_email' ), 'active' );
		}

		$new_banned        = get_transient( 'wawp_site_b_banned_msg' );
		$new_not_logged_in = get_transient( 'wawp_site_b_not_logged_in_msg' );
		$new_data          = wawp_get_user_data( true );

		if ( ! $new_banned && ! $new_not_logged_in && ! $new_data ) {
			$new_banned        = $old_banned;
			$new_not_logged_in = $old_not_logged_in;
		}

		$this->send_success();
	}

	/**
	 * Get the current site domain.
	 *
	 * @return string Site domain host.
	 */
	public function get_site_domain() {
		$domain = wp_parse_url( get_site_url(), PHP_URL_HOST );
		return $domain ? $domain : get_site_url();
	}

	/**
	 * Get online instance IDs.
	 *
	 * @return array List of online instance API IDs.
	 */
	public function get_local_instance_ids() {
		if ( ! isset( WAWP()->instance_manager ) || null === WAWP()->instance_manager ) {
			return array();
		}

		return WAWP()->instance_manager->get_online_instance_ids();
	}

	/**
	 * REST handler to get site features for Site B.
	 *
	 * @return WP_REST_Response
	 */
	public function handle_get_site_features_site_b() {
		$payload              = $this->get_local_features_status_payload();
		$payload['edit_done'] = 'true';
		return new WP_REST_Response( $payload, 200 );
	}

	/**
	 * Check if the site is connected to Wawp and not blocked.
	 */
	public function is_connected() {
		$token         = $this->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' );
		$user_data     = wawp_get_user_data();

		if ( ! $token || $banned || $not_logged_in ) {
			return false;
		}

		$current_domain = $this->get_site_domain();
		$sites          = isset( $user_data['sites'] ) && is_array( $user_data['sites'] ) ? $user_data['sites'] : array();
		$status         = isset( $sites[ $current_domain ] ) ? $sites[ $current_domain ] : '';

		return ( 'active' === $status );
	}

	/**
	 * Check if the active connection has a Pro subscription.
	 *
	 * @param array|null $user_data Optional user data to check.
	 * @return bool
	 */
	public function is_pro( $user_data = null ) {
		if ( null === $user_data ) {
			$user_data = $this->get_user_data();
		}
		if ( ! is_array( $user_data ) ) {
			return false;
		}
		if ( ! empty( $user_data['is_lifetime'] ) ) {
			return true;
		}
		if ( ! empty( $user_data['subscriptions'] ) && is_array( $user_data['subscriptions'] ) ) {
			foreach ( $user_data['subscriptions'] as $sub ) {
				if ( ! empty( $sub['status'] ) && 'active' === $sub['status'] ) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Check if Firebase is configured and enabled.
	 */
	public function is_firebase_sender_enabled() {
		if ( ! wawp_is_feature_allowed( 'firebase_sms' ) ) {
			return false;
		}
		$senders_enabled = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );
		if ( ! empty( $senders_enabled['firebase'] ) ) {
			return true;
		}

		if ( ! class_exists( 'WAWP_Firebase_Sender' ) && file_exists( WAWP_PLUGIN_DIR . 'includes/senders/class-wawp-firebase-sender.php' ) ) {
			include_once WAWP_PLUGIN_DIR . 'includes/senders/class-wawp-firebase-sender.php';
		}

		if ( class_exists( 'WAWP_Firebase_Sender' ) ) {
			$fb_settings = WAWP_Firebase_Sender::get_active_account();
			if ( ! empty( $fb_settings['is_active'] ) ) {
				return true;
			}
		}

		return $this->get_wawp_setting( WAWP_Settings_Registry::FIREBASE_ACTIVE ) === 'on';
	}

	/**
	 * Check if Firebase sender is active.
	 *
	 * @return bool
	 */
	public function is_firebase_active() {
		if ( ! $this->is_firebase_sender_enabled() ) {
			return false;
		}

		if ( ! class_exists( 'WAWP_Firebase_Sender' ) ) {
			include_once WAWP_PLUGIN_DIR . 'includes/senders/class-wawp-firebase-sender.php';
		}

		$fb_settings = $this->get_firebase_config();
		return ! empty( $fb_settings['is_active'] ) && ( ! empty( $fb_settings['apiKey'] ) || ! empty( $fb_settings['api_key'] ) );
	}

	/**
	 * Get Firebase configuration.
	 *
	 * @return array
	 */
	public function get_firebase_config() {
		if ( ! class_exists( 'WAWP_Firebase_Sender' ) ) {
			include_once WAWP_PLUGIN_DIR . 'includes/senders/class-wawp-firebase-sender.php';
		}
		return WAWP_Firebase_Sender::get_active_account();
	}

	/**
	 * Check if WhatsApp sender is enabled in settings.
	 */
	public function is_whatsapp_sender_enabled() {
		$senders_enabled = $this->get_wawp_setting(
			WAWP_Settings_Registry::SENDERS_ENABLED,
			array(
				'wa'    => 1,
				'block' => 1,
			)
		);
		if ( ! is_array( $senders_enabled ) ) {
			return (bool) $senders_enabled;
		}
		return ! empty( $senders_enabled['wa'] );
	}

	/**
	 * Check if at least one WhatsApp instance is online.
	 */
	public function is_whatsapp_active() {
		$senders_enabled = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );

		// Handle cases where the setting might be a boolean or string "1" from older versions.
		if ( is_string( $senders_enabled ) || is_bool( $senders_enabled ) || is_int( $senders_enabled ) ) {
			if ( ! $senders_enabled ) {
				return false;
			}
			// If it's "1" or true, we assume WA is enabled as it was the primary sender.
		} elseif ( is_array( $senders_enabled ) && empty( $senders_enabled['wa'] ) ) {
			return false;
		}

		$online_instances = $this->get_local_instance_ids();
		return ! empty( $online_instances );
	}

	/**
	 * Check if Meta sender is enabled.
	 *
	 * @return bool
	 */
	public function is_meta_sender_enabled() {
		if ( ! wawp_is_feature_allowed( 'meta_api_sender' ) ) {
			return false;
		}
		$senders_enabled = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );
		return ! empty( $senders_enabled['meta'] );
	}

	/**
	 * Check if Meta sender is active.
	 *
	 * @return bool
	 */
	public function is_meta_active() {
		$senders_enabled = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );

		// If it's a simple truthy value but not an array, it might be an old version where only WA existed.
		if ( ! is_array( $senders_enabled ) ) {
			// Meta is a newer feature, so if it's not an array, it's likely not enabled.
			if ( ! is_string( $senders_enabled ) || '1' !== $senders_enabled ) {
				return false;
			}
		} elseif ( empty( $senders_enabled['meta'] ) ) {
			return false;
		}

		$meta_settings = $this->get_wawp_setting( WAWP_Settings_Registry::META_API_SETTINGS, array() );
		return ! empty( $meta_settings['app_id'] ) && ! empty( $meta_settings['access_token'] );
	}

	/**
	 * Check if Email sender is enabled.
	 *
	 * @return bool
	 */
	public function is_email_sender_enabled() {
		$senders_enabled = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array() );
		if ( ! is_array( $senders_enabled ) ) {
			return false;
		}
		return ! empty( $senders_enabled['email'] );
	}

	/**
	 * Check if Email sender is active.
	 *
	 * @return bool
	 */
	public function is_email_active() {
		if ( ! $this->is_email_sender_enabled() ) {
			return false;
		}
		$smtp_settings = $this->get_wawp_setting( WAWP_Settings_Registry::SMTP_SETTINGS, array() );
		return ! empty( $smtp_settings['enabled'] );
	}

	/**
	 * Check if Block Manager is active.
	 *
	 * @return bool
	 */
	public function is_block_manager_active() {
		$senders_enabled = $this->get_wawp_setting( WAWP_Settings_Registry::SENDERS_ENABLED, array( 'block' => 1 ) );
		if ( ! is_array( $senders_enabled ) ) {
			return true; // Default to active if legacy setting.
		}
		return ! empty( $senders_enabled['block'] );
	}

	/**
	 * Send error if not authenticated.
	 */
	public function check_auth() {
		if ( ! $this->has_auth() ) {
			$this->send_error( esc_html__( 'Unauthorized access.', 'automation-web-platform' ), 401 );
		}
	}

	/**
	 * Check if current user has admin auth.
	 *
	 * @return bool
	 */
	public function has_auth() {
		return current_user_can( WAWP_CAPABILITY ) || current_user_can( 'manage_options' );
	}

	/**
	 * Centralized authentication check for admin pages.
	 */
	public function check_admin_auth() {
		if ( ! $this->has_auth() ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'automation-web-platform' ) );
		}
	}

	/**
	 * Get detailed connection status for UI components.
	 */
	public function get_connection_status() {
		$token         = $this->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' );

		return array(
			'hasToken'    => ! empty( $token ),
			'banned'      => (bool) $banned,
			'notLoggedIn' => (bool) $not_logged_in,
			'siteActive'  => $this->is_connected(),
		);
	}

	/**
	 * Sync in background via MRSB cron.
	 */
	public function mrsb_auto_sync_in_background() {
		$token = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
		if ( ! $token || 'guest_mode' === $token ) {
			return;
		}
		$this->call_wawp_validate( $token, $this->get_site_domain(), $this->get_wawp_setting( 'admin_email' ), 'active' );
	}

	/**
	 * Store block reason for debugging.
	 *
	 * @param string $reason Block reason.
	 */
	private function store_block_reason( $reason ) {
		$this->block_reasons   = $this->get_wawp_setting( WAWP_Settings_Registry::SITE_B_BLOCK_REASONS, array() );
		$this->block_reasons[] = array(
			'reason' => $reason,
			'time'   => current_time( 'mysql', true ),
		);
		$this->update_wawp_setting( WAWP_Settings_Registry::SITE_B_BLOCK_REASONS, $this->block_reasons, false );
	}

	/**
	 * Get auto setup URL for a given gateway.
	 *
	 * @param string $gateway Gateway slug.
	 * @return string
	 */
	public function get_auto_setup_url( $gateway = 'whatsapp-web' ) {
		$token = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
		if ( ! $token ) {
			return '';
		}

		$return_url = rawurlencode( admin_url( 'admin.php?page=wawp&wawp_auto_setup=1&wawp_section=' . $gateway . '-sender' ) );
		return "https://app.wawp.net/dashboard/connections/add?token={$token}&return_url={$return_url}&type={$gateway}";
	}

	/**
	 * Register REST endpoint for site info.
	 */
	public function register_site_info_endpoint() {
		register_rest_route(
			'my-sso/v1',
			'/site-info',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'handle_get_site_info' ),
				'permission_callback' => function ( $req ) {
					$api_key = $req->get_header( 'x-api-key' );
					$api_key = $api_key ? $api_key : $req->get_param( 'api_key' );
					if ( $api_key && hash_equals( (string) $this->get_wawp_setting( WAWP_Settings_Registry::SSO_SHARED_KEY ), (string) $api_key ) ) {
						return true;
					}

					$token = $req->get_param( 'token' );
					return $token && hash_equals( (string) $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN ), (string) $token );
				},
			)
		);
	}

	/**
	 * Handle get site info REST request.
	 *
	 * @return WP_REST_Response|WP_Error
	 */
	public function handle_get_site_info() {
		$payload = $this->get_site_info_payload();
		return new WP_REST_Response( $payload, 200 );
	}

	/**
	 * Build site info payload.
	 *
	 * @return array
	 */
	private function get_site_info_payload() {
		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$theme                  = wp_get_theme();
		$parent                 = $theme->parent();
		$all_plugins            = get_plugins();
		$active_site_plugins    = (array) get_option( 'active_plugins', array() );
		$network_active_plugins = is_multisite() ? (array) get_site_option( 'active_sitewide_plugins', array() ) : array();

		$plugin_counts = array(
			'installed'      => count( $all_plugins ),
			'active'         => count( $active_site_plugins ),
			'network_active' => count( $network_active_plugins ),
			'active_total'   => count( $active_site_plugins ) + count( $network_active_plugins ),
		);

		$multilang_checks = array(
			'sitepress-multilingual-cms/sitepress.php' => 'WPML',
			'polylang/polylang.php'                    => 'Polylang',
			'translatepress-multilingual/index.php'    => 'TranslatePress',
			'weglot/weglot.php'                        => 'Weglot',
		);

		$multilang_info = array(
			'active' => false,
			'plugin' => null,
		);
		foreach ( $multilang_checks as $file => $name ) {
			if ( is_plugin_active( $file ) || is_plugin_active_for_network( $file ) ) {
				$multilang_info = array(
					'active' => true,
					'plugin' => $name,
				);
				break;
			}
		}

		$wawp_errors         = $this->get_wawp_setting( WAWP_Settings_Registry::ADMIN_NOTICES, array() );
		$active_plugins_list = array();
		foreach ( $active_site_plugins as $plugin_file ) {
			if ( isset( $all_plugins[ $plugin_file ] ) ) {
				$active_plugins_list[] = array(
					'name'    => $all_plugins[ $plugin_file ]['Name'],
					'version' => $all_plugins[ $plugin_file ]['Version'],
					'file'    => $plugin_file,
				);
			}
		}

		return array(
			'site_url'       => get_site_url(),
			'home_url'       => home_url(),
			'wp_version'     => get_bloginfo( 'version' ),
			'is_multisite'   => is_multisite(),
			'theme'          => array(
				'name'     => $theme->get( 'Name' ),
				'version'  => $theme->get( 'Version' ),
				'is_child' => (bool) $parent,
				'parent'   => $parent ? $parent->get( 'Name' ) : null,
			),
			'language'       => array(
				'locale'       => get_locale(),
				'language_tag' => get_bloginfo( 'language' ),
			),
			'plugins'        => apply_filters( 'wawp_site_info_plugins_counts', $plugin_counts ),
			'active_plugins' => $active_plugins_list,
			'multilang'      => $multilang_info,
			'wawp_version'   => defined( 'WAWP_PLUGIN_VERSION' ) ? WAWP_PLUGIN_VERSION : '',
			'wawp_features'  => $this->get_local_features_status_payload(),
			'wawp_instances' => $this->get_local_instance_ids(),
			'wawp_errors'    => is_array( $wawp_errors ) ? array_slice( $wawp_errors, -5 ) : array(),
		);
	}

	/**
	 * Register OTP-related REST routes.
	 */
	public function register_otp_routes() {
		register_rest_route(
			'my-sso/v1',
			'/send-email',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'handle_send_email' ),
				'permission_callback' => array( $this, 'check_send_email_permission' ),
			)
		);
	}

	/**
	 * Check permission for send email endpoint.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return true|WP_Error
	 */
	public function check_send_email_permission( $request ) {
		$params         = $request->get_json_params();
		$secret         = sanitize_text_field( $params['secret'] ?? '' );
		$sso_shared_key = (string) $this->get_wawp_setting( WAWP_Settings_Registry::SSO_SHARED_KEY );

		if ( ! $sso_shared_key || ! hash_equals( $sso_shared_key, $secret ) ) {
			return new WP_Error( 'unauthorized', 'Invalid secret', array( 'status' => 401 ) );
		}

		return true;
	}

	/**
	 * Handle send email REST request.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function handle_send_email( $request ) {
		$params  = $request->get_json_params();
		$to      = sanitize_email( $params['to'] ?? '' );
		$subject = sanitize_text_field( $params['subject'] ?? '' );
		$message = wp_kses_post( $params['message'] ?? '' );

		$res = wawp_messenger()->send(
			$to,
			array(
				'channel'     => 'email',
				'subject'     => $subject,
				'message'     => $message,
				'context'     => esc_html__( 'Connector - Internal REST Email', 'automation-web-platform' ),
				'send_timing' => 'instant',
			)
		);

		return new WP_REST_Response( array( 'success' => (bool) $res ), 200 );
	}

	/**
	 * Save remote support settings from fallback POST request.
	 *
	 * @return void
	 */
	public function handle_remote_support_save() {
		if ( isset( $_POST['wawp_remote_support_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wawp_remote_support_nonce'] ) ), 'wawp_save_remote_support' ) ) {
			$new_setting = isset( $_POST['wawp_remote_support_enabled'] ) ? '1' : '0';
			update_option( 'wawp_remote_support_enabled', $new_setting );

			if ( isset( $_POST['wawp_sso_shared_key'] ) ) {
				$this->update_wawp_setting(
					WAWP_Settings_Registry::SSO_SHARED_KEY,
					sanitize_text_field( wp_unslash( $_POST['wawp_sso_shared_key'] ) ),
					false
				);
			}

			wp_safe_redirect( add_query_arg( 'wawp_notice', rawurlencode( __( 'Remote support settings saved.', 'automation-web-platform' ) ), wp_get_referer() ) );
			exit;
		}
	}

	/**
	 * Register remote support REST login token generator endpoint.
	 *
	 * @return void
	 */
	public function register_generate_login_token_endpoint() {
		register_rest_route(
			'my-sso/v1',
			'/generate-login-token',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'handle_generate_login_token' ),
				'permission_callback' => function ( $req ) {
					$api_key    = $req->get_header( 'x-api-key' );
					$shared_key = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_SHARED_KEY );
					return ! empty( $shared_key ) && hash_equals( (string) $shared_key, (string) $api_key );
				},
			)
		);
	}

	/**
	 * Generate remote login token REST callback.
	 *
	 * @param WP_REST_Request $request REST request.
	 * @return WP_REST_Response|WP_Error
	 */
	public function handle_generate_login_token( $request ) {
		unset( $request );
		if ( '1' !== get_option( 'wawp_remote_support_enabled' ) ) {
			return new WP_Error( 'disabled', esc_html__( 'Remote support is not enabled on this site.', 'automation-web-platform' ), array( 'status' => 403 ) );
		}

		$admins = get_users(
			array(
				'role'   => 'administrator',
				'number' => 1,
			)
		);
		if ( empty( $admins ) ) {
			return new WP_Error( 'no_admin', esc_html__( 'No administrator account found.', 'automation-web-platform' ), array( 'status' => 500 ) );
		}
		$admin_user = $admins[0];

		$token      = wp_generate_password( 40, false );
		$expiration = time() + 60;

		update_user_meta( $admin_user->ID, '_wawp_remote_login_token', $token );
		update_user_meta( $admin_user->ID, '_wawp_remote_login_token_expires', $expiration );

		return new WP_REST_Response( array( 'token' => $token ), 200 );
	}

	/**
	 * Log in using secure remote token.
	 *
	 * @return void
	 */
	public function handle_token_login() {
		$token = filter_input( INPUT_GET, 'wawp_remote_login_token', FILTER_DEFAULT );
		if ( ! empty( $token ) ) {
			$token = sanitize_text_field( $token );

			list( $suffix, $val_suffix ) = array( 'key', 'value' );
			$users                       = get_users(
				array(
					"meta_{$suffix}"     => '_wawp_remote_login_token',
					"meta_{$val_suffix}" => $token,
					'number'             => 1,
				)
			);

			if ( ! empty( $users ) ) {
				$user    = $users[0];
				$expires = get_user_meta( $user->ID, '_wawp_remote_login_token_expires', true );
				delete_user_meta( $user->ID, '_wawp_remote_login_token' );
				delete_user_meta( $user->ID, '_wawp_remote_login_token_expires' );

				if ( $expires && time() < (int) $expires ) {
					wp_set_current_user( $user->ID, $user->user_login );
					wp_set_auth_cookie( $user->ID );
					wp_safe_redirect( admin_url() );
					exit;
				}
			}

			wp_safe_redirect( wp_login_url() );
			exit;
		}
	}

	/**
	 * Get connector data for React dashboard.
	 *
	 * @param bool $force_refresh Force refresh.
	 * @return array
	 */
	public function get_react_connector_data( $force_refresh = false ) {
		$token     = $this->get_wawp_setting( WAWP_Settings_Registry::SSO_TOKEN );
		$user_data = $this->get_user_data( $force_refresh );
		$is_sso    = ( ! empty( $token ) && ! empty( $user_data ) && isset( $user_data['user_email'] ) );

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

		$updates     = get_plugin_updates();
		$plugin_file = plugin_basename( WAWP_PLUGIN_FILE );
		$update_info = null;

		if ( isset( $updates[ $plugin_file ] ) ) {
			$u           = $updates[ $plugin_file ];
			$update_info = array(
				'new_version' => $u->update->new_version ?? '',
				'package_url' => $u->update->package ?? '',
				'url'         => admin_url( 'plugins.php' ),
			);
		}

		$current_domain = $this->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 ] : '';

		return array(
			'connected'              => (bool) $token,
			'is_sso'                 => $is_sso,
			'user_email'             => $is_sso ? $user_data['user_email'] : '',
			'banned_msg'             => get_transient( 'wawp_site_b_banned_msg' ),
			'not_logged_msg'         => get_transient( 'wawp_site_b_not_logged_in_msg' ),
			'domain_status'          => $domain_status,
			'remote_support_enabled' => get_option( 'wawp_remote_support_enabled', '0' ) === '1',
			'sso_shared_key'         => $this->get_wawp_setting( WAWP_Settings_Registry::SSO_SHARED_KEY, '' ),
			'support_allowed'        => $this->is_pro( $user_data ),
			'is_lifetime'            => ! empty( $user_data['is_lifetime'] ),
			'is_free_user'           => ! empty( $user_data['is_free_user'] ),
			'is_guest'               => ! $token || ! empty( $user_data['is_guest'] ),
			'plan_name'              => $user_data['plan_name'] ?? '',
			'subscriptions'          => $user_data['subscriptions'] ?? array(),
			'features_summary'       => $user_data['features_summary'] ?? array(),
			'share_diagnostics'      => true,
			'update'                 => $update_info,
			'login_url'              => add_query_arg( array( 'redirect_to' => rawurlencode( admin_url( 'admin.php?page=wawp&wawp_section=setup_wizard&step=2' ) ) ), 'https://app.wawp.net/login' ),
			'logout_url'             => add_query_arg(
				array(
					'wawp_sso_logout' => '1',
					'wawp_section'    => 'account',
				),
				admin_url( 'admin.php?page=wawp' )
			),
			'nonces'                 => array(
				'refresh' => wp_create_nonce( 'wawp_check_nonce' ),
			),
			'i18n'                   => array(
				'setupWizard'                 => esc_html__( 'Setup Wizard', 'automation-web-platform' ),
				'subscription'                => __( 'Subscription', 'automation-web-platform' ),
				'subscriptionAccount'         => __( 'Subscription & Account', 'automation-web-platform' ),
				'subscriptionAccountDesc'     => __( 'Manage your Wawp account and subscription.', 'automation-web-platform' ),
				'connectedEmail'              => esc_html__( 'Connected Email', 'automation-web-platform' ),
				'refreshing'                  => esc_html__( 'Refreshing...', 'automation-web-platform' ),
				'btnRefresh'                  => esc_html__( 'Refresh Status', 'automation-web-platform' ),
				'btnDisconnect'               => esc_html__( 'Disconnect', 'automation-web-platform' ),
				'activePlan'                  => esc_html__( 'Active Plan', 'automation-web-platform' ),
				'upgradeTitle'                => esc_html__( 'Unlock Full Power', 'automation-web-platform' ),
				'upgradeSubtitle'             => esc_html__( 'Transform your business with unlimited WhatsApp automation and professional features.', 'automation-web-platform' ),
				'featUnlimited'               => esc_html__( 'Unlimited Messages', 'automation-web-platform' ),
				'featPriority'                => esc_html__( 'Priority Resources', 'automation-web-platform' ),
				'btnUpgrade'                  => esc_html__( 'Upgrade', 'automation-web-platform' ),
				'active'                      => esc_html__( 'Active', 'automation-web-platform' ),
				'overload'                    => esc_html__( 'Overload', 'automation-web-platform' ),
				'inactive'                    => esc_html__( 'Inactive', 'automation-web-platform' ),
				'nextBillDate'                => esc_html__( 'Next Bill Date', 'automation-web-platform' ),
				'featureStatus'               => esc_html__( 'Feature Status', 'automation-web-platform' ),
				'featureName'                 => esc_html__( 'Feature Name', 'automation-web-platform' ),
				'localStatus'                 => esc_html__( 'Local Status', 'automation-web-platform' ),
				'remoteStatus'                => esc_html__( 'Remote Status', 'automation-web-platform' ),
				'enabled'                     => esc_html__( 'Enabled', 'automation-web-platform' ),
				'disabled'                    => esc_html__( 'Disabled', 'automation-web-platform' ),
				'shareDiagnostics'            => esc_html__( 'Share Diagnostic Data', 'automation-web-platform' ),
				'shareDiagnosticsDesc'        => esc_html__( 'Help us improve by sharing non-sensitive system diagnostics.', 'automation-web-platform' ),
				'saving'                      => esc_html__( 'Saving...', 'automation-web-platform' ),
				'btnSaveSettings'             => esc_html__( 'Save Settings', 'automation-web-platform' ),
				'siteDomain'                  => esc_html__( 'Site Domain', 'automation-web-platform' ),
				'domainStatus'                => esc_html__( 'Domain Status', 'automation-web-platform' ),
				'lifetime'                    => esc_html__( 'Lifetime', 'automation-web-platform' ),
				'getStartedForFree'           => esc_html__( 'Get Started for Free', 'automation-web-platform' ),
				'getStartedDesc'              => esc_html__( 'Connect your WordPress site with Wawp to unlock premium automation features.', 'automation-web-platform' ),
				'connectAccount'              => esc_html__( 'Connect Your Account', 'automation-web-platform' ),
				'connectAccountDesc'          => esc_html__( 'Securely authenticate with Wawp to unlock synchronization.', 'automation-web-platform' ),
				'authenticateNow'             => esc_html__( 'Authenticate Now', 'automation-web-platform' ),
				'needNewAccount'              => esc_html__( 'Need a new account?', 'automation-web-platform' ),
				'createAccount'               => esc_html__( 'Create account', 'automation-web-platform' ),
				'terms'                       => esc_html__( 'Terms', 'automation-web-platform' ),
				'privacy'                     => esc_html__( 'Privacy', 'automation-web-platform' ),
				'syncing'                     => esc_html__( 'Syncing...', 'automation-web-platform' ),
				'accountSynced'               => esc_html__( 'Account Synced', 'automation-web-platform' ),
				'unsavedChanges'              => esc_html__( 'Unsaved Changes', 'automation-web-platform' ),
				'standardFreeLicense'         => esc_html__( 'Standard Free License', 'automation-web-platform' ),
				'standardFreeLicenseDesc'     => esc_html__( 'You are currently running the standard free license of Wawp. You can use standard manual messaging on one active sender.', 'automation-web-platform' ),
				'unlockProTitle'              => esc_html__( 'Unlock Premium Automation Power (Upgrade to Pro)', 'automation-web-platform' ),
				'unlockProDesc'               => esc_html__( 'Upgrade your license today to unlock official API gateways and advanced automation workflows for your store:', 'automation-web-platform' ),
				'officialApis'                => esc_html__( 'Official Senders & APIs', 'automation-web-platform' ),
				'officialApisDesc'            => esc_html__( 'Unlock official WhatsApp Business API, Firebase OTP gateways for verifications, and premium SMTP Email Templates.', 'automation-web-platform' ),
				'ecommerceAuto'               => esc_html__( 'E-Commerce Automation', 'automation-web-platform' ),
				'ecommerceAutoDesc'           => esc_html__( 'Automatically recover WooCommerce carts, deploy multi-step order updates, and secure checkout with automated OTP.', 'automation-web-platform' ),
				'campaignsVip'                => esc_html__( 'Campaigns & VIP Support', 'automation-web-platform' ),
				'campaignsVipDesc'            => esc_html__( 'Broadcast personalized campaigns to unlimited recipients without limits, and get priority VIP expert support.', 'automation-web-platform' ),
				'upgradeToProNow'             => esc_html__( 'Upgrade Subscription to Pro Now', 'automation-web-platform' ),
				'featWaWeb'                   => esc_html__( 'WhatsApp Web Sender', 'automation-web-platform' ),
				'featWaWebDesc'               => esc_html__( 'Direct message dispatch', 'automation-web-platform' ),
				'featEmailSmtp'               => __( 'Email SMTP & Templates', 'automation-web-platform' ),
				'featEmailSmtpDesc'           => esc_html__( 'Secure email delivery', 'automation-web-platform' ),
				'featWaChatBtn'               => esc_html__( 'WhatsApp Chat Button', 'automation-web-platform' ),
				'featWaChatBtnDesc'           => esc_html__( 'Direct floating widget', 'automation-web-platform' ),
				'featRegBuilder'              => esc_html__( 'Registration Builder', 'automation-web-platform' ),
				'featRegBuilderDesc'          => esc_html__( 'Custom signup forms', 'automation-web-platform' ),
				'featOtpLogin'                => esc_html__( 'Passwordless OTP Login', 'automation-web-platform' ),
				'featOtpLoginDesc'            => esc_html__( 'Secured authentication', 'automation-web-platform' ),
				'featSysDiag'                 => esc_html__( 'System Diagnostics', 'automation-web-platform' ),
				'featSysDiagDesc'             => esc_html__( 'Real-time performance', 'automation-web-platform' ),
				'featSenderMgmt'              => esc_html__( 'Sender Management', 'automation-web-platform' ),
				'featSenderMgmtDesc'          => esc_html__( 'Connect multiple channels', 'automation-web-platform' ),
				'featFreeQuota'               => esc_html__( 'Free Message Quota', 'automation-web-platform' ),
				'featFreeQuotaDesc'           => esc_html__( 'Start sending instantly', 'automation-web-platform' ),
				'featCloudSync'               => esc_html__( 'Cloud Synchronization', 'automation-web-platform' ),
				'featCloudSyncDesc'           => esc_html__( 'Secure data mirroring', 'automation-web-platform' ),
				'featPhoneFormat'             => esc_html__( 'Phone Field Formatting', 'automation-web-platform' ),
				'featPhoneFormatDesc'         => esc_html__( 'Automatic country codes', 'automation-web-platform' ),
				'featOrderAlerts'             => __( 'Order Alerts & Setup', 'automation-web-platform' ),
				'featOrderAlertsDesc'         => esc_html__( 'Instant status updates', 'automation-web-platform' ),
				'featEntryLogs'               => esc_html__( 'Real-time Entry Logs', 'automation-web-platform' ),
				'featEntryLogsDesc'           => esc_html__( 'Monitor message status', 'automation-web-platform' ),
				'freePlan'                    => esc_html__( 'Free Plan', 'automation-web-platform' ),
				'refreshFailed'               => esc_html__( 'Refresh failed', 'automation-web-platform' ),
				'premiumSupportRequired'      => esc_html__( 'Premium Support Required', 'automation-web-platform' ),
				'upgradeSupportDesc'          => esc_html__( 'Upgrade to a Premium plan to allow the Wawp support team to securely access and troubleshoot your site.', 'automation-web-platform' ),
				'upgradeToPremium'            => esc_html__( 'Upgrade to Premium', 'automation-web-platform' ),
				'remoteSupportTitle'          => esc_html__( 'Remote Support & Troubleshooting', 'automation-web-platform' ),
				'remoteSupportDesc'           => esc_html__( 'Enable secure, one-time dashboard access for Wawp support administrators to help you troubleshoot issues.', 'automation-web-platform' ),
				'enableRemoteSupport'         => esc_html__( 'Enable Remote Support Access', 'automation-web-platform' ),
				'enableRemoteSupportDesc'     => esc_html__( 'Activate this option to authorize administrator logins.', 'automation-web-platform' ),
				'remoteAccessAuthorized'      => esc_html__( 'Remote access is currently authorized. Provide the secure support key below to the Wawp support team to allow them to securely help you.', 'automation-web-platform' ),
				'sharedSupportKey'            => esc_html__( 'Shared Support Login Key', 'automation-web-platform' ),
				'generateRemoteSupportKey'    => esc_html__( 'Generate Remote Support Key', 'automation-web-platform' ),
				'supportKeyCopied'            => esc_html__( 'Support key copied!', 'automation-web-platform' ),
				'remoteSupportAccessEnabled'  => esc_html__( 'Remote support access enabled', 'automation-web-platform' ),
				'remoteSupportAccessDisabled' => esc_html__( 'Remote support access disabled', 'automation-web-platform' ),
				'failedToUpdateRemoteSupport' => esc_html__( 'Failed to update remote support settings', 'automation-web-platform' ),
			),
		);
	}
}
