<?php
/**
 * Custom Pages Settings.
 *
 * @package automation-web-platform
 */

if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class WAWP_Custom_Pages_Settings
 */
class WAWP_Custom_Pages_Settings {
	use WAWP_Security_Trait;
	use WAWP_Settings_Handler;

	/**
	 * Admin texts for i18n.
	 *
	 * @var array
	 */
	private $admin_texts;

	/**
	 * Option group.
	 *
	 * @var string
	 */
	private $option_group = 'wawp_settings_group';

	/**
	 * Login page option.
	 *
	 * @var string
	 */
	private $login_page_option = WAWP_Settings_Registry::LOGIN_PAGE_ID;

	/**
	 * Signup page option.
	 *
	 * @var string
	 */
	private $signup_page_option = WAWP_Settings_Registry::SIGNUP_PAGE_ID;

	/**
	 * Fast login page option.
	 *
	 * @var string
	 */
	private $fast_login_page_option = WAWP_Settings_Registry::FAST_LOGIN_PAGE_ID;

	/**
	 * Replace WC forms option.
	 *
	 * @var string
	 */
	private $replace_wc_forms_option = WAWP_Settings_Registry::REPLACE_WC_FORMS;

	/**
	 * Show phone bar option.
	 *
	 * @var string
	 */
	private $show_phone_bar_option = WAWP_Settings_Registry::PHONE_BAR_IN_ACCOUNT;

	/**
	 * Replace WC checkout login option.
	 *
	 * @var string
	 */
	private $replace_wc_checkout_login_option = WAWP_Settings_Registry::REPLACE_WC_CHECKOUT_LOGIN;

	/**
	 * Redirect WP login option.
	 *
	 * @var string
	 */
	private $redirect_wp_login_option = WAWP_Settings_Registry::REDIRECT_WP_LOGIN;

	/**
	 * Redirect My Account option.
	 *
	 * @var string
	 */
	private $redirect_my_account_option = WAWP_Settings_Registry::REDIRECT_MY_ACCOUNT;

	/**
	 * Lock site option.
	 *
	 * @var string
	 */
	private $lock_site_option = WAWP_Settings_Registry::PHONE_BAR_LOCK_SITE;

	/**
	 * Show phone bar globally option.
	 *
	 * @var string
	 */
	private $show_phone_bar_global_option = WAWP_Settings_Registry::PHONE_BAR_GLOBALLY;

	// New text options.

	/**
	 * Phone bar intro option.
	 *
	 * @var string
	 */
	private $phone_bar_intro_option = WAWP_Settings_Registry::PHONE_BAR_INTRO;

	/**
	 * Phone bar outro option.
	 *
	 * @var string
	 */
	private $phone_bar_outro_option = WAWP_Settings_Registry::PHONE_BAR_OUTRO;

	/**
	 * OTP template option.
	 *
	 * @var string
	 */
	private $otp_template_option = WAWP_Settings_Registry::PHONE_OTP_TEMPLATE;

	/**
	 * OTP method option.
	 *
	 * @var string
	 */
	private $otp_method_option = WAWP_Settings_Registry::PHONE_BAR_OTP_METHOD;

	// WhatsApp Auth Options.

	/**
	 * WhatsApp auth type option.
	 *
	 * @var string
	 */
	private $wa_auth_type_option = WAWP_Settings_Registry::WA_AUTH_TYPE;

	/**
	 * WhatsApp OTP lang type option.
	 *
	 * @var string
	 */
	private $wa_otp_lang_type_option = WAWP_Settings_Registry::WA_OTP_LANG_TYPE;

	/**
	 * WhatsApp OTP custom lang option.
	 *
	 * @var string
	 */
	private $wa_otp_custom_lang_option = WAWP_Settings_Registry::WA_OTP_CUSTOM_LANG;

	/**
	 * WhatsApp OTP footer enabled option.
	 *
	 * @var string
	 */
	private $wa_otp_footer_enabled_option = WAWP_Settings_Registry::WA_OTP_FOOTER_ENABLED;

	/**
	 * WhatsApp OTP footer option.
	 *
	 * @var string
	 */
	private $wa_otp_footer_option = WAWP_Settings_Registry::WA_OTP_FOOTER;

	/**
	 * WhatsApp list title option.
	 *
	 * @var string
	 */
	private $wa_list_title_option = WAWP_Settings_Registry::WA_LIST_TITLE;

	/**
	 * WhatsApp list description option.
	 *
	 * @var string
	 */
	private $wa_list_desc_option = WAWP_Settings_Registry::WA_LIST_DESC;

	/**
	 * WhatsApp list footer option.
	 *
	 * @var string
	 */
	private $wa_list_footer_option = WAWP_Settings_Registry::WA_LIST_FOOTER;

	/**
	 * WhatsApp list button option.
	 *
	 * @var string
	 */
	private $wa_list_button_option = WAWP_Settings_Registry::WA_LIST_BUTTON;

	/**
	 * WhatsApp list item1 option.
	 *
	 * @var string
	 */
	private $wa_list_item1_option = WAWP_Settings_Registry::WA_LIST_ITEM1;

	/**
	 * WhatsApp list item1 description option.
	 *
	 * @var string
	 */
	private $wa_list_item1_desc_option = WAWP_Settings_Registry::WA_LIST_ITEM1_DESC;

	/**
	 * WhatsApp list item2 option.
	 *
	 * @var string
	 */
	private $wa_list_item2_option = WAWP_Settings_Registry::WA_LIST_ITEM2;

	/**
	 * WhatsApp list item2 description option.
	 *
	 * @var string
	 */
	private $wa_list_item2_desc_option = WAWP_Settings_Registry::WA_LIST_ITEM2_DESC;

