<?php
/**
 * Phone Verification Bar.
 *
 * @package automation-web-platform
 */

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


/**
 * Class WAWP_Phone_Verification_Bar
 */
class WAWP_Phone_Verification_Bar {
	use WAWP_Settings_Handler;
	use WAWP_Security_Trait;
	use WAWP_Phone_Helper_Trait;

	/**
	 * DB instance.
	 *
	 * @var object
	 */
	private $db;

	/**
	 * Constructor.
	 */
	public function __construct() {
		$this->db = WAWP()->db;

		if ( $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_IN_ACCOUNT, 0 ) ) {
			add_action( 'woocommerce_before_my_account', array( $this, 'render_bar' ) );
		}

		if ( $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_GLOBALLY, 0 ) ) {
			add_action( 'wawp_after_header', array( $this, 'render_global_bar' ) );
			add_action( 'wp_body_open', array( $this, 'render_global_bar' ), 20 );
		}

		if ( $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_LOCK_SITE, 0 ) ) {
			add_action( 'template_redirect', array( $this, 'maybe_lock_site' ) );
		}

		add_shortcode( 'wawp_phone_verification_bar', array( $this, 'render_bar' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_filter( 'wawp_frontend_global_vars', array( $this, 'add_frontend_global_vars' ) );
	}

	/**
	 * Check if current user is phone-verified.
	 *
	 * @return bool
	 */
	private function is_verified() {
		if ( ! is_user_logged_in() ) {
			return true;
		}

		return WAWP()->user_manager->get_verification_status( get_current_user_id(), 'whatsapp' );
	}

	/**
	 * Lock site access if phone not verified.
	 */
	public function maybe_lock_site() {
		if ( ! is_user_logged_in() || $this->is_verified() ) {
			return;
		}

		if ( is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
			return;
		}

		status_header( 403 );
		?>
		<!DOCTYPE html>
		<html <?php language_attributes(); ?>>
		<head>
			<meta charset="<?php bloginfo( 'charset' ); ?>">
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<?php wp_head(); ?>
			<style>
				body.wawp-site-locked {
					background: #f0f2f5;
					display: flex;
					align-items: center;
					justify-content: center;
					height: 100vh;
					margin: 0;
					font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
				}
				.wawp-lock-container {
					background: white;
					padding: 40px;
					border-radius: 12px;
					box-shadow: 0 10px 25px rgba(0,0,0,0.1);
					text-align: center;
					max-width: 500px;
					width: 90%;
				}
				.wawp-lock-icon {
					font-size: 48px;
					color: #22c55e;
					margin-bottom: 20px;
				}
				.wawp-lock-title {
					font-size: 24px;
					font-weight: 700;
					margin-bottom: 10px;
					color: #1e293b;
				}
				.wawp-lock-desc {
					color: #64748b;
					margin-bottom: 30px;
					line-height: 1.6;
				}
				#wawp-phone-bar {
					background: transparent !important;
					border: none !important;
					padding: 0 !important;
					box-shadow: none !important;
					display: flex;
					flex-direction: column;
					gap: 15px;
				}
				#wawp-phone-bar input, #wawp-phone-bar button {
					width: 100%;
					box-sizing: border-box;
				}
			</style>
		</head>
		<body class="wawp-site-locked">
			<div class="wawp-lock-container">
				<div class="wawp-lock-icon"><i class="ri-shield-user-line"></i></div>
				<h1 class="wawp-lock-title"><?php esc_html_e( 'Verification Required', 'automation-web-platform' ); ?></h1>
				<p class="wawp-lock-desc">
					<?php echo esc_html( $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_INTRO, 'Confirm your number' ) ); ?>
					<?php esc_html_e( 'to continue using our services.', 'automation-web-platform' ); ?>
				</p>
				<?php echo do_shortcode( '[wawp_phone_verification_bar]' ); ?>
				<div style="margin-top: 20px;">
					<a href="<?php echo esc_url( wp_logout_url( home_url() ) ); ?>" style="color: #64748b; text-decoration: none; font-size: 14px;">
						<i class="ri-logout-box-line"></i> <?php esc_html_e( 'Logout', 'automation-web-platform' ); ?>
					</a>
				</div>
			</div>
			<?php wp_footer(); ?>
		</body>
		</html>
		<?php
		exit;
	}

	/**
	 * Render the global verification bar (singleton).
	 */
	public function render_global_bar() {
		static $done = false;
		if ( $done || ! is_user_logged_in() || $this->is_verified() ) {
			return;
		}

		$done = true;
		echo '<div class="wawp-global-bar-wrapper">';
		$this->render_bar();
		echo '</div>';
	}

	/**
	 * Render the phone verification bar shortcode output.
	 */
	public function render_bar() {
		if ( ! is_user_logged_in() || $this->is_verified() ) {
			return '';
		}

		$info   = WAWP()->user_manager->get_user_info( get_current_user_id() );
		$is_new = ( ! $info || empty( $info->phone ) );
		$phone  = $is_new ? '' : $info->phone;

		ob_start();
		wp_nonce_field( 'wawp_phone_verify', 'wawp_phone_verify_nonce' );
		?>
		<div id="wawp-phone-bar">
			<span id="wawp-add-text" class="<?php echo esc_attr( $is_new ? '' : 'wawp-hide' ); ?>">
				<?php esc_html_e( 'Add your number to access all features and login via WhatsApp OTP.', 'automation-web-platform' ); ?>
			</span>
			<span id="wawp-bar-text" class="<?php echo esc_attr( $is_new ? 'wawp-hide' : '' ); ?>">
				<?php echo esc_html( $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_INTRO, 'Confirm your number' ) ); ?>
				<strong id="wawp-phone-display"><?php echo esc_html( $phone ); ?></strong>
				<i id="wawp-edit-phone" class="ri-edit-line <?php echo esc_attr( $is_new ? 'wawp-hide' : '' ); ?>"></i>
				<?php echo esc_html( $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_OUTRO, 'to get full access and login via WhatsApp OTP.' ) ); ?>
			</span>
			<input id="wawp-new-phone" type="tel" value="<?php echo esc_attr( $phone ); ?>" class="<?php echo esc_attr( $is_new ? '' : 'wawp-hide' ); ?>">
			<button id="wawp-save-phone" class="button <?php echo esc_attr( $is_new ? '' : 'wawp-hide' ); ?>">
				<?php esc_html_e( 'Save', 'automation-web-platform' ); ?>
			</button>
			<input id="wawp-otp-input" type="text" placeholder="<?php echo esc_attr__( '123456', 'automation-web-platform' ); ?>" class="wawp-hide">
			<?php
			$wa_auth_type = $this->get_wawp_setting( WAWP_Settings_Registry::WA_AUTH_TYPE, 'otp' );
			$otp_method   = $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_OTP_METHOD, 'whatsapp' );
			$btn_text     = ( 'whatsapp' === $otp_method && 'list' === $wa_auth_type ) ? esc_html__( 'Verify', 'automation-web-platform' ) : esc_html__( 'Send OTP', 'automation-web-platform' );
			?>
			<button id="wawp-send-otp" class="button <?php echo esc_attr( $is_new ? 'wawp-hide' : '' ); ?>">
				<?php echo esc_html( $btn_text ); ?>
			</button>
			<button id="wawp-confirm-otp" class="button wawp-hide">
				<?php esc_html_e( 'Confirm', 'automation-web-platform' ); ?>
			</button>
			<div id="wawp-recaptcha-phonebar"></div>
			<div id="wawp-phone-bar-msg" class="wawp-hide" style="width: 100%; color: #d32f2f; font-size: 13px; font-weight: 500; margin-top: 5px;"></div>
		</div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Update user phone number.
	 *
	 * @param array $params Request params.
	 * @return array
	 */
	public function update_phone_number_return( $params ) {
		if ( ! is_user_logged_in() ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Login required', 'automation-web-platform' ),
			);
		}

		$raw = sanitize_text_field( wp_unslash( $params['phone'] ?? '' ) );
		$raw = self::get_digits_only( $raw );

		if ( ! preg_match( '/^[0-9]{7,15}$/', $raw ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Invalid phone format', 'automation-web-platform' ),
			);
		}

		global $wpdb;
		$user_info_table = WAWP()->user_manager->get_table_name();
		$cache_key       = 'wawp_dup_phone_' . md5( $raw );
		$dup             = wp_cache_get( $cache_key, 'wawp_security' );

		if ( false === $dup ) {
			$dup = call_user_func_array( array( $wpdb, 'get_var' ), array( $wpdb->prepare( 'SELECT user_id FROM %i WHERE phone = %s AND user_id != %d LIMIT 1', $user_info_table, $raw, get_current_user_id() ) ) );
			wp_cache_set( $cache_key, $dup, 'wawp_security', 30 );
		}

		if ( $dup ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Phone already used.', 'automation-web-platform' ),
			);
		}

		WAWP()->connector->sync_user_phone( get_current_user_id(), $raw );
		return array(
			'success' => true,
			'data'    => array( 'phone' => esc_html( $raw ) ),
		);
	}

	/**
	 * Send phone OTP.
	 *
	 * @return array
	 */
	public function send_phone_otp_return() {
		if ( ! is_user_logged_in() ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Login required', 'automation-web-platform' ),
			);
		}

		$user_id = get_current_user_id();
		$info    = WAWP()->user_manager->get_user_info( $user_id );

		if ( ! $info || empty( $info->phone ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'No phone found', 'automation-web-platform' ),
			);
		}

		$otp_method    = $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_OTP_METHOD, 'whatsapp' );
		$auth_settings = array(
			'whatsapp_auth_type'       => $this->get_wawp_setting( WAWP_Settings_Registry::WA_AUTH_TYPE, 'otp' ),
			'whatsapp_list_title'      => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_TITLE, esc_html__( 'Secure Verification', 'automation-web-platform' ) ),
			'whatsapp_list_desc'       => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_DESC, esc_html__( 'Please confirm your identity to continue.', 'automation-web-platform' ) ),
			'whatsapp_list_footer'     => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_FOOTER, esc_html__( 'Secure authentication via Wawp', 'automation-web-platform' ) ),
			'whatsapp_list_button'     => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_BUTTON, esc_html__( 'Choose Action', 'automation-web-platform' ) ),
			'whatsapp_list_item1'      => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_ITEM1, esc_html__( 'Approve Request', 'automation-web-platform' ) ),
			'whatsapp_list_item1_desc' => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_ITEM1_DESC, esc_html__( 'Verify this is you', 'automation-web-platform' ) ),
			'whatsapp_list_item2'      => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_ITEM2, __( 'Reject & Stop', 'automation-web-platform' ) ),
			'whatsapp_list_item2_desc' => $this->get_wawp_setting( WAWP_Settings_Registry::WA_LIST_ITEM2_DESC, esc_html__( 'Cancel this attempt', 'automation-web-platform' ) ),
		);

		$challenge = WAWP_OTP_Service::get_instance()->send_challenge(
			$info->phone,
			array(
				'method'   => $otp_method,
				'context'  => 'Verify Bar',
				'settings' => $auth_settings,
				'user_id'  => $user_id,
			)
		);

		if ( ! $challenge['success'] ) {
			return array(
				'success' => false,
				'message' => $challenge['message'],
			);
		}

		update_user_meta( $user_id, 'wawp_phone_bar_transient', $challenge['transient_key'] );
		update_user_meta( $user_id, 'wawp_phone_bar_auth_type', $challenge['whatsapp_auth_type'] ?? 'otp' );

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

	/**
	 * Verify phone OTP.
	 *
	 * @param array $params Request params.
	 * @return array
	 */
	public function verify_phone_otp_return( $params ) {
		return WAWP_OTP_Service::get_instance()->verify_otp_return(
			array_merge( $params, array( 'transient_field' => 'otp_transient' ) ),
			array(),
			array( $this, 'finalize_phone_verification_return' )
		);
	}

	/**
	 * Finalize phone verification after OTP confirmation.
	 *
	 * @param array $data Verification data.
	 * @return array
	 */
	public function finalize_phone_verification_return( $data ) {
		$user_id = get_current_user_id();
		delete_user_meta( $user_id, 'wawp_phone_bar_transient' );
		delete_user_meta( $user_id, 'wawp_phone_bar_auth_type' );

		WAWP()->user_manager->update_user_verification( $user_id, 'whatsapp', true );

		$info = WAWP()->user_manager->get_user_info( $user_id );
		if ( $info && ! empty( $info->phone ) ) {
			update_user_meta( $user_id, 'billing_phone', $info->phone );
		}

		if ( ( $data['method'] ?? '' ) === 'firebase' ) {
			WAWP()->connector->sync_user_phone( $user_id, $data['phone'] );
		}

		return array(
			'success' => true,
			'data'    => array( 'verified' => true ),
		);
	}

	/**
	 * Check WhatsApp auth status.
	 *
	 * @param array $params Request params.
	 * @return array
	 */
	public function check_phone_auth_status_return( $params ) {
		$transient_key = get_user_meta( get_current_user_id(), 'wawp_phone_bar_transient', true );
		return WAWP_OTP_Service::get_instance()->check_status_return(
			array_merge( $params, array( 'transient_key' => $transient_key ) ),
			array(),
			array( $this, 'finalize_phone_verification_return' )
		);
	}

	/**
	 * Verify Firebase token.
	 *
	 * @param array $params Request params.
	 * @return array
	 */
	public function verify_firebase_token_return( $params ) {
		return WAWP_OTP_Service::get_instance()->verify_firebase_return( $params, array(), array( $this, 'finalize_phone_verification_return' ) );
	}

	/**
	 * Log Firebase OTP initiation.
	 *
	 * @param array $params Request params.
	 * @return array
	 */
	public function log_firebase_otp_return( $params ) {
		$phone = sanitize_text_field( wp_unslash( $params['phone'] ?? '' ) );
		if ( empty( $phone ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Phone number is required.', 'automation-web-platform' ),
			);
		}

		wawp_log_message( $phone, ' Verification Initiated', esc_html__( 'Phone Bar - OTP Request', 'automation-web-platform' ), 'Client-side verification started via Firebase SDK', get_current_user_id(), 'firebase' );
		return array( 'success' => true );
	}

	/**
	 * Dismiss phone bar for current session.
	 *
	 * @return array
	 */
	public function dismiss_phone_bar_return() {
		if ( is_user_logged_in() ) {
			update_user_meta( get_current_user_id(), 'wawp_dismiss_phone_bar', 1 );
		}
		return array( 'success' => true );
	}

	/**
	 * Enqueue frontend assets.
	 */
	public function enqueue_assets() {
		wp_enqueue_style( 'wawp-phone-verify-bar', WAWP_PLUGIN_URL . 'assets/css/phone-verification-bar.css', array(), WAWP_PLUGIN_VERSION );
		wp_enqueue_script( 'wawp-phone-verify-bar', WAWP_PLUGIN_URL . 'assets/js/phone-verification-bar.js', array( 'jquery', 'wawp-global-data-hub' ), WAWP_PLUGIN_VERSION, true );
	}

	/**
	 * Add global variables to the central data hub.
	 *
	 * @param array $vars Global variables array.
	 * @return array
	 */
	public function add_frontend_global_vars( $vars ) {
		if ( ! is_user_logged_in() ) {
			return $vars;
		}

		$user_info = WAWP()->user_manager->get_user_info( get_current_user_id() );
		$is_new    = ( ! $user_info || empty( $user_info->phone ) );

		$vars['wawpPhoneVerify'] = array(
			'ajax'               => admin_url( 'admin-ajax.php' ),
			'rest_url'           => esc_url_raw( rest_url( 'wawp/v1/phone-bar' ) ),
			'nonce'              => wp_create_nonce( 'wp_rest' ),
			'is_new'             => $is_new,
			'resend_text'        => esc_html__( 'Resend OTP', 'automation-web-platform' ),
			'verified_msg'       => __( 'Thank you, your number is verified now', 'automation-web-platform' ),
			'otp_method'         => $this->get_wawp_setting( WAWP_Settings_Registry::PHONE_BAR_OTP_METHOD, 'whatsapp' ),
			'whatsapp_auth_type' => $this->get_wawp_setting( WAWP_Settings_Registry::WA_AUTH_TYPE, 'otp' ),
			'_config'            => ( function () {
				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';
				}
				return class_exists( 'WAWP_Firebase_Sender' ) ? WAWP_Firebase_Sender::get_active_account() : array();
			} )(),
			'_configured'        => ( WAWP_Connector()->is_firebase_active() ? 1 : 0 ),
		);

		return $vars;
	}
}

new WAWP_Phone_Verification_Bar();
