<?php
/**
 * Checkout OTP Service.
 *
 * @package automation-web-platform
 */

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


/**
 * Class WAWP_Checkout_Otp
 * Handles Checkout OTP functionality.
 *
 * @package automation-web-platform
 */
class WAWP_Checkout_Otp {
	use WAWP_Security_Trait;
	use WAWP_Phone_Helper_Trait;
	use WAWP_Settings_Handler;
	use WAWP_Logging_Trait;

	/**
	 * Database Manager.
	 *
	 * @var WAWP_Database_Manager
	 */
	public $db;

	/**
	 * Flag to track if OTP popup markup has been rendered.
	 *
	 * @var bool
	 */
	private $popup_rendered = false;

	/**
	 * Instance of this class.
	 *
	 * @var WAWP_Checkout_Otp|null
	 */
	private static $instance = null;

	/**
	 * Get instance.
	 *
	 * @return WAWP_Checkout_Otp
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		$this->db = WAWP()->db;
		add_action( 'init', array( $this, 'init_hooks' ) );
		add_action( 'init', array( $this, 'load_otp_verification' ) );
	}

	/**
	 * Init hooks.
	 */
	public function init_hooks() {
		add_action( 'woocommerce_thankyou', array( $this, 'update_user_data_after_order' ), 10, 1 );
		add_action( 'woocommerce_checkout_order_processed', array( $this, 'save_otp_verification_to_order' ), 10, 3 );
	}

	/**
	 * Save OTP verification status to the order.
	 *
	 * @param int      $order_id Order ID.
	 * @param array    $posted_data Posted data.
	 * @param WC_Order $order Order object.
	 */
	public function save_otp_verification_to_order( $order_id, $posted_data, $order ) {
		if ( WC()->session && WC()->session->get( 'otp_verified' ) ) {
			$order->update_meta_data( '_otp_verified', 'yes' );
			$order->save();

			$user_id = $order->get_user_id();
			if ( $user_id ) {
				$first_name = sanitize_text_field( $order->get_billing_first_name() );
				$last_name  = sanitize_text_field( $order->get_billing_last_name() );
				$email      = sanitize_email( $order->get_billing_email() );
				[ $phone, ] = $this->format_phone_number( $order->get_billing_phone() );

				WAWP()->user_manager->upsert_user_profile( $user_id, $first_name, $last_name, $email, $phone );
				WAWP()->user_manager->update_user_verification( $user_id, 'whatsapp', true );
			}
		}
	}

	/**
	 * Update user data after order.
	 *
	 * @param int $order_id Order ID.
	 */
	public function update_user_data_after_order( $order_id ) {
		if ( ! $order_id ) {
			return;
		}

		$order = function_exists( 'wc_get_order' ) ? wc_get_order( $order_id ) : null;
		if ( ! $order ) {
			return;
		}

		$user_id = $order->get_user_id();
		if ( ! $user_id ) {
			return;
		}

		$first_name = sanitize_text_field( $order->get_billing_first_name() );
		$last_name  = sanitize_text_field( $order->get_billing_last_name() );
		$email      = sanitize_email( $order->get_billing_email() );
		[ $phone, ] = $this->format_phone_number( $order->get_billing_phone() );

		wp_update_user(
			array(
				'ID'         => $user_id,
				'user_email' => $email ? $email : get_userdata( $user_id )->user_email,
			)
		);

		if ( $first_name ) {
			update_user_meta( $user_id, 'first_name', $first_name );
		}
		if ( $last_name ) {
			update_user_meta( $user_id, 'last_name', $last_name );
		}

		WAWP()->user_manager->upsert_user_profile( $user_id, $first_name, $last_name, $email, $phone );
		WAWP()->connector->sync_user_phone( $user_id, $phone );

		$is_verified = false;
		if ( WC()->session && WC()->session->get( 'otp_verified' ) ) {
			$is_verified = true;
		} elseif ( 'yes' === $order->get_meta( '_otp_verified' ) ) {
			$is_verified = true;
		}

		if ( $is_verified ) {
			WAWP()->user_manager->update_user_verification( $user_id, 'whatsapp', true );
		}
	}

	/**
	 * Load OTP verification.
	 */
	public function load_otp_verification() {
		$settings   = $this->get_settings();
		$enable_otp = $settings[ WAWP_Settings_Registry::CHECKOUT_ENABLE_OTP ];

		if ( 'yes' !== $enable_otp ) {
			return;
		}

		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
		add_filter( 'wawp_frontend_global_vars', array( $this, 'add_frontend_global_vars' ) );
		add_action( 'woocommerce_after_order_notes', array( $this, 'add_otp_verification_popup' ) );
		add_action( 'wp_footer', array( $this, 'add_otp_verification_popup_footer' ) );
		add_action( 'woocommerce_checkout_process', array( $this, 'check_if_otp_verified' ) );
	}

	/**
	 * Render popup on wp_footer if it hasn't been printed yet.
	 */
	public function add_otp_verification_popup_footer() {
		if ( function_exists( 'is_checkout' ) && is_checkout() ) {
			$this->add_otp_verification_popup();
		}
	}

	/**
	 * Enqueue frontend scripts.
	 */
	public function enqueue_frontend_scripts() {
		wp_enqueue_script( 'wawp-checkout-js', WAWP_PLUGIN_URL . 'assets/js/checkout.js', array( 'jquery', 'wawp-global-data-hub' ), '1.0', true );
		wp_enqueue_style( 'wawp-local-fonts', WAWP_PLUGIN_URL . 'assets/css/wawp-fonts.css', array(), '1.0.0' );
		wp_enqueue_style( 'wawp-checkout-css', WAWP_PLUGIN_URL . 'assets/css/checkout.css', array(), '1.0', 'all' );

		$settings   = $this->get_settings();
		$otp_method = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_METHOD ];