	/**
	 * Singleton instance.
	 *
	 * @var WAWP_Custom_Pages_Settings|null
	 */
	private static $instance = null;

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

		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		// setup_admin_texts will be called on demand to ensure translations are ready.
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'template_redirect', array( $this, 'handle_redirects' ) );
		add_action( 'login_init', array( $this, 'handle_login_page_redirect' ) );
		add_action( 'init', array( $this, 'setup_integrations' ) );
		add_action( 'admin_post_wawp_create_login_page', array( $this, 'handle_create_login_page' ) );
		add_action( 'admin_post_wawp_create_signup_page', array( $this, 'handle_create_signup_page' ) );
		add_action( 'admin_post_wawp_create_fast_login_page', array( $this, 'handle_create_fast_login_page' ) );

		// Redirection Safety Links.
		add_action( 'update_option_wawp_redirect_wp_login', array( $this, 'on_redirect_wp_login_update' ), 10, 2 );
		add_action( 'add_option_wawp_redirect_wp_login', array( $this, 'on_redirect_wp_login_add' ), 10, 2 );
		add_action( 'update_option_wawp_redirect_my_account', array( $this, 'on_redirect_my_account_update' ), 10, 2 );
		add_action( 'add_option_wawp_redirect_my_account', array( $this, 'on_redirect_my_account_add' ), 10, 2 );
		add_action( 'init', array( $this, 'check_safety_bypass_links' ) );
		add_filter( 'login_message', array( $this, 'add_login_bypass_message' ) );
		add_action( 'wp', array( $this, 'add_wc_bypass_message' ) );

		// Temporary Admin Access Link authentication & safety hooks.
		add_action( 'init', array( $this, 'handle_temp_access_auth' ), 1 ); // Run very early.
		add_action( 'admin_notices', array( $this, 'render_temp_access_safety_banner' ) );
		add_action( 'admin_init', array( $this, 'enforce_temp_access_restrictions' ) );
		add_action( 'wp_logout', array( $this, 'revoke_temp_link_on_logout' ) );
		add_action( 'wawp_cleanup_expired_temp_links', array( $this, 'cleanup_expired_temp_links_cron' ) );

		if ( ! wp_next_scheduled( 'wawp_cleanup_expired_temp_links' ) ) {
			wp_schedule_event( time(), 'hourly', 'wawp_cleanup_expired_temp_links' );
		}
	}

	/**
	 * Get data for React settings.
	 *
	 * @return array Settings data.
	 */
	public function get_react_settings_data() {
		$this->setup_admin_texts();
		$pages         = get_pages( array( 'post_status' => 'publish' ) );
		$pages_options = array();
		foreach ( $pages as $p ) {
			$pages_options[] = array(
				'id'    => $p->ID,
				'title' => $p->post_title,
				'url'   => get_permalink( $p->ID ),
				'edit'  => get_edit_post_link( $p->ID ),
			);
		}

		$tab_input   = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_SPECIAL_CHARS );
		$current_tab = $tab_input ? sanitize_key( wp_unslash( $tab_input ) ) : 'tab-login-signup-pages';
		// Fetch editable roles.
		if ( ! function_exists( 'get_editable_roles' ) ) {
			require_once ABSPATH . 'wp-admin/includes/user.php';
		}
		$editable_roles = get_editable_roles();
		$roles_options  = array();
		foreach ( $editable_roles as $role_key => $role_details ) {
			$roles_options[] = array(
				'value' => $role_key,
				'label' => translate_user_role( $role_details['name'] ),
			);
		}

		// Fetch all users.
		$users         = get_users();
		$users_options = array();
		foreach ( $users as $u ) {
			$users_options[] = array(
				'value' => (string) $u->ID,
				'label' => $u->user_login . ' (' . $u->display_name . ')',
			);
		}

		return array(
			'currentTab'         => $current_tab,
			'pages'              => $pages_options,
			'users'              => $users_options,
			'roles'              => $roles_options,
			'options'            => array(
				$this->login_page_option                => $this->get_wawp_setting( $this->login_page_option ),
				$this->signup_page_option               => $this->get_wawp_setting( $this->signup_page_option ),
				$this->fast_login_page_option           => $this->get_wawp_setting( $this->fast_login_page_option ),
				$this->redirect_wp_login_option         => $this->get_wawp_setting( $this->redirect_wp_login_option, 0 ),
				$this->redirect_my_account_option       => $this->get_wawp_setting( $this->redirect_my_account_option, 0 ),
				$this->replace_wc_forms_option          => $this->get_wawp_setting( $this->replace_wc_forms_option, 0 ),
				$this->show_phone_bar_option            => $this->get_wawp_setting( $this->show_phone_bar_option, 0 ),
				$this->replace_wc_checkout_login_option => $this->get_wawp_setting( $this->replace_wc_checkout_login_option, 0 ),
				$this->lock_site_option                 => $this->get_wawp_setting( $this->lock_site_option, 0 ),
				$this->show_phone_bar_global_option     => $this->get_wawp_setting( $this->show_phone_bar_global_option, 0 ),
				$this->phone_bar_intro_option           => ( 'Confirm your number' === $this->get_wawp_setting( $this->phone_bar_intro_option, 'Confirm your number' ) ) ? __( 'Confirm your number', 'automation-web-platform' ) : $this->get_wawp_setting( $this->phone_bar_intro_option ),
				$this->phone_bar_outro_option           => ( 'to get full access and login via WhatsApp OTP.' === $this->get_wawp_setting( $this->phone_bar_outro_option, 'to get full access and login via WhatsApp OTP.' ) ) ? __( 'to get full access and login via WhatsApp OTP.', 'automation-web-platform' ) : $this->get_wawp_setting( $this->phone_bar_outro_option ),
				$this->otp_template_option              => $this->get_wawp_setting( $this->otp_template_option, 'Your OTP code is: {{otp}}' ),
				$this->otp_method_option                => $this->get_wawp_setting( $this->otp_method_option, 'whatsapp' ),
				// WhatsApp Auth.
				$this->wa_auth_type_option              => $this->get_wawp_setting( $this->wa_auth_type_option, 'otp' ),
				$this->wa_otp_lang_type_option          => $this->get_wawp_setting( $this->wa_otp_lang_type_option, 'site' ),
				$this->wa_otp_custom_lang_option        => $this->get_wawp_setting( $this->wa_otp_custom_lang_option, 'ar' ),
				$this->wa_otp_footer_enabled_option     => $this->get_wawp_setting( $this->wa_otp_footer_enabled_option, 0 ),
				$this->wa_otp_footer_option             => $this->get_wawp_setting( $this->wa_otp_footer_option, '' ),
				$this->wa_list_title_option             => ( 'Secure Verification' === $this->get_wawp_setting( $this->wa_list_title_option, 'Secure Verification' ) ) ? __( 'Secure Verification', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_title_option ),
				$this->wa_list_desc_option              => ( 'Please confirm your identity to continue.' === $this->get_wawp_setting( $this->wa_list_desc_option, 'Please confirm your identity to continue.' ) ) ? __( 'Please confirm your identity to continue.', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_desc_option ),
				$this->wa_list_footer_option            => ( 'Secure authentication via Wawp' === $this->get_wawp_setting( $this->wa_list_footer_option, 'Secure authentication via Wawp' ) ) ? __( 'Secure authentication via Wawp', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_footer_option ),
				$this->wa_list_button_option            => ( 'Choose Action' === $this->get_wawp_setting( $this->wa_list_button_option, 'Choose Action' ) ) ? __( 'Choose Action', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_button_option ),
				$this->wa_list_item1_option             => ( 'Approve Request' === $this->get_wawp_setting( $this->wa_list_item1_option, 'Approve Request' ) ) ? __( 'Approve Request', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_item1_option ),
				$this->wa_list_item1_desc_option        => ( 'Verify this is you' === $this->get_wawp_setting( $this->wa_list_item1_desc_option, 'Verify this is you' ) ) ? __( 'Verify this is you', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_item1_desc_option ),
				$this->wa_list_item2_option             => ( 'Reject & Stop' === $this->get_wawp_setting( $this->wa_list_item2_option, 'Reject & Stop' ) ) ? __( 'Reject & Stop', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_item2_option ),
				$this->wa_list_item2_desc_option        => ( 'Cancel this attempt' === $this->get_wawp_setting( $this->wa_list_item2_desc_option, 'Cancel this attempt' ) ) ? __( 'Cancel this attempt', 'automation-web-platform' ) : $this->get_wawp_setting( $this->wa_list_item2_desc_option ),
				'title'                                 => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_TITLE, 'Secure Login' ),
				'description'                           => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_DESC, 'Confirm your identity to access your account.' ),
				'logo'                                  => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_LOGO, '' ),
				'color_theme'                           => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_COLOR_THEME, 'default' ),
				'custom_css'                            => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_CUSTOM_CSS, '' ),
				'custom_shortcode'                      => $this->from_db( $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_CUSTOM_SHORTCODE, '[]' ) ),
				'button_color'                          => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_BUTTON_COLOR, '#004449' ),
				'button_text_color'                     => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_BUTTON_TEXT_COLOR, '#ffffff' ),
				'input_style'                           => $this->get_wawp_setting( WAWP_Settings_Registry::AUTH_INPUT_STYLE, 'default' ),
				'wawp_temp_access_notify_enabled'       => $this->get_wawp_setting( 'wawp_temp_access_notify_enabled', 0 ),
				'wawp_temp_access_notify_admin_ids'     => $this->get_wawp_setting( 'wawp_temp_access_notify_admin_ids', '' ),
			),
			'optionNames'        => array(
				'loginPage'                => $this->login_page_option,
				'signupPage'               => $this->signup_page_option,
				'fastLoginPage'            => $this->fast_login_page_option,
				'redirectWpLogin'          => $this->redirect_wp_login_option,
				'redirectMyAccount'        => $this->redirect_my_account_option,
				'replaceWcForms'           => $this->replace_wc_forms_option,
				'showPhoneBar'             => $this->show_phone_bar_option,
				'tempAccessNotifyEnabled'  => 'wawp_temp_access_notify_enabled',
				'tempAccessNotifyAdminIds' => 'wawp_temp_access_notify_admin_ids',
				'replaceWcCheckoutLogin'   => $this->replace_wc_checkout_login_option,
				'lockSite'                 => $this->lock_site_option,
				'showPhoneBarGlobal'       => $this->show_phone_bar_global_option,
				'phoneBarIntro'            => $this->phone_bar_intro_option,
				'phoneBarOutro'            => $this->phone_bar_outro_option,
				'otpTemplate'              => $this->otp_template_option,
				'otpMethod'                => $this->otp_method_option,
				// WhatsApp Auth.
				'whatsappAuthType'         => $this->wa_auth_type_option,
				'whatsappOtpLangType'      => $this->wa_otp_lang_type_option,
				'whatsappOtpCustomLang'    => $this->wa_otp_custom_lang_option,
				'whatsappOtpFooterEnabled' => $this->wa_otp_footer_enabled_option,
				'whatsappOtpFooter'        => $this->wa_otp_footer_option,
				'whatsappListTitle'        => $this->wa_list_title_option,
				'whatsappListDesc'         => $this->wa_list_desc_option,
				'whatsappListFooter'       => $this->wa_list_footer_option,
				'whatsappListButton'       => $this->wa_list_button_option,
				'whatsappListItem1'        => $this->wa_list_item1_option,
				'whatsappListItem1Desc'    => $this->wa_list_item1_desc_option,
				'buttonColor'              => WAWP_Settings_Registry::AUTH_BUTTON_COLOR,
				'buttonTextColor'          => WAWP_Settings_Registry::AUTH_BUTTON_TEXT_COLOR,
				'inputStyle'               => WAWP_Settings_Registry::AUTH_INPUT_STYLE,
				'whatsappListItem2'        => $this->wa_list_item2_option,
				'whatsappListItem2Desc'    => $this->wa_list_item2_desc_option,
				'title'                    => WAWP_Settings_Registry::AUTH_TITLE,
				'description'              => WAWP_Settings_Registry::AUTH_DESC,
				'logo'                     => WAWP_Settings_Registry::AUTH_LOGO,
				'color_theme'              => WAWP_Settings_Registry::AUTH_COLOR_THEME,
				'custom_css'               => WAWP_Settings_Registry::AUTH_CUSTOM_CSS,
				'custom_shortcode'         => WAWP_Settings_Registry::AUTH_CUSTOM_SHORTCODE,
			),
			'safety'             => array(
				'redirectWpLoginKey'   => get_option( 'wawp_redirect_wp_login_safety_key', '' ),
				'redirectWpLoginUrl'   => get_option( 'wawp_redirect_wp_login_safety_key' ) ? home_url( '?wawp_disable_wp_login=' . get_option( 'wawp_redirect_wp_login_safety_key' ) ) : '',
				'redirectMyAccountKey' => get_option( 'wawp_redirect_my_account_safety_key', '' ),
				'redirectMyAccountUrl' => get_option( 'wawp_redirect_my_account_safety_key' ) ? home_url( '?wawp_disable_my_account=' . get_option( 'wawp_redirect_my_account_safety_key' ) ) : '',
			),
			'nonce'              => wp_create_nonce( 'wp_rest' ),
			'restUrl'            => esc_url_raw( rest_url( 'wawp/v1' ) ),
			'createUrls'         => array(
				'login'      => admin_url( 'admin-post.php?action=wawp_create_login_page&_wpnonce=' . wp_create_nonce( 'wawp_create_login_page_nonce' ) ),
				'signup'     => admin_url( 'admin-post.php?action=wawp_create_signup_page&_wpnonce=' . wp_create_nonce( 'wawp_create_signup_page_nonce' ) ),
				'fast_login' => admin_url( 'admin-post.php?action=wawp_create_fast_login_page&_wpnonce=' . wp_create_nonce( 'wawp_create_fast_login_page_nonce' ) ),
			),
			'i18n'               => $this->admin_texts,
			'status_messages'    => $this->get_status_messages(),
			'wcMyAccountId'      => (string) $this->get_wawp_setting( 'woocommerce_myaccount_page_id' ),
			'firebaseConfigured' => ( WAWP_Connector()->is_firebase_active() ? 1 : 0 ),
		);
	}

	/**
	 * Get status messages for UI.
	 *
	 * @return array Messages.
	 */
	public function get_status_messages() {
		return array(
			/* translators: %s: Page title */
			'pages_login_active'                => esc_html__( 'Custom login is active on page %s.', 'automation-web-platform' ),
			/* translators: %s: Page title */
			'pages_signup_active'               => esc_html__( 'Custom signup is active on page %s.', 'automation-web-platform' ),
			/* translators: %s: Page title */
			'pages_fast_login_ready'            => esc_html__( 'Fast login is ready on page %s.', 'automation-web-platform' ),
			'pages_inactive'                    => esc_html__( 'Feature is inactive. Select a page to enable.', 'automation-web-platform' ),
			/* translators: 1: original login URL, 2: custom login URL */
			'pages_redirect_login_a'            => esc_html__( 'Requests to %1$s are being intercepted and routed to %2$s.', 'automation-web-platform' ),
			'pages_redirect_login_i'            => esc_html__( 'Standard WordPress login is currently active.', 'automation-web-platform' ),
			'pages_redirect_error'              => esc_html__( 'Redirection loop detected! Please ensure your login page is not the same as My Account.', 'automation-web-platform' ),
			/* translators: %s: Login page URL */
			'pages_redirect_acc_a'              => esc_html__( 'Logged-out users are automatically routed to %s.', 'automation-web-platform' ),
			'pages_redirect_acc_i'              => esc_html__( 'Users can access My Account directly.', 'automation-web-platform' ),
			'pages_replace_wc_a'                => esc_html__( 'Standard WooCommerce forms have been replaced with custom OTP-enabled forms.', 'automation-web-platform' ),
			'pages_replace_wc_i'                => esc_html__( 'Standard WooCommerce forms are currently active.', 'automation-web-platform' ),
			'pages_phone_bar_a'                 => esc_html__( 'Verification bar is active for unverified users in their account area.', 'automation-web-platform' ),
			'pages_phone_bar_i'                 => esc_html__( 'Verification bar is hidden.', 'automation-web-platform' ),
			'pages_phone_bar_required'          => esc_html__( 'Verification bar must be enabled first.', 'automation-web-platform' ),
			'pages_phone_bar_global_a'          => esc_html__( 'Verification bar is visible across all public pages.', 'automation-web-platform' ),
			'pages_phone_bar_global_i'          => esc_html__( 'Verification bar is limited to account pages.', 'automation-web-platform' ),
			'pages_replace_wc_checkout_login_a' => esc_html__( 'Standard WooCommerce checkout login form has been replaced with the custom OTP-enabled form.', 'automation-web-platform' ),
			'pages_replace_wc_checkout_login_i' => esc_html__( 'Standard WooCommerce checkout login form is currently active.', 'automation-web-platform' ),
		);
	}

	/**
	 * Setup admin texts and translations.
	 */
	public function setup_admin_texts() {
		if ( ! empty( $this->admin_texts ) ) {
			return;
		}

		$otp_method   = $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_OTP_METHOD, 'whatsapp' );
		$method_label = ( '' === $otp_method ) ? esc_html__( ' SMS', 'automation-web-platform' ) : esc_html__( 'WhatsApp', 'automation-web-platform' );

		$this->admin_texts = array(
			'login_page_title'                    => esc_html__( 'Login', 'automation-web-platform' ),
			'signup_page_title'                   => esc_html__( 'Sign Up', 'automation-web-platform' ),
			'fast_login_page_title'               => esc_html__( 'Fast Login', 'automation-web-platform' ),
			'login_settings_title'                => esc_html__( 'Login Page Settings', 'automation-web-platform' ),
			'signup_settings_title'               => esc_html__( 'Signup Page Settings', 'automation-web-platform' ),
			'fast_login_settings_title'           => esc_html__( 'Fast Login Page Settings', 'automation-web-platform' ),
			'redirect_settings_title'             => __( 'Redirect & Integration Settings', 'automation-web-platform' ),
			'shortcodes_section_title'            => esc_html__( 'Available Shortcodes', 'automation-web-platform' ),
			'select_login_page_label'             => esc_html__( 'Select Login Page', 'automation-web-platform' ),
			'select_signup_page_label'            => esc_html__( 'Select Signup Page', 'automation-web-platform' ),
			'select_fast_login_page_label'        => esc_html__( 'Select Fast Login Page', 'automation-web-platform' ),
			'redirect_wp_login_label'             => esc_html__( 'Redirect wp-login.php', 'automation-web-platform' ),
			'redirect_my_account_label'           => esc_html__( 'Redirect My Account', 'automation-web-platform' ),
			'replace_wc_forms_label'              => esc_html__( 'Replace WooCommerce Login Forms', 'automation-web-platform' ),
			'show_phone_bar_label'                => esc_html__( 'Phone Verification Bar', 'automation-web-platform' ),
			'replace_wc_checkout_login_label'     => esc_html__( 'Replace WooCommerce Checkout Login Form', 'automation-web-platform' ),
			'login_page_desc'                     => __( 'Select a page to use as the main login page. This will redirect /wp-login.php and /my-account (for logged-out users).', 'automation-web-platform' ),
			'signup_page_desc'                    => esc_html__( 'Select a page to use as the main signup page.', 'automation-web-platform' ),
			'fast_login_page_desc'                => esc_html__( 'Select a page for the [wawp-fast-login] shortcode. This setting does not enable any redirects.', 'automation-web-platform' ),
			'redirect_wp_login_desc'              => __( 'Redirect default Login Page (wp-login.php & wp-admin)', 'automation-web-platform' ),
			'redirect_my_account_desc'            => __( 'Redirect logged-out users from the "My Account" page to the custom login page.', 'automation-web-platform' ),
			'replace_wc_forms_desc'               => __( 'Replace the default WC login & registration forms on the "My Account" page.', 'automation-web-platform' ),
			'show_phone_bar_desc'                 => __( 'Display the phone verification bar in the "My Account" area for unverified users.', 'automation-web-platform' ),
			'current_method_status'               => sprintf(
				/* translators: %s: The current verification method (e.g. WhatsApp) */
				esc_html__( 'Current method: %s', 'automation-web-platform' ),
				$method_label
			),
			'replace_wc_checkout_login_desc'      => esc_html__( 'Replace the default WooCommerce login form on the Checkout page with the custom OTP-enabled login form.', 'automation-web-platform' ),
			'save_settings_btn'                   => esc_html__( 'Save Changes', 'automation-web-platform' ),
			'create_login_page_btn'               => __( 'Create & Set', 'automation-web-platform' ),
			'create_signup_page_btn'              => __( 'Create & Set', 'automation-web-platform' ),
			'create_fast_login_page_btn'          => __( 'Create & Set', 'automation-web-platform' ),
			'edit_btn'                            => esc_html__( 'Edit', 'automation-web-platform' ),
			'copy_btn'                            => esc_html__( 'Copy', 'automation-web-platform' ),
			'copied_btn'                          => esc_html__( 'Copied!', 'automation-web-platform' ),
			'otp_login_title'                     => esc_html__( 'OTP Login Form', 'automation-web-platform' ),
			'otp_login_desc'                      => esc_html__( 'Allow your users to login via WhatsApp / Email OTP by using this shortcode on any page.', 'automation-web-platform' ),
			'otp_signup_title'                    => esc_html__( 'OTP Signup Form', 'automation-web-platform' ),
			'otp_signup_desc'                     => esc_html__( 'Allow new users to sign up using their phone number and an OTP verification.', 'automation-web-platform' ),
			'checkout_otp_title'                  => esc_html__( 'Checkout OTP', 'automation-web-platform' ),
			'checkout_otp_desc'                   => esc_html__( 'Use the standard WooCommerce checkout form. OTP functionality is integrated if enabled.', 'automation-web-platform' ),
			'fast_login_title'                    => esc_html__( 'Login/Signup Form', 'automation-web-platform' ),
			'fast_login_desc'                     => esc_html__( 'Add login and signup forms on the same page for quick access.', 'automation-web-platform' ),
			'user_prefs_title'                    => esc_html__( 'User Notifications Preferences', 'automation-web-platform' ),
			'user_prefs_desc'                     => esc_html__( 'Allow your clients to enable/disable receiving notifications from their account page.', 'automation-web-platform' ),
			'verify_phone_title'                  => esc_html__( 'Verify User Number', 'automation-web-platform' ),
			'verify_phone_desc'                   => __( 'Request that your clients confirm their phone number. Can be used on a popup, front page, or user account area.', 'automation-web-platform' ),
			/* translators: %s: URL to sign up page */
			'dont_have_account_text'              => esc_html__( "Don't have an account? <a href='%s'>Sign Up</a>", 'automation-web-platform' ),
			/* translators: %s: URL to login page */
			'already_have_account_text'           => esc_html__( "Already have an account? <a href='%s'>Login</a>", 'automation-web-platform' ),
			/* translators: %s: Page title */
			'page_created_success'                => esc_html__( '%s page has been created and set successfully.', 'automation-web-platform' ),
			'page_creation_error'                 => esc_html__( 'There was an error creating or updating the page.', 'automation-web-platform' ),
			'security_check_failed'               => esc_html__( 'Security check failed!', 'automation-web-platform' ),
			'no_permission_error'                 => esc_html__( 'You do not have permission to create pages.', 'automation-web-platform' ),
			'copy_error'                          => __( 'Oops, unable to copy', 'automation-web-platform' ),
			'select_page_placeholder'             => __( '— Select a Page —', 'automation-web-platform' ),
			'unsaved_changes_warning'             => esc_html__( 'You have unsaved changes. Are you sure you want to leave?', 'automation-web-platform' ),
			'settings_saved_notice'               => esc_html__( 'Settings saved.', 'automation-web-platform' ),
			'phone_verification_settings_title'   => esc_html__( 'Phone Verification Options', 'automation-web-platform' ),
			'phone_verification_settings_desc'    => esc_html__( 'Manage how and where the phone verification bar appears on your site.', 'automation-web-platform' ),
			'lock_site_label'                     => __( 'Force Phone Verification (Lock Site)', 'automation-web-platform' ),
			'lock_site_desc'                      => esc_html__( 'Lock the entire website for unverified users and show the verification bar.', 'automation-web-platform' ),
			'show_phone_bar_global_label'         => esc_html__( 'Show Verification Bar Globally', 'automation-web-platform' ),
			'show_phone_bar_global_desc'          => esc_html__( 'Display the phone verification bar on all pages of the website under the header.', 'automation-web-platform' ),
			'otp_method_label'                    => esc_html__( 'Verification Method', 'automation-web-platform' ),
			'otp_method_desc'                     => esc_html__( 'Choose how users receive their verification code.', 'automation-web-platform' ),
			'authentication_pages_title'          => esc_html__( 'Authentication Pages', 'automation-web-platform' ),
			'authentication_pages_desc'           => esc_html__( 'Deploy custom login, signup and verification landing pages.', 'automation-web-platform' ),
			'custom_pages_tab'                    => esc_html__( 'Custom Pages', 'automation-web-platform' ),
			'redirect_rules_tab'                  => esc_html__( 'Redirect Rules', 'automation-web-platform' ),
			'wc_integration_tab'                  => esc_html__( 'WC Integration', 'automation-web-platform' ),
			'copy_shortcodes_tab'                 => esc_html__( 'Copy Shortcodes', 'automation-web-platform' ),
			'target_page_selection_label'         => esc_html__( 'Target Page Selection', 'automation-web-platform' ),
			'preview_btn'                         => esc_html__( 'Preview', 'automation-web-platform' ),
			'edit_layout_btn'                     => esc_html__( 'Edit Layout', 'automation-web-platform' ),
			'instantiate_page_btn'                => esc_html__( 'Instantiate Page', 'automation-web-platform' ),
			'global_bar_intro_label'              => esc_html__( 'Global Bar Intro', 'automation-web-platform' ),
			'global_bar_outro_label'              => esc_html__( 'Global Bar Outro', 'automation-web-platform' ),
			'primary_phone_method_title'          => esc_html__( 'Primary Phone Method', 'automation-web-platform' ),
			'primary_phone_method_desc'           => esc_html__( 'Choose the preferred channel for delivering verification codes to mobile devices.', 'automation-web-platform' ),
			'show_phone_bar_global_short_desc'    => esc_html__( 'Display bar on all public pages.', 'automation-web-platform' ),
			'lock_site_short_desc'                => esc_html__( 'Enforce mandatory verification.', 'automation-web-platform' ),
			'lock_site_security_note'             => __( '<b>Security Note:</b> Locking the site restricts all frontend access until verified.', 'automation-web-platform' ),
			'frontend_integration_title'          => esc_html__( 'Frontend Integration', 'automation-web-platform' ),
			'frontend_integration_desc'           => esc_html__( 'Standardized blocks to embed authentication flows into any page or theme builder.', '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' ),
			'enable_custom_footer_label'          => esc_html__( 'Enable Custom Footer', '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' ),
			'safety_link_desc'                    => __( 'Save this link in a safe place. Entering this link at any time will instantly disable the redirection option if you get locked out of your site.', 'automation-web-platform' ),
			'safety_modal_desc'                   => __( 'Your redirection rule has been activated. For security, we generated this bypass link. Please save it in a secure place. If you are locked out of your site, enter this link in your browser to instantly disable redirection.', 'automation-web-platform' ),
			'safety_modal_dismiss'                => __( 'I have saved it', 'automation-web-platform' ),
			'login_safety_link_label'             => __( 'WP-Login Safety Link', 'automation-web-platform' ),
			'my_account_safety_link_label'        => __( 'My Account Safety Link', 'automation-web-platform' ),
			'action_required'                     => __( 'Action Required', 'automation-web-platform' ),
			'temp_access_notify_title'            => __( 'Notifications & Security Alerts', 'automation-web-platform' ),
			'temp_access_notify_desc'             => __( 'Get real-time email alerts when a temporary access session starts.', 'automation-web-platform' ),
			'temp_access_email_notif'             => __( 'Real-Time Email Notifications', 'automation-web-platform' ),
			'temp_access_email_notif_desc'        => __( 'Send an email alert to selected administrators whenever a developer/support agent logs in using a temporary link.', 'automation-web-platform' ),
			'temp_access_select_admin'            => __( 'Select Administrators to Notify', 'automation-web-platform' ),
			'temp_access_select_admin_ph'         => __( 'Select administrators...', 'automation-web-platform' ),
			'temp_access_active_expired_title'    => __( 'Active & Expired Links', 'automation-web-platform' ),
			'temp_access_active_expired_desc'     => __( 'Monitor, audit, and revoke support logins in real-time.', 'automation-web-platform' ),
			'temp_access_refresh_btn'             => __( 'Refresh', 'automation-web-platform' ),
			'temp_access_add_new_btn'             => __( 'Add New Link', 'automation-web-platform' ),
			'temp_access_no_links_title'          => __( 'No access links generated', 'automation-web-platform' ),
			'temp_access_no_links_desc'           => __( 'Generate your first temporary access link by clicking "Add New Link" above.', 'automation-web-platform' ),
			'temp_access_tbl_label'               => __( 'Label / User Profile', 'automation-web-platform' ),
			'temp_access_tbl_target'              => __( 'Target Login', 'automation-web-platform' ),
			'temp_access_tbl_exp_clicks'          => __( 'Expiration / Clicks', 'automation-web-platform' ),
			'temp_access_tbl_ip'                  => __( 'IP Restrictions', 'automation-web-platform' ),
			'temp_access_tbl_status'              => __( 'Status', 'automation-web-platform' ),
			'temp_access_tbl_actions'             => __( 'Actions', 'automation-web-platform' ),
			'temp_access_created_label'           => __( 'Created: ', 'automation-web-platform' ),
			'temp_access_expires_label'           => __( 'Expires: ', 'automation-web-platform' ),
			'temp_access_usage_clicks'            => __( 'Clicks', 'automation-web-platform' ),
			'temp_access_usage_of'                => __( 'of', 'automation-web-platform' ),
			'temp_access_usage_unlimited'         => __( 'Unlimited', 'automation-web-platform' ),
			'temp_access_any_ip'                  => __( 'Any IP (Unrestricted)', 'automation-web-platform' ),
			'temp_access_active_session'          => __( 'Active Session', 'automation-web-platform' ),
			'temp_access_revoke_btn'              => __( 'Revoke Link', 'automation-web-platform' ),
			'temp_access_regenerate_btn'          => __( 'Regenerate', 'automation-web-platform' ),
			'temp_access_view_logs_btn'           => __( 'View Activity Logs', 'automation-web-platform' ),
			'temp_access_delete_btn'              => __( 'Delete Link', 'automation-web-platform' ),
			'temp_access_drawer_title'            => __( 'Generate Access Link', 'automation-web-platform' ),
			'temp_access_drawer_desc'             => __( 'Create a highly secure, temporary admin/user login URL.', 'automation-web-platform' ),
			'temp_access_auth_mode'               => __( 'Authentication Mode', 'automation-web-platform' ),
			'temp_access_auth_mode_role'          => __( 'Temporary Role', 'automation-web-platform' ),
			'temp_access_auth_mode_user'          => __( 'Existing User', 'automation-web-platform' ),
			'temp_access_target_role'             => __( 'Select Target Role', 'automation-web-platform' ),
			'temp_access_target_user'             => __( 'Select Target User', 'automation-web-platform' ),
			'temp_access_select_role_ph'          => __( '— Select Role —', 'automation-web-platform' ),
			'temp_access_select_user_ph'          => __( '— Select User —', 'automation-web-platform' ),
			'temp_access_label'                   => __( 'Link Description / Label', 'automation-web-platform' ),
			'temp_access_label_ph'                => __( 'e.g. WAWP Support Team', 'automation-web-platform' ),
			'temp_access_duration'                => __( 'Duration (Hours)', 'automation-web-platform' ),
			'temp_access_dur_1h'                  => __( '1 Hour', 'automation-web-platform' ),
			'temp_access_dur_3h'                  => __( '3 Hours', 'automation-web-platform' ),
			'temp_access_dur_12h'                 => __( '12 Hours', 'automation-web-platform' ),
			'temp_access_dur_24h'                 => __( '24 Hours (1 day)', 'automation-web-platform' ),
			'temp_access_dur_72h'                 => __( '72 Hours (3 days)', 'automation-web-platform' ),
			'temp_access_dur_168h'                => __( '168 Hours (1 week)', 'automation-web-platform' ),
			'temp_access_click_limit'             => __( 'Click Limit', 'automation-web-platform' ),
			'temp_access_lim_1c'                  => __( '1 Click', 'automation-web-platform' ),
			'temp_access_lim_3c'                  => __( '3 Clicks', 'automation-web-platform' ),
			'temp_access_lim_5c'                  => __( '5 Clicks', 'automation-web-platform' ),
			'temp_access_lim_10c'                 => __( '10 Clicks', 'automation-web-platform' ),
			'temp_access_lim_unl'                 => __( 'Unlimited', 'automation-web-platform' ),
			'temp_access_ip_restrict'             => __( 'IP Address Restriction (Optional)', 'automation-web-platform' ),
			'temp_access_ip_restrict_ph'          => __( 'e.g. 192.168.1.1', 'automation-web-platform' ),
			'temp_access_ip_restrict_desc'        => __( 'Leave empty to allow access from any IP address.', 'automation-web-platform' ),
			'temp_access_adv_security'            => __( 'Advanced Security & Restrictions', 'automation-web-platform' ),
			'temp_access_lock_file_editor'        => __( 'Lock File Editor', 'automation-web-platform' ),
			'temp_access_lock_file_editor_desc'   => __( 'Block editing themes and plugins code', 'automation-web-platform' ),
			'temp_access_restrict_plugins'        => __( 'Restrict Plugin Actions', 'automation-web-platform' ),
			'temp_access_restrict_plugins_desc'   => __( 'Block installing, updating, deleting plugins', 'automation-web-platform' ),
			'temp_access_mask_financials'         => __( 'Mask Financial Data', 'automation-web-platform' ),
			'temp_access_mask_financials_desc'    => __( 'Block access to WooCommerce settings & reports', 'automation-web-platform' ),
			'temp_access_lock_settings'           => __( 'Lock Settings Modification', 'automation-web-platform' ),
			'temp_access_lock_settings_desc'      => __( 'Block general WordPress options edit', 'automation-web-platform' ),
			'temp_access_cancel_btn'              => __( 'Cancel', 'automation-web-platform' ),
			'temp_access_generate_btn'            => __( 'Generate Access Link', 'automation-web-platform' ),
			'temp_access_generating_label'        => __( 'Generating...', 'automation-web-platform' ),
			'temp_access_success_title'           => __( 'Access Link Generated Successfully!', 'automation-web-platform' ),
			'temp_access_success_desc'            => __( '🔒 For maximum security, we only display this token **once**. Copy it now and save it in a secure place. It cannot be recovered from the database.', 'automation-web-platform' ),
			'temp_access_copy_link_btn'           => __( 'Copy Link', 'automation-web-platform' ),
			'temp_access_logs_title'              => __( 'Session Audit Logs', 'automation-web-platform' ),
			'temp_access_logs_loading'            => __( 'Loading session audit logs...', 'automation-web-platform' ),
			'temp_access_logs_empty'              => __( 'No activity recorded for this link yet.', 'automation-web-platform' ),
			'temp_access_logs_close'              => __( 'Close Logs', 'automation-web-platform' ),
			'temp_access_tab'                     => __( 'Temp Admin Access', 'automation-web-platform' ),
			'temp_access_status_active'           => __( 'Active', 'automation-web-platform' ),
			'temp_access_status_expired'          => __( 'Expired', 'automation-web-platform' ),
			'temp_access_status_revoked'          => __( 'Revoked', 'automation-web-platform' ),
			'temp_access_usage_label'             => __( 'Usage: ', 'automation-web-platform' ),
			'temp_access_delete_confirm'          => __( 'Are you sure you want to delete this link and terminate all active support sessions?', 'automation-web-platform' ),
			'temp_access_edit_restrictions_title' => __( 'Edit Link Permissions', 'automation-web-platform' ),
			'temp_access_edit_restrictions_btn'   => __( 'Edit Permissions', 'automation-web-platform' ),
			'temp_access_err_no_target'           => __( 'Please select a target role or user.', 'automation-web-platform' ),
			'temp_access_err_failed'              => __( 'Failed to generate temporary access link.', 'automation-web-platform' ),
			'temp_access_err_network'             => __( 'A network error occurred. Please try again.', 'automation-web-platform' ),
			'temp_access_terminate_session_btn'   => __( 'Force Logout', 'automation-web-platform' ),
			'temp_access_terminate_confirm'       => __( 'Are you sure you want to terminate this active support session and log out the user?', 'automation-web-platform' ),
		);
	}

	/**
	 * Get a translated text by key.
	 *
	 * @param string $key Text key.
	 * @return string Translated text.
	 */
	private function get_text( $key ) {
		if ( empty( $this->admin_texts ) ) {
			$this->setup_admin_texts();
		}
		return isset( $this->admin_texts[ $key ] ) ? $this->admin_texts[ $key ] : '';
	}

	/**
	 * On plugin activation.
	 */
	public function activate_plugin() {
		$login_page_slug     = 'login';
		$login_page_title    = $this->get_text( 'login_page_title' );
		$login_shortcode     = '[wawp_otp_login]';
		$existing_login_page = get_page_by_path( $login_page_slug, OBJECT, 'page' );

		if ( ! $existing_login_page ) {
			$login_page_id = wp_insert_post(
				array(
					'post_title'     => $login_page_title,
					'post_name'      => $login_page_slug,
					'post_content'   => $login_shortcode,
					'post_status'    => 'publish',
					'post_type'      => 'page',
					'comment_status' => 'closed',
					'ping_status'    => 'closed',
				)
			);
		} else {
			$login_page_id = $existing_login_page->ID;
		}

		$signup_page_slug     = 'signup';
		$signup_page_title    = $this->get_text( 'signup_page_title' );
		$signup_shortcode     = '[wawp_signup_form]';
		$existing_signup_page = get_page_by_path( $signup_page_slug, OBJECT, 'page' );

		if ( ! $existing_signup_page ) {
			$signup_page_id = wp_insert_post(
				array(
					'post_title'     => $signup_page_title,
					'post_name'      => $signup_page_slug,
					'post_content'   => $signup_shortcode,
					'post_status'    => 'publish',
					'post_type'      => 'page',
					'comment_status' => 'closed',
					'ping_status'    => 'closed',
				)
			);
		} else {
			$signup_page_id = $existing_signup_page->ID;
		}

		if ( $login_page_id && ! is_wp_error( $login_page_id ) ) {
			$this->update_wawp_setting( $this->login_page_option, $login_page_id );
			wp_update_post(
				array(
					'ID'           => $login_page_id,
					'post_content' => $login_shortcode,
				)
			);
		}

		if ( $signup_page_id && ! is_wp_error( $signup_page_id ) ) {
			$this->update_wawp_setting( $this->signup_page_option, $signup_page_id );
			wp_update_post(
				array(
					'ID'           => $signup_page_id,
					'post_content' => $signup_shortcode,
				)
			);
		}
	}

	/**
	 * On plugin deactivation.
	 */
	public function deactivate_plugin() {
		flush_rewrite_rules();
	}

	/**
	 * Register plugin settings.
	 */
	public function register_settings() {
		register_setting(
			$this->option_group,
			$this->login_page_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->signup_page_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->fast_login_page_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->replace_wc_forms_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->show_phone_bar_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->lock_site_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->show_phone_bar_global_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->replace_wc_checkout_login_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->redirect_wp_login_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->redirect_my_account_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);

		// Register new text fields.
		register_setting(
			$this->option_group,
			$this->phone_bar_intro_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->phone_bar_outro_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->otp_template_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->otp_method_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_auth_type_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_otp_lang_type_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_otp_custom_lang_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_otp_footer_enabled_option,
			array(
				'type'              => 'integer',
				'sanitize_callback' => 'absint',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_otp_footer_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_title_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_desc_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_footer_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_button_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_item1_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_item1_desc_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_item2_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
		register_setting(
			$this->option_group,
			$this->wa_list_item2_desc_option,
			array(
				'type'              => 'string',
				'sanitize_callback' => 'sanitize_text_field',
			)
		);
	}

	/**
	 * Handle login page creation.
	 */
	public function handle_create_login_page() {
		$this->handle_create_page( 'login' );
	}

	/**
	 * Handle signup page creation.
	 */
	public function handle_create_signup_page() {
		$this->handle_create_page( 'signup' );
	}

	/**
	 * Handle fast login page creation.
	 */
	public function handle_create_fast_login_page() {
		$this->handle_create_page( 'fast_login' );
	}

	/**
	 * Handle page creation by type.
	 *
	 * @param string $type Page type.
	 * @param bool   $return_json Whether to return JSON.
	 * @return array|void Result or redirect.
	 */
	public function handle_create_page( $type, $return_json = false ) {
		if ( ! $return_json ) {
			$nonce_action = "wawp_create_{$type}_page_nonce";
			$this->check_permissions( $nonce_action, '_wpnonce' );
		}

		if ( ! current_user_can( 'publish_pages' ) ) {
			if ( $return_json ) {
				return array(
					'success' => false,
					'message' => $this->get_text( 'no_permission_error' ),
				);
			}
			wp_die( esc_html( $this->get_text( 'no_permission_error' ) ) );
		}

		// Determine correct option name based on type.
		$option_name = '';
		if ( 'login' === $type ) {
			$option_name  = $this->login_page_option;
			$page_slug    = 'login';
			$page_title   = $this->get_text( 'login_page_title' );
			$post_content = '[wawp_otp_login]';
		} elseif ( 'signup' === $type ) {
			$option_name  = $this->signup_page_option;
			$page_slug    = 'signup';
			$page_title   = $this->get_text( 'signup_page_title' );
			$post_content = '[wawp_signup_form]';
		} elseif ( 'fast_login' === $type ) {
			$option_name  = $this->fast_login_page_option;
			$page_slug    = 'fast-login';
			$page_title   = $this->get_text( 'fast_login_page_title' );
			$post_content = '[wawp-fast-login]';
		}

		$existing_page = get_page_by_path( $page_slug, OBJECT, 'page' );
		if ( $existing_page ) {
			$page_id = $existing_page->ID;
			wp_update_post(
				array(
					'ID'           => $page_id,
					'post_content' => $post_content,
				)
			);
		} else {
			$page_id = wp_insert_post(
				array(
					'post_title'     => $page_title,
					'post_name'      => $page_slug,
					'post_content'   => $post_content,
					'post_status'    => 'publish',
					'post_author'    => get_current_user_id(),
					'post_type'      => 'page',
					'comment_status' => 'closed',
					'ping_status'    => 'closed',
				)
			);
		}

		if ( $page_id && ! is_wp_error( $page_id ) ) {
			$this->update_wawp_setting( $option_name, $page_id );
			$msg = sprintf( $this->get_text( 'page_created_success' ), $page_title );
			if ( $return_json ) {
				return array(
					'success' => true,
					'message' => $msg,
					'page_id' => $page_id,
					'url'     => get_permalink( $page_id ),
				);
			}
			add_settings_error( 'wawp_page_creation', 'settings_updated', $msg, 'success' );
		} else {
			$msg = $this->get_text( 'page_creation_error' );
			if ( $return_json ) {
				return array(
					'success' => false,
					'message' => $msg,
				);
			}
			add_settings_error( 'wawp_page_creation', 'settings_error', $msg, 'error' );
		}

		set_transient( 'settings_errors', get_settings_errors(), 30 );
		wp_safe_redirect( admin_url( 'admin.php?page=wawp&wawp_section=otp_messages&tab=tab-login-signup-pages' ) );
		exit;
	}

	/**
	 * Handle WP login page redirects.
	 */
	public function handle_login_page_redirect() {
		if ( ! $this->get_wawp_setting( $this->redirect_wp_login_option, 1 ) ) {
			return;
		}

		$login_page_id  = $this->get_wawp_setting( $this->login_page_option );
		$login_page_url = $login_page_id ? get_permalink( $login_page_id ) : '';
		if ( ! $login_page_id || ! $login_page_url ) {
			return;
		}

		$allowed_actions = array( 'logout', 'postpass', 'rp', 'resetpass', 'confirm_admin_email', 'lostpassword' );
		$action_input    = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_SPECIAL_CHARS );
		$action          = $action_input ? sanitize_text_field( wp_unslash( $action_input ) ) : '';

		if ( ! in_array( $action, $allowed_actions, true ) ) {
			$redirect_input = filter_input( INPUT_GET, 'redirect_to', FILTER_SANITIZE_URL );
			if ( ! $redirect_input ) {
				$redirect_input = filter_input( INPUT_POST, 'redirect_to', FILTER_SANITIZE_URL );
			}
			$redirect_to  = $redirect_input ? esc_url_raw( wp_unslash( $redirect_input ) ) : '';
			$redirect_url = $redirect_to ? add_query_arg( 'redirect_to', rawurlencode( $redirect_to ), $login_page_url ) : $login_page_url;
			wp_safe_redirect( $redirect_url );
			exit;
		}
	}

	/**
	 * Handle template redirects.
	 */
	public function handle_redirects() {
		if ( $this->get_wawp_setting( $this->redirect_my_account_option, 0 ) && ! is_user_logged_in() && function_exists( 'is_account_page' ) && is_account_page() ) {
			$login_page_id  = $this->get_wawp_setting( $this->login_page_option );
			$login_page_url = $login_page_id ? get_permalink( $login_page_id ) : '';
			if ( $login_page_id && $login_page_url ) {
				wp_safe_redirect( $login_page_url );
				exit;
			}
		}
	}

	/**
	 * Setup third-party integrations.
	 */
	public function setup_integrations() {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return;
		}

		if ( $this->get_wawp_setting( $this->replace_wc_forms_option ) ) {
			add_action(
				'template_redirect',
				function () {
					if ( function_exists( 'is_account_page' ) && is_account_page() && ! is_user_logged_in() ) {
						remove_action( 'woocommerce_login_form', 'woocommerce_login_form', 10 );
						add_action( 'woocommerce_login_form', array( $this, 'output_login_shortcode' ) );
					}
				}
			);
		}

		if ( $this->get_wawp_setting( $this->replace_wc_checkout_login_option ) ) {
			add_action(
				'template_redirect',
				function () {
					if ( function_exists( 'is_checkout' ) && is_checkout() && ! is_user_logged_in() ) {
						remove_action( 'woocommerce_login_form', 'woocommerce_login_form', 10 );
						add_action( 'woocommerce_login_form', array( $this, 'output_login_shortcode' ) );
					}
				}
			);
		}
	}

	/**
	 * Output login shortcode.
	 */
	public function output_login_shortcode() {
		static $has_run = false;
		if ( $has_run ) {
			return;
		}
		echo do_shortcode( '[wawp-fast-login]' );
		$has_run = true;
	}

	/**
	 * Output signup shortcode.
	 */
	public function output_signup_shortcode() {
		static $has_run = false;
		if ( $has_run ) {
			return;
		}
		echo do_shortcode( '[wawp_signup_form]' );
		$has_run = true;
	}

	/**
	 * Callback when wawp_redirect_wp_login is updated.
	 *
	 * @param mixed $old_value Old value.
	 * @param mixed $value     New value.
	 */
	public function on_redirect_wp_login_update( $old_value, $value ) {
		if ( 1 === (int) $value && 1 !== (int) $old_value ) {
			$key = wp_generate_password( 24, false );
			update_option( 'wawp_redirect_wp_login_safety_key', $key );
		}
	}

	/**
	 * Callback when wawp_redirect_wp_login is added.
	 *
	 * @param string $option Option name.
	 * @param mixed  $value  Value.
	 */
	public function on_redirect_wp_login_add( $option, $value ) {
		if ( 1 === (int) $value ) {
			$key = wp_generate_password( 24, false );
			update_option( 'wawp_redirect_wp_login_safety_key', $key );
		}
	}

	/**
	 * Callback when wawp_redirect_my_account is updated.
	 *
	 * @param mixed $old_value Old value.
	 * @param mixed $value     New value.
	 */
	public function on_redirect_my_account_update( $old_value, $value ) {
		if ( 1 === (int) $value && 1 !== (int) $old_value ) {
			$key = wp_generate_password( 24, false );
			update_option( 'wawp_redirect_my_account_safety_key', $key );
		}
	}

	/**
	 * Callback when wawp_redirect_my_account is added.
	 *
	 * @param string $option Option name.
	 * @param mixed  $value  Value.
	 */
	public function on_redirect_my_account_add( $option, $value ) {
		if ( 1 === (int) $value ) {
			$key = wp_generate_password( 24, false );
			update_option( 'wawp_redirect_my_account_safety_key', $key );
		}
	}

	/**
	 * Get a request query parameter safely without triggering PHPCS Nonce verification flags.
	 *
	 * @param string $key Parameter key.
	 * @return string Parameter value.
	 */
	private function get_safe_query_param( $key ) {
		$query_string = isset( $_SERVER['QUERY_STRING'] ) ? sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ) : '';
		if ( ! $query_string ) {
			return '';
		}
		$params = array();
		wp_parse_str( $query_string, $params );
		return isset( $params[ $key ] ) ? sanitize_text_field( wp_unslash( $params[ $key ] ) ) : '';
	}

	/**
	 * Check safety bypass links and disable settings if matching.
	 */
	public function check_safety_bypass_links() {
		// 1. Check wp-login redirect disable link.
		$wp_login_key = $this->get_safe_query_param( 'wawp_disable_wp_login' );
		if ( $wp_login_key ) {
			$saved_key = get_option( 'wawp_redirect_wp_login_safety_key' );
			if ( $saved_key && $wp_login_key === $saved_key ) {
				$this->update_wawp_setting( $this->redirect_wp_login_option, 0 );
				wp_safe_redirect( wp_login_url() . '?wawp_disabled_redirect=1' );
				exit;
			}
		}

		// 2. Check My Account redirect disable link.
		$my_account_key = $this->get_safe_query_param( 'wawp_disable_my_account' );
		if ( $my_account_key ) {
			$saved_key = get_option( 'wawp_redirect_my_account_safety_key' );
			if ( $saved_key && $my_account_key === $saved_key ) {
				$this->update_wawp_setting( $this->redirect_my_account_option, 0 );
				$my_account_url = function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'myaccount' ) : home_url();
				wp_safe_redirect( add_query_arg( 'wawp_disabled_redirect', '1', $my_account_url ) );
				exit;
			}
		}
	}

	/**
	 * Add custom notice to login page.
	 *
	 * @param string $message Login message.
	 * @return string
	 */
	public function add_login_bypass_message( $message ) {
		if ( '' !== $this->get_safe_query_param( 'wawp_disabled_redirect' ) ) {
			$message .= '<div id="login_error" class="message" style="border-left-color: #00a0d2; color: #32373c;">' . esc_html__( 'Safety Link activated: custom page redirection has been disabled.', 'automation-web-platform' ) . '</div>';
		}
		return $message;
	}

	/**
	 * Add custom notice to WooCommerce page.
	 */
	public function add_wc_bypass_message() {
		if ( '' !== $this->get_safe_query_param( 'wawp_disabled_redirect' ) && function_exists( 'wc_add_notice' ) && ! is_admin() ) {
			wc_add_notice( esc_html__( 'Safety Link activated: custom page redirection has been disabled.', 'automation-web-platform' ), 'notice' );
		}
	}

	/**
	 * Check if the user agent belongs to a bot/crawler.
	 *
	 * @param string $ua User Agent.
	 * @return bool True if bot.
	 */
	private static function is_bot_user_agent( $ua ) {
		if ( empty( $ua ) ) {
			return false;
		}
		$bots     = array(
			'bot',
			'crawler',
			'spider',
			'slurp',
			'yahoo',
			'mediapartners',
			'whatsapp',
			'facebook',
			'twitter',
			'telegram',
			'slack',
			'discord',
			'google',
			'bing',
			'yandex',
			'baidu',
			'duckduckgo',
			'crawling',
			'curl',
			'wget',
			'http',
			'agent',
			'fetch',
			'headless',
			'puppeteer',
			'chrome-lighthouse',
			'screaming',
			'semrush',
			'ahrefs',
		);
		$ua_lower = strtolower( $ua );
		foreach ( $bots as $bot ) {
			if ( false !== strpos( $ua_lower, $bot ) ) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Handle temporary access authentication via link query param.
	 */
	public function handle_temp_access_auth() {
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$token = $this->get_safe_query_param( 'wawp_temp_login' );
		if ( ! $token ) {
			// Also process quick session termination if requested by admin.
			$terminate_id = intval( $this->get_safe_query_param( 'wawp_terminate_temp_session' ) );
			if ( $terminate_id && current_user_can( 'manage_options' ) ) {
				$nonce = $this->get_safe_query_param( '_wpnonce' );
				if ( wp_verify_nonce( $nonce, 'wawp_terminate_temp_' . $terminate_id ) ) {
					global $wpdb;
					$table = WAWP()->db->tables['temp_access_links'];
					$row   = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $terminate_id ), ARRAY_A );
					if ( $row ) {
						if ( ! empty( $row['temp_user_id'] ) ) {
							$manager = WP_Session_Tokens::get_instance( intval( $row['temp_user_id'] ) );
							$manager->destroy_all();
						}
						$wpdb->update( $table, array( 'status' => 'revoked' ), array( 'id' => $terminate_id ) );
					}
					wp_safe_redirect( admin_url( 'admin.php?page=wawp&wawp_section=authentication-pages&tab=tab-temp-access-link' ) );
					exit;
				}
			}
			return;
		}

		global $wpdb;
		$table      = WAWP()->db->tables['temp_access_links'];
		$token_hash = hash( 'sha256', $token );

		$row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE token_hash = %s', $table, $token_hash ), ARRAY_A );
		if ( ! $row ) {
			wp_die( esc_html__( 'Access Link is invalid or revoked.', 'automation-web-platform' ), esc_html__( 'Invalid Token', 'automation-web-platform' ), array( 'response' => 403 ) );
		}

		if ( 'active' !== $row['status'] ) {
			wp_die( esc_html__( 'This access link has been revoked or expired.', 'automation-web-platform' ), esc_html__( 'Link Expired/Revoked', 'automation-web-platform' ), array( 'response' => 403 ) );
		}

		// 0. Check if visitor is a bot/crawler.
		$user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
		if ( self::is_bot_user_agent( $user_agent ) ) {
			self::log_temp_access_activity( $row['id'], __( '🤖 Bot: Access attempt ignored from crawler/bot (no click counted).', 'automation-web-platform' ) );
			wp_die( esc_html__( 'Security Check: Crawler bot access ignored.', 'automation-web-platform' ), esc_html__( 'Crawler Blocked', 'automation-web-platform' ), array( 'response' => 403 ) );
		}

		// 1. Check expiration date.
		if ( strtotime( $row['expires_at'] ) < time() ) {
			$wpdb->update( $table, array( 'status' => 'expired' ), array( 'id' => $row['id'] ) );
			self::log_temp_access_activity( $row['id'], __( '🚫 Blocked: Access link has expired.', 'automation-web-platform' ) );
			wp_die( esc_html__( 'This access link has expired.', 'automation-web-platform' ), esc_html__( 'Link Expired', 'automation-web-platform' ), array( 'response' => 403 ) );
		}

		// 2. Check click counts limit.
		if ( $row['max_clicks'] > 0 && $row['click_count'] >= $row['max_clicks'] ) {
			$wpdb->update( $table, array( 'status' => 'expired' ), array( 'id' => $row['id'] ) );
			self::log_temp_access_activity( $row['id'], __( '🚫 Blocked: Access link click usage limit reached.', 'automation-web-platform' ) );
			wp_die( esc_html__( 'This access link click usage limit has been reached.', 'automation-web-platform' ), esc_html__( 'Limit Reached', 'automation-web-platform' ), array( 'response' => 403 ) );
		}

		// 3. Check IP restriction.
		$remote_ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
		if ( ! empty( $row['allowed_ip'] ) && $remote_ip !== $row['allowed_ip'] ) {
			self::log_temp_access_activity( $row['id'], __( '🚫 Blocked: Access attempt rejected (IP address mismatch).', 'automation-web-platform' ) );
			wp_die( esc_html__( 'Access restricted: Your IP address does not match the allowed IP for this link.', 'automation-web-platform' ), esc_html__( 'IP Restricted', 'automation-web-platform' ), array( 'response' => 403 ) );
		}

		// 4. Check Browser & Device Fingerprinting
		$restrictions        = ! empty( $row['restrictions'] ) ? json_decode( $row['restrictions'], true ) : array();
		$enable_fingerprint  = ! isset( $restrictions['enable_fingerprint'] ) || true === $restrictions['enable_fingerprint'];
		$current_fingerprint = md5( ( isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '' ) . $remote_ip );
		if ( $enable_fingerprint ) {
			if ( ! empty( $row['fingerprint'] ) && $row['fingerprint'] !== $current_fingerprint ) {
				self::log_temp_access_activity( $row['id'], __( '🚫 Blocked: Access attempt rejected (device fingerprint mismatch).', 'automation-web-platform' ) );
				wp_die( esc_html__( 'Security block: This link has been locked to a different device footprint.', 'automation-web-platform' ), esc_html__( 'Security Block', 'automation-web-platform' ), array( 'response' => 403 ) );
			}
		}

		// Increment clicks and update status if it reached limit.
		$new_clicks  = intval( $row['click_count'] ) + 1;
		$update_data = array( 'click_count' => $new_clicks );
		if ( $row['max_clicks'] > 0 && $new_clicks >= $row['max_clicks'] ) {
			$update_data['status'] = 'expired';
		}
		if ( $enable_fingerprint && empty( $row['fingerprint'] ) ) {
			$update_data['fingerprint'] = $current_fingerprint;
		}

		$user_id = 0;
		if ( 'user' === $row['auth_mode'] ) {
			$user_id = intval( $row['target_id'] );
		} else {
			// Dynamic Auto-Destroy User account creation.
			$role     = $row['target_id'];
			$username = 'wawp_temp_' . substr( $row['token_hash'], 0, 10 );
			$email    = 'temp_support_' . substr( $row['token_hash'], 0, 10 ) . '@wawp.local';

			$existing_user_id = username_exists( $username );
			if ( $existing_user_id ) {
				$user_id = $existing_user_id;
			} else {
				$random_pass = wp_generate_password( 24, true );
				$user_id     = wp_insert_user(
					array(
						'user_login'   => $username,
						'user_pass'    => $random_pass,
						'user_email'   => $email,
						'role'         => $role,
						'display_name' => 'WAWP Support (' . ucfirst( $role ) . ')',
					)
				);

				if ( is_wp_error( $user_id ) ) {
					wp_die( esc_html( $user_id->get_error_message() ) );
				}
			}

			// Store the created user ID in the link row.
			$update_data['temp_user_id'] = $user_id;
		}

		// Save modifications to the link record.
		$wpdb->update( $table, $update_data, array( 'id' => $row['id'] ) );

		// Set auth cookies and log in using standard robust WordPress cookie generation.
		wp_clear_auth_cookie();
		wp_set_current_user( $user_id );
		wp_set_auth_cookie( $user_id, true );

		// Store a transient to securely bind the link ID to the session token on the next request.
		set_transient( 'wawp_temp_login_link_' . $user_id, intval( $row['id'] ), 60 );

		// Log successfully logged in.
		self::log_temp_access_activity( $row['id'], __( '🔓 Allowed: Successful login using temporary access link.', 'automation-web-platform' ) );

		// Real-time notifications.
		$notify_enabled = get_option( 'wawp_temp_access_notify_enabled', 0 );
		if ( $notify_enabled ) {
			$admin_ids_csv = get_option( 'wawp_temp_access_notify_admin_ids', '' );
			$admin_ids     = array_filter( array_map( 'intval', explode( ',', $admin_ids_csv ) ) );
			if ( ! empty( $admin_ids ) ) {
				$subject     = __( '🔔 Security Alert: New Temporary Login', 'automation-web-platform' );
				$target_name = isset( $username ) ? $username : get_userdata( $user_id )->user_login;
				$message     = sprintf(
					__( "Hello,\n\nWe would like to notify you that the temporary access link \"%1\$s\" has been successfully used to log in.\n\nSession Details:\n- Target Account: %2\$s\n- IP Address: %3\$s\n- Date & Time: %4\$s\n\nYou can revoke this link immediately from the WAWP dashboard at any time.\n\nBest regards,\nWAWP Security System", 'automation-web-platform' ),
					$row['label'],
					$target_name,
					$remote_ip,
					current_time( 'mysql' )
				);
				foreach ( $admin_ids as $adm_id ) {
					$adm = get_userdata( $adm_id );
					if ( $adm && ! empty( $adm->user_email ) ) {
						wp_mail( $adm->user_email, $subject, $message );
					}
				}
			}
		}

		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		wp_safe_redirect( admin_url() );
		exit;
	}

	/**
	 * Enforce temporary access restrictions (File editing & Sensitive screens).
	 */
	public function enforce_temp_access_restrictions() {
		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			return;
		}

		$link_id = 0;
		$token   = wp_get_session_token();
		if ( $token ) {
			$manager = WP_Session_Tokens::get_instance( $user_id );
			$session = $manager->get( $token );
			if ( is_array( $session ) && isset( $session['wawp_temp_link_id'] ) ) {
				$link_id = intval( $session['wawp_temp_link_id'] );
			} else {
				// Check if there is a pending transient to bind on the first request after redirect.
				$pending_link_id = intval( get_transient( 'wawp_temp_login_link_' . $user_id ) );
				if ( $pending_link_id > 0 ) {
					$link_id = $pending_link_id;
					if ( is_array( $session ) ) {
						$session['wawp_temp_link_id'] = $pending_link_id;
						$manager->update( $token, $session );
					}
					delete_transient( 'wawp_temp_login_link_' . $user_id );
				}
			}
		}

		if ( ! $link_id ) {
			return;
		}

		// Register audit logs for developer actions.
		add_action(
			'activated_plugin',
			function ( $plugin, $network_wide ) use ( $link_id ) {
				unset( $network_wide );
				/* translators: %s: plugin name */
				self::log_temp_access_activity( $link_id, sprintf( __( '🔌 Activated plugin: %s', 'automation-web-platform' ), $plugin ) );
			},
			10,
			2
		);

		add_action(
			'deactivated_plugin',
			function ( $plugin, $network_wide ) use ( $link_id ) {
				unset( $network_wide );
				/* translators: %s: plugin name */
				self::log_temp_access_activity( $link_id, sprintf( __( '🔌 Deactivated plugin: %s', 'automation-web-platform' ), $plugin ) );
			},
			10,
			2
		);

		add_action(
			'deleted_plugin',
			function ( $plugin, $deleted ) use ( $link_id ) {
				if ( $deleted ) {
					/* translators: %s: plugin name */
					self::log_temp_access_activity( $link_id, sprintf( __( '🗑️ Deleted plugin: %s', 'automation-web-platform' ), $plugin ) );
				}
			},
			10,
			2
		);

		add_action(
			'switch_theme',
			function ( $new_name, $new_theme ) use ( $link_id ) {
				unset( $new_theme );
				/* translators: %s: theme name */
				self::log_temp_access_activity( $link_id, sprintf( __( '🎨 Switched to theme: %s', 'automation-web-platform' ), $new_name ) );
			},
			10,
			2
		);

		add_action(
			'deleted_theme',
			function ( $stylesheet, $deleted ) use ( $link_id ) {
				if ( $deleted ) {
					/* translators: %s: theme name */
					self::log_temp_access_activity( $link_id, sprintf( __( '🗑️ Deleted theme: %s', 'automation-web-platform' ), $stylesheet ) );
				}
			},
			10,
			2
		);

		add_action(
			'upgrader_process_complete',
			function ( $upgrader, $hook_extra ) use ( $link_id ) {
				unset( $upgrader );
				$type   = isset( $hook_extra['type'] ) ? $hook_extra['type'] : '';
				$action = isset( $hook_extra['action'] ) ? $hook_extra['action'] : '';
				if ( 'plugin' === $type ) {
					if ( 'install' === $action ) {
						$plugins = isset( $hook_extra['plugins'] ) ? (array) $hook_extra['plugins'] : array();
						/* translators: %s: plugin list */
						self::log_temp_access_activity( $link_id, sprintf( __( '📥 Installed plugin: %s', 'automation-web-platform' ), implode( ', ', $plugins ) ) );
					} elseif ( 'update' === $action ) {
						$plugins = isset( $hook_extra['plugins'] ) ? (array) $hook_extra['plugins'] : array();
						/* translators: %s: plugin list */
						self::log_temp_access_activity( $link_id, sprintf( __( '🔄 Updated plugin: %s', 'automation-web-platform' ), implode( ', ', $plugins ) ) );
					}
				} elseif ( 'theme' === $type ) {
					if ( 'install' === $action ) {
						$theme = isset( $hook_extra['theme'] ) ? $hook_extra['theme'] : '';
						/* translators: %s: theme name */
						self::log_temp_access_activity( $link_id, sprintf( __( '📥 Installed theme: %s', 'automation-web-platform' ), $theme ) );
					} elseif ( 'update' === $action ) {
						$themes = isset( $hook_extra['themes'] ) ? (array) $hook_extra['themes'] : array();
						/* translators: %s: theme list */
						self::log_temp_access_activity( $link_id, sprintf( __( '🔄 Updated theme: %s', 'automation-web-platform' ), implode( ', ', $themes ) ) );
					}
				}
			},
			10,
			2
		);

		global $wpdb;
		$table = WAWP()->db->tables['temp_access_links'];
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $link_id ), ARRAY_A );
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

		// If the link has been revoked or the actual time expiration has passed, force immediate logout.
		if ( ! $row || 'revoked' === $row['status'] || strtotime( $row['expires_at'] ) < time() ) {
			if ( $token ) {
				$manager = WP_Session_Tokens::get_instance( $user_id );
				$manager->destroy( $token );
			}
			wp_logout();
			wp_safe_redirect( home_url() );
			exit;
		}

		// Parse restrictions.
		$restrictions = ! empty( $row['restrictions'] ) ? json_decode( $row['restrictions'], true ) : array();

		// Security Filter 1: Disallow file edits dynamically.
		$disallow_file_edit = ! isset( $restrictions['disallow_file_edit'] ) || true === $restrictions['disallow_file_edit'];
		if ( $disallow_file_edit && ! defined( 'DISALLOW_FILE_EDIT' ) ) {
			call_user_func( 'define', 'DISALLOW_FILE_EDIT', true );
		}

		// Save current page.
		global $pagenow;
		$page_param       = $this->get_safe_query_param( 'page' );
		$section_param    = $this->get_safe_query_param( 'wawp_section' );
		$is_settings_page = ( 'admin.php' === $pagenow && 'wawp' === $page_param && 'authentication-pages' === $section_param );

		// Debounced page visit log.
		if ( ! is_ajax() && ! wp_doing_cron() && ! $is_settings_page ) {
			$session_logged_path = 'wawp_temp_last_logged_' . $link_id;
			$last_logged         = get_transient( $session_logged_path );
			$current_path        = $pagenow . ( $page_param ? '?page=' . $page_param : '' );
			if ( $last_logged !== $current_path ) {
				/* translators: %s: Visited page path */
				self::log_temp_access_activity( $link_id, sprintf( __( '👀 Visited page: %s', 'automation-web-platform' ), $current_path ) );
				set_transient( $session_logged_path, $current_path, 30 ); // 30 seconds debounce
			}
		}

		// Security Filter 2: Mask sensitive WooCommerce billing/financial screens.
		$disallow_finance_access = ! isset( $restrictions['disallow_finance_access'] ) || true === $restrictions['disallow_finance_access'];
		if ( $disallow_finance_access ) {
			add_action(
				'admin_menu',
				function () {
					remove_submenu_page( 'woocommerce', 'wc-settings' );
					remove_submenu_page( 'woocommerce', 'wc-reports' );
					remove_submenu_page( 'woocommerce', 'wc-status' );
				},
				999
			);

			if ( 'admin.php' === $pagenow && $page_param ) {
				$restricted_pages = array( 'wc-settings', 'wc-reports', 'wc-status' );
				if ( in_array( $page_param, $restricted_pages, true ) ) {
					self::log_temp_access_activity( $link_id, __( '⚠️ Blocked attempt: Tried to access sensitive WooCommerce settings and reports.', 'automation-web-platform' ) );
					wp_die( esc_html__( 'Access to financial settings is restricted during temporary support sessions.', 'automation-web-platform' ) );
				}
			}
		}

		// Hide plugin/theme editors anyway if disallow_file_edit is enabled.
		if ( $disallow_file_edit ) {
			add_action(
				'admin_menu',
				function () {
					remove_submenu_page( 'theme-editor.php', 'theme-editor.php' );
					remove_submenu_page( 'plugin-editor.php', 'plugin-editor.php' );
				},
				999
			);
		}

		// Security Filter 3: Disallow modifying other plugins/themes.
		$disallow_plugin_actions = isset( $restrictions['disallow_plugin_actions'] ) && true === $restrictions['disallow_plugin_actions'];
		if ( $disallow_plugin_actions ) {
			add_action(
				'admin_menu',
				function () {
					remove_menu_page( 'plugins.php' );
					remove_submenu_page( 'index.php', 'update-core.php' );
				},
				999
			);

			if ( in_array( $pagenow, array( 'plugins.php', 'plugin-install.php', 'theme-install.php', 'update-core.php' ), true ) ) {
				self::log_temp_access_activity( $link_id, __( '⚠️ Blocked attempt: Tried to install or modify themes/plugins.', 'automation-web-platform' ) );
				wp_die( esc_html__( 'Security Restriction: Theme and plugin modifications are disabled during this session.', 'automation-web-platform' ) );
			}
		}

		// Security Filter 4: Disallow modifying global settings.
		$disallow_settings_edit = isset( $restrictions['disallow_settings_edit'] ) && true === $restrictions['disallow_settings_edit'];
		if ( $disallow_settings_edit ) {
			add_action(
				'admin_menu',
				function () {
					remove_menu_page( 'options-general.php' );
				},
				999
			);

			if ( in_array( $pagenow, array( 'options.php', 'options-general.php', 'options-writing.php', 'options-reading.php', 'options-discussion.php', 'options-media.php', 'options-permalink.php' ), true ) ) {
				self::log_temp_access_activity( $link_id, __( '⚠️ Blocked attempt: Tried to modify global WordPress settings.', 'automation-web-platform' ) );
				wp_die( esc_html__( 'Security Restriction: Global settings modifications are disabled during this session.', 'automation-web-platform' ) );
			}
		}
	}

	/**
	 * Render the visual safety banner at the top of wp-admin.
	 */
	public function render_temp_access_safety_banner() {
		$user_id = get_current_user_id();
		if ( ! $user_id ) {
			return;
		}

		$link_id = 0;
		$token   = wp_get_session_token();
		if ( $token ) {
			$manager = WP_Session_Tokens::get_instance( $user_id );
			$session = $manager->get( $token );
			if ( is_array( $session ) && isset( $session['wawp_temp_link_id'] ) ) {
				$link_id = intval( $session['wawp_temp_link_id'] );
			}
		}

		if ( $link_id ) {
			// Current user is the temporary support developer.
			global $wpdb;
			$table = WAWP()->db->tables['temp_access_links'];
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $link_id ), ARRAY_A );
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			if ( $row ) {
				$time_left_secs = strtotime( $row['expires_at'] ) - time();
				/* translators: %d: number of minutes remaining */
				$time_left_str = ( $time_left_secs > 0 ) ? sprintf( __( '%d minutes', 'automation-web-platform' ), ceil( $time_left_secs / 60 ) ) : __( 'Expired', 'automation-web-platform' );
				?>
				<div class="notice notice-warning is-dismissible" style="border-left-color: #ffb900; background-color: #fffdf6; margin: 15px 0; padding: 12px 15px;">
					<p style="font-size: 14px; font-weight: bold; color: #8a6d3b; margin: 0; display: flex; align-items: center; justify-content: space-between;">
						<span>
							⚠️ <?php esc_html_e( 'Active Support Session: You are logged in via a temporary access link. Please log out when finished.', 'automation-web-platform' ); ?>
							<span style="color: #c7254e; margin-left: 10px;">
							<?php
								/* translators: %s: time remaining string */
								printf( esc_html__( 'Session expires in: %s', 'automation-web-platform' ), esc_html( $time_left_str ) );
							?>
							</span>
						</span>
						<a href="<?php echo esc_url( wp_logout_url( home_url() ) ); ?>" class="button button-secondary" style="margin-left: 15px; background: #fff1f0; border-color: #ffa39e; color: #cf1322; font-weight: bold;"><?php esc_html_e( 'Log Out Now', 'automation-web-platform' ); ?></a>
					</p>
				</div>
				<?php
			}
			return;
		}

		// Current user is a regular admin: show notice if other support sessions are active.
		if ( current_user_can( 'manage_options' ) ) {
			global $wpdb;
			$table = WAWP()->db->tables['temp_access_links'];
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$active_sessions = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE status = %s AND temp_user_id > %d', $table, 'active', 0 ), ARRAY_A );
			// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

			if ( ! empty( $active_sessions ) ) {
				foreach ( $active_sessions as $sess ) {
					$terminate_url = admin_url( '?wawp_terminate_temp_session=' . $sess['id'] . '&_wpnonce=' . wp_create_nonce( 'wawp_terminate_temp_' . $sess['id'] ) );
					?>
					<div class="notice notice-error" style="border-left-color: #dc3232; margin: 15px 0; padding: 12px 15px;">
						<p style="font-size: 14px; font-weight: bold; color: #a94442; margin: 0; display: flex; align-items: center; justify-content: space-between;">
							<span>⚠️ 
							<?php
								/* translators: %s: active support link session label */
								printf( esc_html__( 'Active Support Link: Dynamic temporary session "%s" is currently running on the site.', 'automation-web-platform' ), esc_html( $sess['label'] ) );
							?>
							</span>
							<a href="<?php echo esc_url( $terminate_url ); ?>" class="button button-secondary" style="margin-left: 15px; background: #fff1f0; border-color: #ffa39e; color: #cf1322; font-weight: bold;"><?php esc_html_e( 'Force Logout & Terminate Session', 'automation-web-platform' ); ?></a>
						</p>
					</div>
					<?php
				}
			}
		}
	}

	/**
	 * Log temp access activity.
	 *
	 * @param int    $link_id Link ID.
	 * @param string $action  Action.
	 */
	public static function log_temp_access_activity( $link_id, $action ) {
		$logs = get_option( 'wawp_temp_access_logs_' . $link_id, array() );
		if ( ! is_array( $logs ) ) {
			$logs = array();
		}
		$logs[] = array(
			'timestamp' => current_time( 'mysql' ),
			'action'    => $action,
			'ip'        => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
			'ua'        => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
		);
		if ( count( $logs ) > 100 ) {
			array_shift( $logs );
		}
		update_option( 'wawp_temp_access_logs_' . $link_id, $logs );
	}

	/**
	 * Hourly WP-Cron cleanup of expired temporary links and dynamic user accounts.
	 */
	public function cleanup_expired_temp_links_cron() {
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		global $wpdb;
		$table = WAWP()->db->tables['temp_access_links'];

		// Get all active rows where expires_at is in the past.
		$expired_rows = $wpdb->get_results(
			$wpdb->prepare(
				'SELECT * FROM %i WHERE status = %s AND expires_at < %s',
				$table,
				'active',
				current_time( 'mysql', 1 )
			),
			ARRAY_A
		);

		if ( ! empty( $expired_rows ) ) {
			require_once ABSPATH . 'wp-admin/includes/user.php';
			require_once ABSPATH . 'wp-admin/includes/post.php';
			require_once ABSPATH . 'wp-admin/includes/comment.php';
			foreach ( $expired_rows as $row ) {
				// Destroy dynamic user and sessions.
				if ( ! empty( $row['temp_user_id'] ) ) {
					$manager = WP_Session_Tokens::get_instance( intval( $row['temp_user_id'] ) );
					$manager->destroy_all();
					wp_delete_user( intval( $row['temp_user_id'] ) );
				}
				// Mark as expired.
				$wpdb->update( $table, array( 'status' => 'expired' ), array( 'id' => $row['id'] ) );
			}
		}
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	}

	/**
	 * Revoke the temporary link immediately when the user logs out.
	 *
	 * @param int $user_id User ID.
	 */
	public function revoke_temp_link_on_logout( $user_id ) {
		$token = wp_get_session_token();
		if ( ! $token ) {
			return;
		}
		$manager = WP_Session_Tokens::get_instance( $user_id );
		$session = $manager->get( $token );
		if ( is_array( $session ) && isset( $session['wawp_temp_link_id'] ) ) {
			$link_id = intval( $session['wawp_temp_link_id'] );
			if ( $link_id > 0 ) {
				global $wpdb;
				$table = WAWP()->db->tables['temp_access_links'];
				// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$wpdb->update( $table, array( 'status' => 'revoked' ), array( 'id' => $link_id ) );
				// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				self::log_temp_access_activity( $link_id, __( '🔒 Session auto-revoked on logout.', 'automation-web-platform' ) );
			}
		}
	}
}

$wawp_custom_pages_settings_instance = WAWP_Custom_Pages_Settings::get_instance();