		if ( 'firebase' === $otp_method ) {
			wp_enqueue_script( 'firebase-app', WAWP_PLUGIN_URL . 'assets/js/resources/firebase-app-compat.js', array(), '9.1.1', true );
			wp_enqueue_script( 'firebase-auth', WAWP_PLUGIN_URL . 'assets/js/resources/firebase-auth-compat.js', array( 'firebase-app' ), '9.1.1', true );
		}
	}

	/**
	 * Add global variables to the central data hub.
	 *
	 * @param array $vars Global variables array.
	 * @return array
	 */
	public function add_frontend_global_vars( $vars ) {
		$settings   = $this->get_settings();
		$enable_otp = $settings[ WAWP_Settings_Registry::CHECKOUT_ENABLE_OTP ];

		if ( 'yes' !== $enable_otp ) {
			return $vars;
		}

		$otp_method = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_METHOD ];

		$vars['wawp_translations'] = array(
			'otp_sent_success'     => esc_html__( 'OTP sent successfully.', 'automation-web-platform' ),
			'otp_sent_failure'     => esc_html__( 'Failed to send OTP. Please try again.', 'automation-web-platform' ),
			'otp_verified_success' => esc_html__( 'OTP verified successfully.', 'automation-web-platform' ),
			'otp_incorrect'        => esc_html__( 'Incorrect OTP. Please try again.', 'automation-web-platform' ),
			'method'               => $otp_method,
		);

		if ( 'firebase' === $otp_method ) {
			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' ) ) {
				$vars['wawpCheckoutFirebase'] = array(
					'firebase_config'  => WAWP_Firebase_Sender::get_active_account(),
					'firebase_enabled' => true,
				);
			}
		}

		$otp_mode         = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_MODE ];
		$already_verified = 'false';

		if ( is_user_logged_in() ) {
			$u    = get_current_user_id();
			$info = WAWP()->user_manager->get_user_info( $u );
			if ( $info && 'Verified' === $info->whatsapp_verified && 1 === (int) $info->otp_verification_whatsapp ) {
				$already_verified = 'true';
			}
		}

		$vars['wawpCheckoutOtpAjax'] = array(
			'ajaxurl'          => admin_url( 'admin-ajax.php' ),
			'rest_url'         => esc_url_raw( rest_url( 'wawp/v1/checkout-otp' ) ),
			'nonce'            => wp_create_nonce( 'otp-ajax-nonce' ),
			'wp_rest_nonce'    => wp_create_nonce( 'wp_rest' ),
			'isLoggedIn'       => is_user_logged_in() ? 'true' : 'false',
			'otpMode'          => $otp_mode,
			'verified'         => $already_verified,
			'initial_cooldown' => $settings[ WAWP_Settings_Registry::AUTH_INITIAL_COOLDOWN ] ?? 30,
			'max_cooldown'     => $settings[ WAWP_Settings_Registry::AUTH_MAX_COOLDOWN ] ?? 300,
			'polling_interval' => $settings[ WAWP_Settings_Registry::AUTH_POLLING_INTERVAL ] ?? 3000,
		);

		$disabled_payment_methods = (array) $settings[ WAWP_Settings_Registry::CHECKOUT_DISABLE_PAYMENT ];
		$vars['wawpDisable']      = array( 'disableMethods' => $disabled_payment_methods );

		$disabled_shipping_methods   = (array) $settings[ WAWP_Settings_Registry::CHECKOUT_DISABLE_SHIPPING ];
		$vars['wawpDisableShipping'] = array( 'disableMethods' => $disabled_shipping_methods );

		return $vars;
	}

	/**
	 * Add OTP verification popup.
	 */
	public function add_otp_verification_popup() {
		if ( $this->popup_rendered ) {
			return;
		}
		$this->popup_rendered = true;

		$settings  = $this->get_settings();
		$otp_title = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_TITLE ] ?? '';
		WAWP_OTP_Service::get_instance()->render_dynamic_styles( $settings );

		$otp_method = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_METHOD ];
		$otp_icon   = 'ri-whatsapp-line';
		$otp_desc   = __( 'To complete your order, enter the 6-digit code sent via WhatsApp to <span id="user_phone_number"></span>', 'automation-web-platform' );

		if ( 'firebase' === $otp_method ) {
			$otp_icon = 'ri-message-3-line';
			$otp_desc = __( 'To complete your order, enter the 6-digit code sent via SMS to <span id="user_phone_number"></span>', 'automation-web-platform' );
		} elseif ( 'email' === $otp_method ) {
			$otp_icon = 'ri-mail-line';
			$otp_desc = __( 'To complete your order, enter the 6-digit code sent to your email <span id="user_phone_number"></span>', 'automation-web-platform' );
		}

		echo '<div id="wawp_otp_popup" class="wawp-otp-popup">
                <div class="wawp-otp-popup-content">
                    <div class="wawp-popup-message"></div>
                    <div class="wawp-otp-box">
                        <div class="wawp-icon-wrapper"><i id="otp-icon" class="' . esc_attr( $otp_icon ) . '"></i></div>
                        <h3 class="wawp-title">' . esc_html( $otp_title ) . '</h3>
                        <p class="wawp-desc">' . wp_kses_post( $otp_desc ) . '</p>
                        <span class="wawp-otp-popup-close">&times;</span>
                    </div>
                    <div class="wawp-otp-content">
                        ' . ( ( 'firebase' === $otp_method ) ? '<div id="wawp-recaptcha-checkout"></div>' : '' ) . '
                        <input type="tel" id="wawp_otp_input" pattern="[0-9]*" inputmode="numeric" maxlength="6" placeholder="' . esc_attr__( 'Enter 6-digit code', 'automation-web-platform' ) . '" />
                        <div class="wawp-btn-group">
                            <button type="button" class="wawp-btn wawp-verify-btn" id="wawp_verify_otp_btn">' . esc_html__( 'Confirm order', 'automation-web-platform' ) . '</button>
                            <button type="button" class="wawp-btn wawp-resend-btn" id="wawp_resend_otp_btn" disabled>
                                ' . esc_html__( 'Resend code', 'automation-web-platform' ) . '
                                <span id="wawp_resend_timer"></span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>';
	}

	/**
	 * Send OTP AJAX handler.
	 */
	public function send_otp_ajax_handler() {
		check_ajax_referer( 'otp-ajax-nonce', 'security' );
		$res = $this->handle_send_otp( filter_input_array( INPUT_POST, FILTER_DEFAULT ) );
		if ( $res['success'] ) {
			$this->send_success( $res['message'], $res['data'] );
		} else {
			$this->send_error( $res['message'] );
		}
	}

	/**
	 * Send OTP return.
	 *
	 * @param array $params Request parameters.
	 * @return array|WP_Error
	 */
	public function send_otp_return( $params ) {
		return $this->handle_send_otp( $params );
	}

	/**
	 * Handle send OTP.
	 *
	 * @param array $params Request parameters.
	 * @return array|WP_Error
	 */
	private function handle_send_otp( $params ) {
		$phone_number   = sanitize_text_field( wp_unslash( $params['phone_number'] ?? '' ) );
		$checkout_first = sanitize_text_field( wp_unslash( $params['first_name'] ?? '' ) );
		$checkout_last  = sanitize_text_field( wp_unslash( $params['last_name'] ?? '' ) );
		$checkout_email = sanitize_email( wp_unslash( $params['email'] ?? '' ) );

		if ( ! $phone_number ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Phone number is missing.', 'automation-web-platform' ),
			);
		}

		[ $numeric_phone, ] = $this->format_phone_number( $phone_number );

		if ( WAWP()->block_manager && ( WAWP()->block_manager->is_recipient_blocked( $phone_number ) || WAWP()->block_manager->is_recipient_blocked( $checkout_email ) ) ) {
			// Log the blocked attempt in the unified log.
			if ( class_exists( 'WAWP_Unified_Log' ) ) {
				$details = array(
					'phone'        => $phone_number,
					'email'        => $checkout_email,
					'message'      => 'Checkout OTP Blocked',
					'message_type' => 'Blocked OTP',
					'response'     => array(
						'status' => 'failed',
						'error'  => 'Recipient phone or email is blacklisted.',
					),
					'context'      => 'Checkout',
				);
				WAWP()->unified_log->add_activity_log(
					array(
						'phone'      => $phone_number,
						'email'      => $checkout_email,
						'event_type' => 'message',
						'gateway'    => 'checkout_otp',
						'log_status' => 'failed',
						'message'    => 'Blocked Checkout OTP: Recipient phone or email is blacklisted.',
						'details'    => $details,
					)
				);
			}
			return array(
				'success' => false,
				'message' => esc_html__( 'This phone number or email is blocked by the system.', 'automation-web-platform' ),
			);
		}

		if ( is_user_logged_in() ) {
			$this->sync_logged_in_user_data( $checkout_first, $checkout_last, $checkout_email, $phone_number );
		}

		$settings   = $this->get_settings();
		$otp_method = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_METHOD ];

		$challenge = WAWP_OTP_Service::get_instance()->send_challenge(
			( 'email' === $otp_method ? $checkout_email : $phone_number ),
			array(
				'method'   => $otp_method,
				'context'  => 'Checkout',
				'settings' => array_merge(
					$settings,
					array(
						'selected_instance'     => $settings[ WAWP_Settings_Registry::CHECKOUT_SELECTED_INSTANCE ] ?? '',
						'otp_subject_email'     => $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_SUBJECT_EMAIL ] ?? '',
						'otp_message_email'     => $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_MESSAGE_EMAIL ] ?? '',
						'otp_email_template_id' => $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_EMAIL_TEMPLATE_ID ] ?? '',
					)
				),
				'user_id'  => is_user_logged_in() ? get_current_user_id() : null,
			)
		);

		if ( ! $challenge['success'] ) {
			return $challenge;
		}

		if ( WC()->session ) {
			if ( ! empty( $challenge['auth_id'] ) ) {
				WC()->session->set( 'wawp_auth_id', $challenge['auth_id'] );
			}
			WC()->session->set( 'wawp_otp_transient', $challenge['transient_key'] );
		}

		return array(
			'success' => true,
			'message' => $challenge['message'],
			'data'    => array(
				'otp_transient'      => $challenge['transient_key'],
				'auth_id'            => $challenge['auth_id'] ?? '',
				'whatsapp_auth_type' => $challenge['whatsapp_auth_type'] ?? ( 'email' === $otp_method ? 'otp' : 'otp' ),
			),
		);
	}

	/**
	 * Verify OTP AJAX handler.
	 */
	public function verify_otp_ajax_handler() {
		WAWP_OTP_Service::get_instance()->handle_ajax_verify(
			array(
				'nonce_field'  => 'security',
				'nonce_action' => 'otp-ajax-nonce',
				'settings'     => $this->get_settings(),
			),
			array( $this, 'finalize_checkout_verification' )
		);
	}

	/**
	 * Verify OTP return.
	 *
	 * @param array $params Request parameters.
	 * @return array|WP_Error
	 */
	public function verify_otp_return( $params ) {
		if ( ! empty( $params['firebase'] ) ) {
			return $this->finalize_checkout_verification_return();
		}

		$settings   = $this->get_settings();
		$otp_method = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_METHOD ] ?? 'whatsapp';

		$verify_params = array_merge(
			$params,
			array(
				'settings' => $settings,
				'method'   => $otp_method,
			)
		);

		// For WhatsApp OTP - use API-based verification with auth_id (no transient needed).
		if ( 'whatsapp' === $otp_method && WC()->session ) {
			$auth_id = WC()->session->get( 'wawp_auth_id' );
			if ( ! empty( $auth_id ) && ! empty( $params['phone_number'] ) ) {
				$verify_params['auth_id'] = $auth_id;
				$verify_params['phone']   = $params['phone_number'];
			}
		}

		return WAWP_OTP_Service::get_instance()->verify_otp_return(
			$verify_params,
			array( $this, 'finalize_checkout_verification_return' )
		);
	}

	/**
	 * Finalize checkout verification.
	 *
	 * @param array $data Verification data.
	 */
	public function finalize_checkout_verification( $data ) {
		if ( WC()->session ) {
			WC()->session->set( 'otp_verified', true );
		}
		if ( is_user_logged_in() ) {
			WAWP()->user_manager->update_user_verification( get_current_user_id(), 'whatsapp', true );
		}

		if ( ( $data['method'] ?? '' ) === 'firebase' ) {
			$this->log_action(
				'success',
				'Firebase OTP verified successfully during checkout.',
				array(
					'recipient' => $data['phone'] ?? '',
					'user_id'   => is_user_logged_in() ? get_current_user_id() : 0,
					'gateway'   => 'firebase',
				),
				'Checkout - Firebase OTP Verification'
			);
		}

		$this->send_success( esc_html__( 'Verified successfully.', 'automation-web-platform' ), array( 'verified' => true ) );
	}

	/**
	 * Finalize checkout verification return.
	 *
	 * @return array
	 */
	public function finalize_checkout_verification_return() {
		if ( null === WC()->session && function_exists( 'WC' ) && isset( WC()->session ) ) {
			WC()->initialize_session();
		}
		if ( WC()->session ) {
			WC()->session->set( 'otp_verified', true );
		}
		if ( is_user_logged_in() ) {
			WAWP()->user_manager->update_user_verification( get_current_user_id(), 'whatsapp', true );
		}

		return array(
			'success'  => true,
			'message'  => esc_html__( 'Verified successfully.', 'automation-web-platform' ),
			'verified' => true,
			'data'     => array( 'verified' => true ),
		);
	}

	/**
	 * Verify Firebase OTP AJAX handler.
	 */
	public function verify_firebase_otp_ajax_handler() {
		WAWP_OTP_Service::get_instance()->handle_ajax_verify_firebase(
			array(
				'nonce_field'  => 'security',
				'nonce_action' => 'otp-ajax-nonce',
			),
			array( $this, 'finalize_checkout_verification' )
		);
	}

	/**
	 * AJAX resend OTP.
	 */
	public function ajax_resend_otp() {
		WAWP_OTP_Service::get_instance()->handle_ajax_resend(
			array(
				'nonce_field'     => 'security',
				'nonce_action'    => 'otp-ajax-nonce',
				'settings'        => $this->get_settings(),
				'context'         => 'Checkout',
				'transient_field' => 'wawp_otp_transient',
			)
		);
	}

	/**
	 * AJAX resend OTP return.
	 *
	 * @param array $params Request parameters.
	 * @return array|WP_Error
	 */
	public function ajax_resend_otp_return( $params ) {
		return WAWP_OTP_Service::get_instance()->resend_return(
			array_merge(
				$params,
				array(
					'settings'        => $this->get_settings(),
					'context'         => 'Checkout',
					'transient_field' => 'wawp_otp_transient',
				)
			)
		);
	}

	/**
	 * AJAX check auth status.
	 */
	public function ajax_check_auth_status() {
		$transient_key = '';
		if ( WC()->session ) {
			$transient_key = WC()->session->get( 'wawp_otp_transient' );
		}
		WAWP_OTP_Service::get_instance()->handle_ajax_check_status(
			array(
				'nonce_field'   => 'security',
				'nonce_action'  => 'otp-ajax-nonce',
				'settings'      => $this->get_settings(),
				'transient_key' => $transient_key,
			),
			array( $this, 'finalize_checkout_verification' )
		);
	}

	/**
	 * Check auth status return.
	 *
	 * @param array $params Request parameters.
	 * @return array|WP_Error
	 */
	public function check_auth_status_return( $params ) {
		$settings      = $this->get_settings();
		$otp_method    = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_METHOD ] ?? 'whatsapp';
		$transient_key = $params['transient_key'] ?? '';
		$auth_id       = $params['auth_id'] ?? '';

		// Get from session if not provided in params.
		if ( WC()->session ) {
			if ( empty( $transient_key ) ) {
				$transient_key = WC()->session->get( 'wawp_otp_transient' );
			}
			if ( empty( $auth_id ) ) {
				$auth_id = WC()->session->get( 'wawp_auth_id' );
			}
		}

		// For WhatsApp Interactive List - use API-based check directly (priority when auth_id is provided).
		if ( 'whatsapp' === $otp_method && ! empty( $auth_id ) ) {
			$wa_instance = WAWP_OTP_Service::get_instance()->get_active_whatsapp_instance( $settings );
			if ( ! $wa_instance ) {
				return array(
					'success'  => false,
					'verified' => false,
					'message'  => esc_html__( 'No active WhatsApp instance found.', 'automation-web-platform' ),
				);
			}

			$res = WAWP_Senders::check_auth_status( $wa_instance->instance_id, $wa_instance->access_token, $auth_id );

			if ( 'success' === $res['status'] ) {
				$response_data = $res['full_response'] ?? array();

				// Check if verified.
				if ( ! empty( $response_data['verified'] ) || ( isset( $response_data['status'] ) && 'verified' === $response_data['status'] ) ) {
					return $this->finalize_checkout_verification_return();
				}

				// Check if rejected.
				if ( isset( $response_data['status'] ) && 'rejected' === $response_data['status'] ) {
					return array(
						'success'  => true,
						'verified' => false,
						'status'   => 'rejected',
						'message'  => esc_html__( 'Verification was rejected.', 'automation-web-platform' ),
					);
				}

				// Still pending.
				return array(
					'success'  => true,
					'verified' => false,
					'status'   => 'pending',
					'pending'  => true,
				);
			}

			// API error.
			return array(
				'success'  => false,
				'verified' => false,
				'message'  => $res['message'] ?? esc_html__( 'Failed to check verification status.', 'automation-web-platform' ),
			);
		}

		// Fall back to transient-based status check (for email and legacy OTP).
		if ( ! empty( $transient_key ) ) {
			$status_params = array_merge(
				$params,
				array(
					'settings'      => $settings,
					'otp_transient' => $transient_key,
				)
			);
			return WAWP_OTP_Service::get_instance()->check_status_return(
				$status_params,
				array( $this, 'finalize_checkout_verification_return' )
			);
		}

		// No transient or auth_id available.
		return new WP_Error( 'missing_session', esc_html__( 'Missing session information.', 'automation-web-platform' ) );
	}

	/**
	 * Check if OTP verified.
	 */
	public function check_if_otp_verified() {
		$settings   = $this->get_settings();
		$enable_otp = $settings[ WAWP_Settings_Registry::CHECKOUT_ENABLE_OTP ];
		$mode       = $settings[ WAWP_Settings_Registry::CHECKOUT_OTP_MODE ];

		if ( 'yes' !== $enable_otp ) {
			return;
		}

		$disabled_payments     = (array) $settings[ WAWP_Settings_Registry::CHECKOUT_DISABLE_PAYMENT ];
		$chosen_payment_method = '';
		if ( WC()->session ) {
			$chosen_payment_method = WC()->session->get( 'chosen_payment_method' );
		}
		if ( in_array( $chosen_payment_method, $disabled_payments, true ) ) {
			return;
		}

		$disabled_shippings      = (array) $settings[ WAWP_Settings_Registry::CHECKOUT_DISABLE_SHIPPING ];
		$chosen_shipping_methods = array();
		if ( WC()->session ) {
			$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
		}
		if ( ! empty( $chosen_shipping_methods ) && is_array( $chosen_shipping_methods ) ) {
			$chosen_shipping = $chosen_shipping_methods[0] ?? '';
			if ( in_array( $chosen_shipping, $disabled_shippings, true ) ) {
				return;
			}
		}

		$logged_in = is_user_logged_in();
		if ( $logged_in ) {
			$u     = get_current_user_id();
			$info  = WAWP()->user_manager->get_user_info( $u );
			$nonce = isset( $_POST['woocommerce-process-checkout-nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ) : '';
			if ( wp_verify_nonce( $nonce, 'woocommerce-process_checkout' ) ) {
				[ $checkout_phone, ] = $this->format_phone_number( isset( $_POST['billing_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_phone'] ) ) : '' );

				if ( $info && ! empty( $checkout_phone ) && $checkout_phone !== $info->phone ) {
					WAWP()->db->reset_user_verification( $u );
					if ( WC()->session ) {
						WC()->session->set( 'otp_verified', false );
					}
				}
			}
		}

		switch ( $mode ) {
			case 'enable_for_all':
				$this->verify_or_abort();
				break;
			case 'enable_for_guests':
				if ( ! $logged_in ) {
					$this->verify_or_abort();
				}
				break;
			case 'enable_for_loggedin':
				if ( $logged_in ) {
					$this->verify_or_abort();
				}
				break;
		}
	}

	/**
	 * Verify or abort.
	 */
	private function verify_or_abort() {
		if ( is_user_logged_in() ) {
			$u    = get_current_user_id();
			$info = WAWP()->user_manager->get_user_info( $u );

			$nonce = isset( $_POST['woocommerce-process-checkout-nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['woocommerce-process-checkout-nonce'] ) ) : '';
			if ( wp_verify_nonce( $nonce, 'woocommerce-process_checkout' ) ) {
				[ $checkout_phone, ] = $this->format_phone_number( isset( $_POST['billing_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_phone'] ) ) : '' );

				if ( $info && ! empty( $checkout_phone ) && $checkout_phone !== $info->phone ) {
					wc_add_notice( esc_html__( 'You changed your phone number. Please verify OTP again.', 'automation-web-platform' ), 'error' );
					if ( WC()->session ) {
						WC()->session->set( 'otp_verified', false );
					}
					return;
				}
			}

			if ( $info && 'Verified' === $info->whatsapp_verified && 1 === (int) $info->otp_verification_whatsapp ) {
				return;
			}

			$otp_verified = false;
			if ( WC()->session ) {
				$otp_verified = WC()->session->get( 'otp_verified' );
			}

			if ( ! $otp_verified ) {
				wc_add_notice( esc_html__( 'Please verify the OTP before placing your order.', 'automation-web-platform' ), 'error' );
			}
		} else {
			$otp_verified = false;
			if ( WC()->session ) {
				$otp_verified = WC()->session->get( 'otp_verified' );
			}

			if ( ! $otp_verified ) {
				wc_add_notice( esc_html__( 'Please verify the OTP before placing your order.', 'automation-web-platform' ), 'error' );
			}
		}
	}

	/**
	 * Sync logged in user data.
	 *
	 * @param string $first First name.
	 * @param string $last  Last name.
	 * @param string $email Email.
	 * @param string $phone Phone.
	 */
	private function sync_logged_in_user_data( $first, $last, $email, $phone ) {
		$uid            = get_current_user_id();
		$checkout_email = sanitize_email( $email ? $email : '' );
		$checkout_first = sanitize_text_field( $first ? $first : '' );
		$checkout_last  = sanitize_text_field( $last ? $last : '' );

		$wp_user     = get_userdata( $uid );
		$wp_email    = $wp_user->user_email;
		$final_email = $checkout_email ? $checkout_email : $wp_email;

		wp_update_user(
			array(
				'ID'         => $uid,
				'user_email' => $final_email,
			)
		);

		if ( $checkout_first ) {
			update_user_meta( $uid, 'first_name', $checkout_first );
		}
		if ( $checkout_last ) {
			update_user_meta( $uid, 'last_name', $checkout_last );
		}

		WAWP()->user_manager->upsert_user_profile( $uid, $checkout_first, $checkout_last, $final_email, $phone );
		WAWP()->connector->sync_user_phone( $uid, $phone );
	}

	/**
	 * Get React settings data.
	 *
	 * @return array
	 */
	public function get_react_settings_data() {
		static $cached_result = null;
		if ( null !== $cached_result ) {
			return $cached_result;
		}

		$payment_gateways = array();
		if ( class_exists( 'WooCommerce' ) && isset( WC()->payment_gateways ) ) {
			foreach ( WC()->payment_gateways->payment_gateways() as $gateway_id => $gateway ) {
				if ( 'yes' === $gateway->enabled ) {
					$payment_gateways[] = array(
						'id'    => $gateway_id,
						'title' => $gateway->get_title(),
					);
				}
			}
		}

		$shipping_options = array();
		if ( class_exists( 'WC_Shipping_Zones' ) && is_object( WC() ) ) {
			$shipping_zones = WC_Shipping_Zones::get_zones();
			foreach ( $shipping_zones as $zone_data ) {
				$zone = new WC_Shipping_Zone( $zone_data['id'] );
				foreach ( $zone->get_shipping_methods() as $method ) {
					$method_id                        = method_exists( $method, 'get_method_id' ) ? $method->get_method_id() : ( $method->id ?? 'unknown' );
					$instance_id                      = $method->instance_id ?? 0;
					$id_instance                      = $method_id . ':' . $instance_id;
					$method_title                     = method_exists( $method, 'get_title' ) ? $method->get_title() : ( $method->title ?? 'Unknown' );
					$shipping_options[ $id_instance ] = $method_title . ' (' . $id_instance . ')';
				}
			}
			if ( class_exists( 'WC_Shipping_Zone' ) ) {
				$default_zone = new WC_Shipping_Zone( 0 );
				foreach ( $default_zone->get_shipping_methods() as $method ) {
					$method_id                        = method_exists( $method, 'get_method_id' ) ? $method->get_method_id() : ( $method->id ?? 'unknown' );
					$instance_id                      = $method->instance_id ?? 0;
					$id_instance                      = $method_id . ':' . $instance_id;
					$method_title                     = method_exists( $method, 'get_title' ) ? $method->get_title() : ( $method->title ?? 'Unknown' );
					$shipping_options[ $id_instance ] = $method_title . ' (' . $id_instance . ')';
				}
			}
		}

		$instances = array();
		foreach ( WAWP()->instance_manager->get_online_instances_cached() as $r ) {
			$instances[] = array(
				'instance_id' => $r->instance_id,
				'name'        => $r->name,
			);
		}

		$cache_key       = 'wawp_email_templates_checkout';
		$email_templates = wp_cache_get( $cache_key, 'wawp_database' );

		if ( false === $email_templates ) {
			global $wpdb;
			$table           = $wpdb->prefix . 'wawp_email_templates';
			$email_templates = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT id, name FROM %i', $table ), $cache_key, 'wawp_database', HOUR_IN_SECONDS );
			$email_templates = $email_templates ? $email_templates : array();
		}

		$raw_settings = $this->get_settings();
		$option_names = array(
			'enableOtp'                  => WAWP_Settings_Registry::CHECKOUT_ENABLE_OTP,
			'otpMode'                    => WAWP_Settings_Registry::CHECKOUT_OTP_MODE,
			'otpMsgTemplate'             => WAWP_Settings_Registry::CHECKOUT_OTP_MSG_TEMPLATE,
			'otpEmailTemplate'           => WAWP_Settings_Registry::CHECKOUT_OTP_EMAIL_TEMPLATE,
			'selectedInstance'           => WAWP_Settings_Registry::CHECKOUT_SELECTED_INSTANCE,
			'disablePayment'             => WAWP_Settings_Registry::CHECKOUT_DISABLE_PAYMENT,
			'disableShipping'            => WAWP_Settings_Registry::CHECKOUT_DISABLE_SHIPPING,
			'checkoutOtpTitle'           => WAWP_Settings_Registry::CHECKOUT_OTP_TITLE,
			'checkoutOtpBtnColor'        => WAWP_Settings_Registry::CHECKOUT_OTP_BTN_COLOR,
			'checkoutOtpBtnTextColor'    => WAWP_Settings_Registry::CHECKOUT_OTP_BTN_TEXT_COLOR,
			'checkoutOtpResendColor'     => WAWP_Settings_Registry::CHECKOUT_OTP_RESEND_COLOR,
			'checkoutOtpResendTextColor' => WAWP_Settings_Registry::CHECKOUT_OTP_RESEND_TEXT_COLOR,
			'checkoutOtpMethod'          => WAWP_Settings_Registry::CHECKOUT_OTP_METHOD,
			'checkoutColorTheme'         => WAWP_Settings_Registry::CHECKOUT_COLOR_THEME,
			'otpSubjectEmail'            => WAWP_Settings_Registry::CHECKOUT_OTP_SUBJECT_EMAIL,
			'otpEmailTemplateId'         => WAWP_Settings_Registry::CHECKOUT_OTP_EMAIL_TEMPLATE_ID,
			'whatsappAuthType'           => WAWP_Settings_Registry::CHECKOUT_WA_AUTH_TYPE,
			'whatsappOtpLangType'        => WAWP_Settings_Registry::CHECKOUT_WA_OTP_LANG_TYPE,
			'whatsappOtpCustomLang'      => WAWP_Settings_Registry::CHECKOUT_WA_OTP_CUSTOM_LANG,
			'whatsappOtpFooterEnabled'   => WAWP_Settings_Registry::CHECKOUT_WA_OTP_FOOT_EN,
			'whatsappOtpFooter'          => WAWP_Settings_Registry::CHECKOUT_WA_OTP_FOOT,
			'whatsappListTitle'          => WAWP_Settings_Registry::CHECKOUT_WA_LIST_TITLE,
			'whatsappListDesc'           => WAWP_Settings_Registry::CHECKOUT_WA_LIST_DESC,
			'whatsappListFooter'         => WAWP_Settings_Registry::CHECKOUT_WA_LIST_FOOTER,
			'whatsappListButton'         => WAWP_Settings_Registry::CHECKOUT_WA_LIST_BUTTON,
			'whatsappListItem1'          => WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM1,
			'whatsappListItem1Desc'      => WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM1_DESC,
			'whatsappListItem2'          => WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM2,
			'whatsappListItem2Desc'      => WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM2_DESC,
			'initialCooldown'            => WAWP_Settings_Registry::AUTH_INITIAL_COOLDOWN,
			'maxCooldown'                => WAWP_Settings_Registry::AUTH_MAX_COOLDOWN,
			'pollingInterval'            => WAWP_Settings_Registry::AUTH_POLLING_INTERVAL,
		);

		$mapped_options    = array();
		$registry_defaults = WAWP_Settings_Registry::get_defaults();
		foreach ( $option_names as $pretty => $db ) {
			$val = isset( $raw_settings[ $db ] ) ? $raw_settings[ $db ] : null;
			if ( null === $val || '' === $val ) {
				$val = $registry_defaults[ $db ] ?? null;
			}
			$mapped_options[ $pretty ] = $val;
			$mapped_options[ $db ]     = $val;
		}

		$result        = array(
			'options'         => $mapped_options,
			'optionNames'     => $option_names,
			'paymentGateways' => $payment_gateways,
			'shippingMethods' => $shipping_options,
			'instances'       => $instances,
			'emailTemplates'  => $email_templates,
			'availability'    => array(
				'whatsapp' => array(
					'available' => WAWP_Connector()->is_whatsapp_active(),
					'reason'    => ! WAWP_Connector()->is_whatsapp_active() ? esc_html__( 'No active WhatsApp instances found.', 'automation-web-platform' ) : '',
				),
				'email'    => array(
					'available' => WAWP_Connector()->is_email_sender_enabled(),
					'reason'    => ! WAWP_Connector()->is_email_sender_enabled() ? esc_html__( 'Email SMTP is not configured.', 'automation-web-platform' ) : '',
				),
				'firebase' => array(
					'available' => WAWP_Connector()->is_firebase_active(),
					'reason'    => ! WAWP_Connector()->is_firebase_active() ? esc_html__( 'Firebase credentials are not configured.', 'automation-web-platform' ) : '',
				),
			),
			'status_messages' => array(
				'checkout_active'          => esc_html__( 'Checkout verification is active.', 'automation-web-platform' ),
				'checkout_inactive'        => esc_html__( 'Checkout verification is paused.', 'automation-web-platform' ),
				'checkout_mode_all'        => esc_html__( 'System will verify all customers during checkout.', 'automation-web-platform' ),
				'checkout_mode_guests'     => esc_html__( 'Verification is restricted to guest checkouts only.', 'automation-web-platform' ),
				'checkout_mode_loggedin'   => esc_html__( 'Only logged-in users will be asked to verify.', 'automation-web-platform' ),
				/* translators: %d: number of payment gateways */
				'checkout_pay_excl'        => esc_html__( 'Verification skipped for %d selected payment gateways.', 'automation-web-platform' ),
				'checkout_pay_all'         => esc_html__( 'Verification applied to all payment methods.', 'automation-web-platform' ),
				/* translators: %d: number of shipping methods */
				'checkout_ship_excl'       => esc_html__( 'Verification skipped for %d selected shipping methods.', 'automation-web-platform' ),
				'checkout_ship_all'        => esc_html__( 'Verification applied to all shipping methods.', 'automation-web-platform' ),
				'checkout_method_whatsapp' => esc_html__( 'WhatsApp is set as the primary verification channel.', 'automation-web-platform' ),
				'checkout_method_email'    => esc_html__( 'Email is set as the primary verification channel.', 'automation-web-platform' ),
				'checkout_method_firebase' => esc_html__( 'Firebase SMS is set as the primary verification channel.', 'automation-web-platform' ),
				'checkout_guest_a'         => esc_html__( 'Guest checkout is permitted.', 'automation-web-platform' ),
				'checkout_guest_i'         => esc_html__( 'Users must log in to checkout.', 'automation-web-platform' ),
				'checkout_login_a'         => esc_html__( 'Login reminder is displayed on checkout page.', 'automation-web-platform' ),
				'checkout_login_i'         => esc_html__( 'Login reminder is hidden.', 'automation-web-platform' ),
				'checkout_signup_a'        => esc_html__( 'Account creation is enabled during checkout.', 'automation-web-platform' ),
				'checkout_signup_i'        => esc_html__( 'Account creation is disabled.', 'automation-web-platform' ),
				'checkout_pass_a'          => esc_html__( 'Passwords are automatically generated for new accounts.', 'automation-web-platform' ),
				'checkout_pass_i'          => esc_html__( 'Users must manually set their password.', 'automation-web-platform' ),
			),
			'i18n'            => array(
				'checkout_title'                 => esc_html__( 'Checkout Verification', 'automation-web-platform' ),
				'checkout_desc'                  => __( 'Verify customers WhatsApp at checkout to prevent fraud & fake orders.', 'automation-web-platform' ),
				'strategy_title'                 => esc_html__( 'Checkout OTP Strategy', 'automation-web-platform' ),
				'strategy_desc'                  => esc_html__( 'Verify numbers to reduce fake cash-on-delivery orders. Compatible with all major payment gateways.', 'automation-web-platform' ),
				'security_hardening'             => esc_html__( 'Security Hardening', 'automation-web-platform' ),
				'security_hardening_desc'        => esc_html__( 'Define exactly when and for whom the verification triggers.', 'automation-web-platform' ),
				'core_sync_title'                => esc_html__( 'WooCommerce Core Sync', 'automation-web-platform' ),
				'core_sync_desc'                 => esc_html__( 'Synchronize these settings with your WooCommerce defaults.', 'automation-web-platform' ),
				'visual_custom_title'            => esc_html__( 'Visual Customization', 'automation-web-platform' ),
				'visual_custom_desc'             => esc_html__( 'Ensure the verification popup matches your brand identity.', 'automation-web-platform' ),
				'whatsapp_label'                 => esc_html__( 'Whatsapp Web', 'automation-web-platform' ),
				'whatsapp_desc'                  => esc_html__( 'Ultra-fast delivery via Wawp engine', 'automation-web-platform' ),
				'email_label'                    => esc_html__( 'Email Magic Link', 'automation-web-platform' ),
				'email_desc'                     => esc_html__( 'Users receive a secure link in their inbox to authorize login instantly.', 'automation-web-platform' ),
				'firebase_label'                 => esc_html__( 'Firebase SMS', 'automation-web-platform' ),
				'firebase_desc'                  => esc_html__( 'Reliable Google infrastructure', 'automation-web-platform' ),
				'checkout_verification_title'    => esc_html__( 'Checkout OTP Verification', 'automation-web-platform' ),
				'checkout_verification_desc'     => esc_html__( 'Ensure order authenticity by verifying customer phone numbers or emails before order completion.', 'automation-web-platform' ),
				'general'                        => esc_html__( 'General', 'automation-web-platform' ),
				'methods'                        => esc_html__( 'Verification Methods', 'automation-web-platform' ),
				'exclusions'                     => __( 'Exclusions & Rules', 'automation-web-platform' ),
				'style'                          => __( 'Style & Branding', 'automation-web-platform' ),
				'shortcodes'                     => esc_html__( 'Shortcodes', 'automation-web-platform' ),
				'settingsSaved'                  => esc_html__( 'Checkout settings saved successfully!', 'automation-web-platform' ),
				'errorOccurred'                  => esc_html__( 'An error occurred while saving checkout settings.', 'automation-web-platform' ),
				'enable_checkout_otp_label'      => esc_html__( 'Enable Checkout Verification', 'automation-web-platform' ),
				'enable_checkout_otp_desc'       => esc_html__( 'Require users to verify their identity via OTP during the checkout process.', 'automation-web-platform' ),
				'otp_mode_label'                 => esc_html__( 'Verification Enforcement', 'automation-web-platform' ),
				'otp_mode_desc'                  => esc_html__( 'Choose who needs to verify their identity during checkout.', 'automation-web-platform' ),
				'otp_method_label'               => esc_html__( 'Primary Verification Method', 'automation-web-platform' ),
				'otp_method_desc'                => esc_html__( 'Select the default channel for sending OTP codes during checkout.', 'automation-web-platform' ),
				'payment_exclusions_title'       => esc_html__( 'Payment Gateway Exclusions', 'automation-web-platform' ),
				'payment_exclusions_desc'        => __( 'Disable OTP verification for specific payment methods (e.g., Credit Cards).', 'automation-web-platform' ),
				'shipping_exclusions_title'      => esc_html__( 'Shipping Method Exclusions', 'automation-web-platform' ),
				'shipping_exclusions_desc'       => esc_html__( 'Bypass OTP verification for trusted shipping carriers or local pickup.', 'automation-web-platform' ),
				'design_customization_title'     => __( 'Popup Design & Customization', 'automation-web-platform' ),
				'design_customization_desc'      => esc_html__( 'Personalize the OTP verification popup to match your store’s branding.', 'automation-web-platform' ),
				'chooseWaSender'                 => esc_html__( 'Choose WhatsApp Sender', 'automation-web-platform' ),
				'chooseWaSenderDesc'             => esc_html__( 'Select the WhatsApp number that will be used to send messages for this feature.', 'automation-web-platform' ),
				'preferredChannel'               => esc_html__( 'Preferred Verification Channel', 'automation-web-platform' ),
				'msg_config_label'               => esc_html__( 'Message Configuration', 'automation-web-platform' ),
				'force_lang_label'               => esc_html__( 'Force Language', 'automation-web-platform' ),
				'enable_custom_footer_label'     => esc_html__( 'Enable Custom Footer', 'automation-web-platform' ),
				'list_ui_label'                  => esc_html__( 'List Interface Design', 'automation-web-platform' ),
				'preferred_channel_label'        => esc_html__( 'Preferred Verification Channel', 'automation-web-platform' ),
				'standard_otp_label'             => esc_html__( 'Standard OTP', 'automation-web-platform' ),
				'standard_otp_desc'              => esc_html__( '6-digit code via Message', 'automation-web-platform' ),
				'interactive_list_label'         => esc_html__( 'Interactive List', 'automation-web-platform' ),
				'interactive_list_desc'          => esc_html__( 'One-tap Verify/Reject', 'automation-web-platform' ),
				'message_config_label'           => esc_html__( 'Message Configuration', 'automation-web-platform' ),
				'force_language_label'           => esc_html__( 'Force Language', 'automation-web-platform' ),
				'list_interface_design_label'    => esc_html__( 'List Interface Design', 'automation-web-platform' ),
				'list_title_field_label'         => esc_html__( 'List Title', 'automation-web-platform' ),
				'main_description_field_label'   => esc_html__( 'Main Description', 'automation-web-platform' ),
				'item1_success_action_label'     => esc_html__( 'Item 1 (Success Action)', 'automation-web-platform' ),
				'action_title_field_label'       => esc_html__( 'Action Title', 'automation-web-platform' ),
				'action_description_field_label' => esc_html__( 'Action Description', 'automation-web-platform' ),
				'item2_reject_action_label'      => esc_html__( 'Item 2 (Reject Action)', 'automation-web-platform' ),
				'selection_button_field_label'   => esc_html__( 'Selection Button', 'automation-web-platform' ),
				'bottom_footer_field_label'      => esc_html__( 'Bottom Footer', 'automation-web-platform' ),
				'select_language_label'          => esc_html__( 'Select Language', 'automation-web-platform' ),
				'footer_content_label'           => esc_html__( 'Footer Content', 'automation-web-platform' ),
				'selectInstance'                 => esc_html__( '— Select Instance —', 'automation-web-platform' ),
				'all_gateways'                   => esc_html__( 'All Gateways Included', 'automation-web-platform' ),
				'all_shipping'                   => esc_html__( 'All Shipping Methods Included', 'automation-web-platform' ),
				'whatsapp_auth_engine'           => esc_html__( 'WhatsApp Auth Engine', 'automation-web-platform' ),
				'badge_active'                   => esc_html__( 'Active', 'automation-web-platform' ),
				'woo_guest_checkout_label'       => esc_html__( 'Guest Checkout', 'automation-web-platform' ),
				'woo_guest_checkout_desc'        => esc_html__( 'Allow orders without accounts', 'automation-web-platform' ),
				'woo_login_reminder_label'       => esc_html__( 'Login Reminder', 'automation-web-platform' ),
				'woo_login_reminder_desc'        => esc_html__( 'Help returning customers', 'automation-web-platform' ),
				'woo_account_creation_label'     => esc_html__( 'Account Creation', 'automation-web-platform' ),
				'woo_account_creation_desc'      => esc_html__( 'Build customer loyalty', 'automation-web-platform' ),
				'woo_password_setup_label'       => esc_html__( 'Password Setup', 'automation-web-platform' ),
				'woo_password_setup_desc'        => esc_html__( 'Secure auto-generation', 'automation-web-platform' ),
				'popup_header_label'             => esc_html__( 'Popup Header Text', 'automation-web-platform' ),
				'popup_header_desc'              => esc_html__( 'Title displayed at top of verification popup. Default: "Confirm your order"', 'automation-web-platform' ),
				'branding_presets_label'         => esc_html__( 'Branding Presets', 'automation-web-platform' ),
				'preset_default'                 => esc_html__( 'Default', 'automation-web-platform' ),
				'preset_teal'                    => esc_html__( 'Teal', 'automation-web-platform' ),
				'preset_ocean'                   => esc_html__( 'Ocean', 'automation-web-platform' ),
				'preset_midnight'                => esc_html__( 'Midnight', 'automation-web-platform' ),
				'preset_sunset'                  => esc_html__( 'Sunset', 'automation-web-platform' ),
				'preset_minimal'                 => esc_html__( 'Minimal', 'automation-web-platform' ),
				'verification_button_label'      => esc_html__( 'Verification Button', 'automation-web-platform' ),
				'background_label'               => esc_html__( 'Background', 'automation-web-platform' ),
				'text_color_label'               => esc_html__( 'Text Color', 'automation-web-platform' ),
				'confirm_order_label'            => esc_html__( 'Confirm Order', 'automation-web-platform' ),
				'retry_logic_label'              => esc_html__( 'Retry Logic Actions', 'automation-web-platform' ),
				'resend_code_label'              => esc_html__( 'Resend Verification Code', 'automation-web-platform' ),
				'checkout_otp_title'             => esc_html__( 'Secure Verification', 'automation-web-platform' ),
				'checkout_otp_desc'              => esc_html__( 'Please confirm your identity to complete checkout.', 'automation-web-platform' ),
				'whatsapp_list_footer'           => esc_html__( 'Secure authentication via Wawp', 'automation-web-platform' ),
				'whatsapp_list_button'           => esc_html__( 'Choose Action', 'automation-web-platform' ),
				'whatsapp_list_item1_desc'       => esc_html__( 'Verify this transaction', 'automation-web-platform' ),
				'whatsapp_list_item1'            => esc_html__( 'Approve Order', 'automation-web-platform' ),
				'whatsapp_list_item2_desc'       => esc_html__( 'Cancel this request', 'automation-web-platform' ),
				'whatsapp_list_item2'            => esc_html__( 'Reject & Cancel', 'automation-web-platform' ),
				'auto_site_locale'               => esc_html__( 'Auto (Site Locale)', 'automation-web-platform' ),
				'user_context_dynamic'           => esc_html__( 'User Context (Dynamic)', 'automation-web-platform' ),
				'forced_manual_selection'        => esc_html__( 'Forced (Manual Selection)', 'automation-web-platform' ),
				'lang_arabic'                    => esc_html__( 'Arabic', 'automation-web-platform' ),
				'lang_english'                   => esc_html__( 'English', 'automation-web-platform' ),
				'lang_spanish'                   => esc_html__( 'Spanish', 'automation-web-platform' ),
				'lang_french'                    => esc_html__( 'French', 'automation-web-platform' ),
				'lang_portuguese'                => esc_html__( 'Portuguese', 'automation-web-platform' ),
				'lang_indonesian'                => esc_html__( 'Indonesian', 'automation-web-platform' ),
				'lang_russian'                   => esc_html__( 'Russian', 'automation-web-platform' ),
				'lang_turkish'                   => esc_html__( 'Turkish', 'automation-web-platform' ),
				'lang_german'                    => esc_html__( 'German', 'automation-web-platform' ),
			),
		);
		$cached_result = $result;
		return $result;
	}

	/**
	 * Get settings.
	 *
	 * @return array
	 */
	public function get_settings() {
		static $cache = null;
		if ( null !== $cache ) {
			return $cache;
		}

		$keys = array(
			WAWP_Settings_Registry::CHECKOUT_ENABLE_OTP,
			WAWP_Settings_Registry::CHECKOUT_OTP_MODE,
			WAWP_Settings_Registry::CHECKOUT_OTP_MSG_TEMPLATE,
			WAWP_Settings_Registry::CHECKOUT_OTP_EMAIL_TEMPLATE,
			WAWP_Settings_Registry::CHECKOUT_SELECTED_INSTANCE,
			WAWP_Settings_Registry::CHECKOUT_DISABLE_PAYMENT,
			WAWP_Settings_Registry::CHECKOUT_DISABLE_SHIPPING,
			WAWP_Settings_Registry::CHECKOUT_OTP_TITLE,
			WAWP_Settings_Registry::CHECKOUT_OTP_BTN_COLOR,
			WAWP_Settings_Registry::CHECKOUT_OTP_BTN_TEXT_COLOR,
			WAWP_Settings_Registry::CHECKOUT_OTP_RESEND_COLOR,
			WAWP_Settings_Registry::CHECKOUT_OTP_RESEND_TEXT_COLOR,
			WAWP_Settings_Registry::CHECKOUT_OTP_METHOD,
			WAWP_Settings_Registry::CHECKOUT_COLOR_THEME,
			WAWP_Settings_Registry::CHECKOUT_OTP_SUBJECT_EMAIL,
			WAWP_Settings_Registry::CHECKOUT_OTP_EMAIL_TEMPLATE_ID,
			WAWP_Settings_Registry::CHECKOUT_WA_AUTH_TYPE,
			WAWP_Settings_Registry::CHECKOUT_WA_OTP_LANG_TYPE,
			WAWP_Settings_Registry::CHECKOUT_WA_OTP_CUSTOM_LANG,
			WAWP_Settings_Registry::CHECKOUT_WA_OTP_FOOT_EN,
			WAWP_Settings_Registry::CHECKOUT_WA_OTP_FOOT,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_TITLE,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_DESC,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_FOOTER,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_BUTTON,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM1,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM1_DESC,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM2,
			WAWP_Settings_Registry::CHECKOUT_WA_LIST_ITEM2_DESC,
			WAWP_Settings_Registry::AUTH_INITIAL_COOLDOWN,
			WAWP_Settings_Registry::AUTH_MAX_COOLDOWN,
			WAWP_Settings_Registry::AUTH_POLLING_INTERVAL,
			WAWP_Settings_Registry::AUTH_EMAIL_DOMAINS,
		);

		$registry_defaults = WAWP_Settings_Registry::get_defaults();
		$settings          = array();
		$array_keys        = array(
			WAWP_Settings_Registry::CHECKOUT_DISABLE_PAYMENT,
			WAWP_Settings_Registry::CHECKOUT_DISABLE_SHIPPING,
			WAWP_Settings_Registry::AUTH_EMAIL_DOMAINS,
		);
		foreach ( $keys as $key ) {
			$default = $registry_defaults[ $key ] ?? '';
			$val     = $this->get_wawp_setting( $key, $default );
			if ( in_array( $key, $array_keys, true ) ) {
				$val = $this->from_db( $val );
			} elseif ( is_array( $val ) || is_object( $val ) ) {
					$val = '';
			} elseif ( is_string( $val ) && ( '<br>' === $val || '<br/>' === $val || '<br />' === $val ) ) {
				$val = '';
			}
			if ( null === $val || '' === $val ) {
				$val = $default;
			}
			if ( WAWP_Settings_Registry::CHECKOUT_OTP_METHOD === $key && 'email' === $val ) {
				$val = 'whatsapp';
			}
			$settings[ $key ] = $val;
		}

		$cache = $settings;
		return $cache;
	}

	/**
	 * Update settings.
	 *
	 * @param array $data Settings data.
	 */
	public function update_settings( $data ) {
		foreach ( $data as $key => $value ) {
			$final_key = $key;
			if ( 'wawp_selected_instance' === $key ) {
				$final_key = WAWP_Settings_Registry::CHECKOUT_SELECTED_INSTANCE;
			}
			$this->update_wawp_setting( $final_key, $value );
		}
	}
}

new WAWP_Checkout_Otp();
