<?php
/**
 * Admin Users Helper.
 *
 * @package automation-web-platform
 */

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

/**
 * WAWP_Admin_Users Class
 * Handles user management UI in WordPress Admin.
 */
class WAWP_Admin_Users {
	use WAWP_Settings_Handler;
	use WAWP_Security_Trait;
	use WAWP_Phone_Helper_Trait;
	use WAWP_Logging_Trait;

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_filter( 'manage_users_columns', array( $this, 'modify_users_columns' ) );
		add_filter( 'manage_users_custom_column', array( $this, 'populate_custom_columns' ), 10, 3 );
		add_filter( 'manage_users_sortable_columns', array( $this, 'make_columns_sortable' ) );

		add_action( 'show_user_profile', array( $this, 'show_user_phone_field' ) );
		add_action( 'edit_user_profile', array( $this, 'show_user_phone_field' ) );
		add_action( 'personal_options_update', array( $this, 'save_user_phone_field' ) );
		add_action( 'edit_user_profile_update', array( $this, 'save_user_phone_field' ) );

		add_action( 'woocommerce_edit_account_form', array( $this, 'wawp_show_custom_phone_fields' ) );
		add_action( 'woocommerce_save_account_details', array( $this, 'wawp_save_custom_phone_fields' ) );

		add_action( 'profile_update', array( $this, 'sync_phone_fields' ) );
		add_action( 'woocommerce_customer_save_address', array( $this, 'sync_phone_fields' ), 10, 1 );
		add_action( 'woocommerce_checkout_update_user_meta', array( $this, 'sync_checkout_phone_meta' ), 10, 2 );
		add_action( 'user_register', array( $this, 'sync_phone_fields' ) );

		add_filter( 'bulk_actions-users', array( $this, 'wawp_add_bulk_verification_actions' ) );
		add_filter( 'handle_bulk_actions-users', array( $this, 'wawp_handle_bulk_verification_actions' ), 10, 3 );
		add_action( 'admin_notices', array( $this, 'wawp_verification_bulk_admin_notice' ) );

		add_action( 'delete_user', array( $this, 'delete_wawp_user_info' ) );

		$this->enable_number_search_bar();
		add_action( 'wp_ajax_wawp_send_user_custom_message', array( $this, 'ajax_send_user_custom_message' ) );
	}

	/**
	 * Delete user info from WAWP DB on user deletion.
	 *
	 * @param int $user_id User ID.
	 */
	public function delete_wawp_user_info( $user_id ) {
		WAWP()->user_manager->delete_user_info( $user_id );
	}

	/**
	 * Modify user table columns to include custom email, phone, and direct WhatsApp actions.
	 *
	 * @param array $columns Columns array.
	 * @return array
	 */
	public function modify_users_columns( $columns ) {
		$new_columns = array();

		foreach ( $columns as $key => $title ) {
			if ( 'email' === $key ) {
				// Replace core email with our custom email column.
				$new_columns['wawp_email'] = esc_html__( 'Email', 'automation-web-platform' );

				// Prepend Wawp brand logo SVG to the header of the "Phone number" column.
				$wawp_logo = WAWP_UI_Helper::get_svg(
					'main-icon',
					array(
						'width'  => 16,
						'height' => 16,
					)
				);

				// Prepare Renamed Phone number column.
				$phone_title                      = sprintf(
					'<span style="display:inline-flex; align-items:center; gap:6px; vertical-align: middle;">%s <span>%s</span></span>',
					$wawp_logo,
					esc_html__( 'Phone number', 'automation-web-platform' )
				);
				$new_columns['wawp_user_phone']   = $phone_title;
				$new_columns['wawp_send_message'] = esc_html__( 'Quick Send', 'automation-web-platform' );
			} elseif ( ! in_array( $key, array( 'whatsapp_verified', 'wawp_user_phone' ), true ) ) {
				// We also make sure to remove any legacy columns if other filters registered them.
				$new_columns[ $key ] = $title;
			}
		}

		return $new_columns;
	}

	/**
	 * Populate custom columns with inline verification badges and direct links.
	 *
	 * @param string $value       Column value.
	 * @param string $column_name Column name.
	 * @param int    $user_id     User ID.
	 * @return string
	 */
	public function populate_custom_columns( $value, $column_name, $user_id ) {
		if ( 'wawp_email' === $column_name ) {
			$userdata = get_userdata( $user_id );
			if ( ! $userdata ) {
				return '---';
			}
			$email = $userdata->user_email;
			if ( ! $email ) {
				return '---';
			}

			$email_verified = WAWP()->user_manager->get_verification_status( $user_id, 'email' );
			$badge_color    = $email_verified ? '#22c55e' : '#ef4444';
			$badge_icon     = $email_verified ? 'verified' : 'not-verified';
			$svg            = WAWP_UI_Helper::get_svg(
				$badge_icon,
				array(
					'width'  => 16,
					'height' => 16,
					'color'  => $badge_color,
				)
			);

			return sprintf(
				'<span style="display:inline-flex; align-items:center; gap:6px; vertical-align: middle;">' .
				'<a href="mailto:%1$s">%1$s</a>' .
				'<span title="%2$s" style="display:inline-flex; align-items:center; vertical-align:middle;">%3$s</span>' .
				'</span>',
				esc_html( $email ),
				$email_verified ? esc_attr__( 'Email Verified', 'automation-web-platform' ) : esc_attr__( 'Email Not Verified', 'automation-web-platform' ),
				$svg
			);
		}

		if ( 'wawp_user_phone' === $column_name ) {
			$phone = WAWP()->user_manager->get_user_phone( $user_id );
			if ( ! $phone ) {
				return '---';
			}

			$phone_verified = WAWP()->user_manager->get_verification_status( $user_id, 'whatsapp' );
			$badge_color    = $phone_verified ? '#22c55e' : '#ef4444';
			$badge_icon     = $phone_verified ? 'verified' : 'not-verified';
			$svg            = WAWP_UI_Helper::get_svg(
				$badge_icon,
				array(
					'width'  => 16,
					'height' => 16,
					'color'  => $badge_color,
				)
			);

			return sprintf(
				'<span style="display:inline-flex; align-items:center; gap:6px; vertical-align: middle;">' .
				'<span>%1$s</span>' .
				'<span title="%2$s" style="display:inline-flex; align-items:center; vertical-align:middle;">%3$s</span>' .
				'</span>',
				esc_html( $phone ),
				$phone_verified ? esc_attr__( 'WhatsApp Verified', 'automation-web-platform' ) : esc_attr__( 'WhatsApp Not Verified', 'automation-web-platform' ),
				$svg
			);
		}

		if ( 'wawp_send_message' === $column_name ) {
			$url          = admin_url( 'admin.php?page=wawp&wawp_section=activity_hub&wawp_action=send_message&user_id=' . $user_id );
			$svg_whatsapp = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="currentColor" class="bi bi-whatsapp" viewBox="0 0 16 16" style="display:inline-block; vertical-align:middle; margin-right:5px;"><path d="M13.601 2.326A7.85 7.85 0 0 0 7.994 0C3.627 0 .068 3.558.064 7.926c0 1.399.366 2.76 1.057 3.965L0 16l4.204-1.102a7.9 7.9 0 0 0 3.79.965h.004c4.368 0 7.926-3.558 7.93-7.93A7.9 7.9 0 0 0 13.6 2.326zM7.994 14.521a6.6 6.6 0 0 1-3.356-.92l-.24-.144-2.494.654.666-2.433-.156-.251a6.56 6.56 0 0 1-1.007-3.505c0-3.626 2.957-6.584 6.591-6.584a6.56 6.56 0 0 1 4.66 1.931 6.56 6.56 0 0 1 1.928 4.66c-.004 3.639-2.961 6.592-6.592 6.592m3.615-4.934c-.197-.099-1.17-.578-1.353-.646-.182-.065-.315-.099-.445.099-.133.197-.513.646-.627.775-.114.133-.232.148-.43.05-.197-.1-.836-.308-1.592-.985-.59-.525-.985-1.175-1.103-1.372-.114-.198-.011-.304.088-.403.087-.088.197-.232.296-.346.1-.114.133-.198.198-.33.065-.134.034-.248-.015-.347-.05-.099-.445-1.076-.612-1.47-.16-.389-.323-.335-.445-.34-.114-.007-.247-.007-.38-.007a.73.73 0 0 0-.529.247c-.182.198-.691.677-.691 1.654s.71 1.916.81 2.049c.098.133 1.394 2.132 3.383 2.992.47.205.84.326 1.129.418.475.152.904.129 1.246.08.38-.058 1.171-.48 1.338-.943.164-.464.164-.86.114-.943-.049-.084-.182-.133-.38-.232"/></svg>';

			return sprintf(
				'<a href="%s" class="wawp-quick-send-btn" style="' .
				'display: inline-flex; align-items: center; justify-content: center; ' .
				'background-color: #ffffff; color: #004349; ' .
				'padding: 5px 10px; font-size: 10px; font-weight: 700; ' .
				'border-radius: 6px; text-decoration: none; ' .
				'box-shadow: 0 1px 2px rgba(0,0,0,0.05); ' .
				'transition: all 0.2s ease-in-out; border: 1px solid #004349; cursor: pointer;' .
				'" onmouseover="this.style.backgroundColor=\'#004349\'; this.style.color=\'#ffffff\'; this.style.transform=\'translateY(-1px)\'; this.style.boxShadow=\'0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)\';" ' .
				'onmouseout="this.style.backgroundColor=\'#ffffff\'; this.style.color=\'#004349\'; this.style.transform=\'none\'; this.style.boxShadow=\'0 1px 2px rgba(0,0,0,0.05)\';">' .
				'%s <span>%s</span>' .
				'</a>',
				esc_url( $url ),
				$svg_whatsapp,
				esc_html__( 'Send Message', 'automation-web-platform' )
			);
		}

		return $value;
	}

	/**
	 * Make custom email column sortable.
	 *
	 * @param array $sortable_columns Sortable columns array.
	 * @return array
	 */
	public function make_columns_sortable( $sortable_columns ) {
		$sortable_columns['wawp_email'] = 'email';
		return $sortable_columns;
	}

	/**
	 * Show user phone field on profile page.
	 *
	 * @param WP_User $user User object.
	 */
	public function show_user_phone_field( $user ) {
		if ( ! current_user_can( 'edit_user', $user->ID ) ) {
			return;
		}

		$user_info  = WAWP()->user_manager->get_user_info( $user->ID );
		$user_phone = ! empty( $user_info->phone ) ? $user_info->phone : '';

		wp_nonce_field( 'wawp_save_profile_phone', 'wawp_profile_phone_nonce' );

		$whatsapp_verified = WAWP()->user_manager->get_verification_status( $user->ID, 'whatsapp' );
		$email_verified    = WAWP()->user_manager->get_verification_status( $user->ID, 'email' );

		$whatsapp_badge = $whatsapp_verified ?
			'<div class="wawp-badge-admin verified" style="cursor: default;">' .
				WAWP_UI_Helper::get_svg(
					'verified',
					array(
						'width'  => 18,
						'height' => 18,
						'color'  => 'rgba(34,197,94,1)',
					)
				) .
				'<span>' . esc_html__( 'Verified By Wawp', 'automation-web-platform' ) . '</span>' .
			'</div>' :
			'<div class="wawp-badge-admin not-verified" style="cursor: default;">' .
				WAWP_UI_Helper::get_svg(
					'not-verified',
					array(
						'width'  => 18,
						'height' => 18,
						'color'  => 'rgba(237,55,55,1)',
					)
				) .
				'<span>' . esc_html__( 'Not Verified', 'automation-web-platform' ) . '</span>' .
			'</div>';

		$email_badge = $email_verified ?
			'<div class="wawp-badge-admin verified" style="cursor: default;">' .
				WAWP_UI_Helper::get_svg(
					'verified',
					array(
						'width'  => 18,
						'height' => 18,
						'color'  => 'rgba(34,197,94,1)',
					)
				) .
				'<span>' . esc_html__( 'Email Verified', 'automation-web-platform' ) . '</span>' .
			'</div>' :
			'<div class="wawp-badge-admin not-verified" style="cursor: default;">' .
				WAWP_UI_Helper::get_svg(
					'not-verified',
					array(
						'width'  => 18,
						'height' => 18,
						'color'  => 'rgba(237,55,55,1)',
					)
				) .
				'<span>' . esc_html__( 'Email Not Verified', 'automation-web-platform' ) . '</span>' .
			'</div>';

		$allowed_html = array(
			'div'  => array(
				'class' => true,
				'style' => true,
			),
			'span' => array(
				'class' => true,
				'style' => true,
				'title' => true,
			),
			'svg'  => array(
				'xmlns'   => true,
				'viewbox' => true,
				'viewBox' => true,
				'width'   => true,
				'height'  => true,
				'fill'    => true,
				'class'   => true,
			),
			'path' => array(
				'd'    => true,
				'fill' => true,
			),
		);

		echo '<h3>' . esc_html__( 'Wawp User Information', 'automation-web-platform' ) . '</h3>';
		echo '<table class="form-table">
			<tr>
				<th><label for="wawp_user_phone">' . esc_html__( 'Phone number', 'automation-web-platform' ) . '</label></th>
				<td>
					<input type="text" name="wawp_user_phone" id="wawp_user_phone" value="' . esc_attr( $user_phone ) . '" class="regular-text" />
					<p class="description">' . esc_html__( 'The phone number for Wawp notifications.', 'automation-web-platform' ) . '</p>
				</td>
			</tr>
			<tr>
				<th>' . esc_html__( 'WhatsApp Verification', 'automation-web-platform' ) . '</th>
				<td>' . wp_kses( $whatsapp_badge, $allowed_html ) . '</td>
			</tr>
			<tr>
				<th>' . esc_html__( 'Email Verification', 'automation-web-platform' ) . '</th>
				<td>' . wp_kses( $email_badge, $allowed_html ) . '</td>
			</tr>
		</table>';
	}

	/**
	 * Save user phone field from profile page.
	 *
	 * @param int $user_id User ID.
	 */
	public function save_user_phone_field( $user_id ) {
		if ( ! current_user_can( 'edit_user', $user_id ) ) {
			return;
		}

		if ( ! isset( $_POST['wawp_profile_phone_nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['wawp_profile_phone_nonce'] ) ), 'wawp_save_profile_phone' ) ) {
			return;
		}

		$wawp_phone    = isset( $_POST['wawp_user_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['wawp_user_phone'] ) ) : '';
		$billing_phone = isset( $_POST['billing_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_phone'] ) ) : '';

		$current_phone = WAWP()->user_manager->get_user_phone( $user_id );
		$final_phone   = $wawp_phone;

		if ( $wawp_phone === $current_phone && $billing_phone !== $current_phone ) {
			$final_phone = $billing_phone;
		}

		$_POST['wawp_user_phone'] = $final_phone;
		$_POST['billing_phone']   = $final_phone;

		WAWP()->connector->sync_user_phone( $user_id, $final_phone );
	}

	/**
	 * Show custom phone field on WooCommerce account page.
	 */
	public function wawp_show_custom_phone_fields() {
		if ( ! is_user_logged_in() ) {
			return;
		}

		$user_id    = get_current_user_id();
		$user_info  = WAWP()->user_manager->get_user_info( $user_id );
		$user_phone = ! empty( $user_info->phone ) ? $user_info->phone : '';

		echo '<h3>' . esc_html__( 'Phone number', 'automation-web-platform' ) . '</h3>';
		echo '<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
			<label for="wawp_user_phone">' . esc_html__( 'Phone number', 'automation-web-platform' ) . '</label>
			<input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="wawp_user_phone" id="wawp_user_phone" value="' . esc_attr( $user_phone ) . '" />
		</p>';
	}

	/**
	 * Save custom phone field from WooCommerce account page.
	 *
	 * @param int $user_id User ID.
	 */
	public function wawp_save_custom_phone_fields( $user_id ) {
		// Nonce check for WooCommerce Edit Account page.
		if ( ! isset( $_POST['save_account_details'] ) || ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['_wpnonce'] ) ), 'save_account_details' ) ) {
			return;
		}

		if ( isset( $_POST['wawp_user_phone'] ) ) {
			$phone = sanitize_text_field( wp_unslash( $_POST['wawp_user_phone'] ) );
			WAWP()->connector->sync_user_phone( $user_id, $phone );
		}
	}

	/**
	 * Sync phone fields on profile update.
	 *
	 * @param int $user_id User ID.
	 */
	public function sync_phone_fields( $user_id ) {
		$billing_phone = get_user_meta( $user_id, 'billing_phone', true );
		if ( $billing_phone ) {
			WAWP()->connector->sync_user_phone( $user_id, $billing_phone );
		}
	}

	/**
	 * Sync phone fields on checkout update user meta.
	 *
	 * @param int   $user_id User ID.
	 * @param array $posted  Posted data.
	 */
	public function sync_checkout_phone_meta( $user_id, $posted ) {
		$billing_phone = isset( $posted['billing_phone'] ) ? sanitize_text_field( $posted['billing_phone'] ) : '';
		if ( $billing_phone ) {
			WAWP()->connector->sync_user_phone( $user_id, $billing_phone );
		}
	}

	/**
	 * Add bulk verification actions to users list.
	 *
	 * @param array $actions Bulk actions.
	 * @return array
	 */
	public function wawp_add_bulk_verification_actions( $actions ) {
		$actions['wawp_mark_verified']         = esc_html__( 'Mark as WhatsApp Verified', 'automation-web-platform' );
		$actions['wawp_mark_unverified']       = esc_html__( 'Mark as WhatsApp Unverified', 'automation-web-platform' );
		$actions['wawp_mark_email_verified']   = esc_html__( 'Mark as Email Verified', 'automation-web-platform' );
		$actions['wawp_mark_email_unverified'] = esc_html__( 'Mark as Email Unverified', 'automation-web-platform' );
		return $actions;
	}

	/**
	 * Handle bulk verification actions.
	 *
	 * @param string $redirect_to Redirect URL.
	 * @param string $action      Action slug.
	 * @param array  $user_ids    User IDs.
	 * @return string
	 */
	public function wawp_handle_bulk_verification_actions( $redirect_to, $action, $user_ids ) {
		if ( ! in_array( $action, array( 'wawp_mark_verified', 'wawp_mark_unverified', 'wawp_mark_email_verified', 'wawp_mark_email_unverified' ), true ) ) {
			return $redirect_to;
		}

		$method = ( strpos( $action, 'email' ) !== false ) ? 'email' : 'whatsapp';
		$status = ( 'wawp_mark_verified' === $action || 'wawp_mark_email_verified' === $action );

		foreach ( $user_ids as $user_id ) {
			WAWP()->user_manager->update_user_verification( $user_id, $method, $status );
		}

		$redirect_to = remove_query_arg( array( 'wawp_bulk_action_count', 'wawp_bulk_action_type' ), $redirect_to );
		return add_query_arg(
			array(
				'wawp_bulk_action_count' => count( $user_ids ),
				'wawp_bulk_action_type'  => $method,
			),
			$redirect_to
		);
	}

	/**
	 * Show admin notice after bulk verification action.
	 */
	public function wawp_verification_bulk_admin_notice() {
		$bulk_count = filter_input( INPUT_GET, 'wawp_bulk_action_count', FILTER_SANITIZE_NUMBER_INT );
		$bulk_type  = filter_input( INPUT_GET, 'wawp_bulk_action_type', FILTER_DEFAULT );
		if ( $bulk_count ) {
			$count = absint( $bulk_count );
			$type  = $bulk_type ? sanitize_key( $bulk_type ) : 'whatsapp';

			if ( 'email' === $type ) {
				// translators: %d: number of users updated.
				$message = sprintf( esc_html__( 'Bulk email verification updated for %d users.', 'automation-web-platform' ), $count );
			} else {
				// translators: %d: number of users updated.
				$message = sprintf( esc_html__( 'Bulk WhatsApp verification updated for %d users.', 'automation-web-platform' ), $count );
			}

			echo '<div class="updated notice is-dismissible"><p>' . esc_html( $message ) . '</p></div>';
		}
	}

	/**
	 * Handle AJAX request to send custom message to user.
	 */
	public function ajax_send_user_custom_message() {
		$this->check_permissions( 'wawp_send_msg_nonce', 'security' );

		$user_id     = (int) filter_input( INPUT_POST, 'user_id', FILTER_SANITIZE_NUMBER_INT );
		$instance_id = filter_input( INPUT_POST, 'instance_id', FILTER_SANITIZE_SPECIAL_CHARS );
		$text        = filter_input( INPUT_POST, 'text', FILTER_SANITIZE_SPECIAL_CHARS );

		$result = $this->handle_send_user_custom_message(
			array(
				'user_id'     => $user_id,
				'instance_id' => $instance_id,
				'text'        => $text,
			)
		);

		if ( $result['success'] ) {
			$this->send_success( $result['message'] );
		} else {
			$this->send_error( $result['message'] );
		}
	}

	/**
	 * Send custom WhatsApp message to user.
	 *
	 * @param array $data Message data.
	 * @return array
	 */
	public function handle_send_user_custom_message( $data ) {
		$user_id     = isset( $data['user_id'] ) ? absint( $data['user_id'] ) : 0;
		$instance_id = isset( $data['instance_id'] ) ? sanitize_text_field( $data['instance_id'] ) : '';
		$text        = isset( $data['text'] ) ? sanitize_textarea_field( $data['text'] ) : '';

		if ( $user_id <= 0 || empty( $instance_id ) || empty( $text ) ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'Missing fields.', 'automation-web-platform' ),
			);
		}

		$phone = WAWP()->user_manager->get_user_phone( $user_id );
		if ( ! $phone ) {
			return array(
				'success' => false,
				'message' => esc_html__( 'No phone found for user.', 'automation-web-platform' ),
			);
		}

		$result = WAWP_Messaging_Service::get_instance()->send(
			$phone,
			array(
				'channel'     => 'whatsapp',
				'message'     => $text,
				'user_id'     => $user_id,
				'instance_id' => $instance_id,
				'context'     => esc_html__( 'Admin Custom Message', 'automation-web-platform' ),
				'send_timing' => 'instant',
			)
		);

		if ( $result ) {
			return array(
				'success' => true,
				'message' => esc_html__( 'Message sent successfully.', 'automation-web-platform' ),
			);
		}

		return array(
			'success' => false,
			'message' => esc_html__( 'Failed to send message via WhatsApp.', 'automation-web-platform' ),
		);
	}

	/**
	 * Enable phone number search bar on users list.
	 */
	public function enable_number_search_bar() {
		add_action( 'restrict_manage_users', array( $this, 'render_number_search_field' ) );
		add_action( 'pre_user_query', array( $this, 'filter_users_by_phone' ), 999 );
	}

	/**
	 * Render the phone number search field.
	 *
	 * @param string $which Top or bottom position.
	 */
	public function render_number_search_field( $which ) {
		if ( 'users.php' !== $GLOBALS['pagenow'] || 'top' !== $which ) {
			return;
		}

		$number_search = filter_input( INPUT_GET, 'number_search', FILTER_SANITIZE_SPECIAL_CHARS );
		$current_value = $number_search ? sanitize_text_field( wp_unslash( $number_search ) ) : '';
		echo '<input type="search" id="number_search_live" name="number_search" value="' . esc_attr( $current_value ) . '" placeholder="' . esc_attr__( 'Search Number...', 'automation-web-platform' ) . '" style="margin-right: 5px;" />';
	}

	/**
	 * Filter users by phone number in admin.
	 *
	 * @param WP_User_Query $user_search User query object.
	 */
	public function filter_users_by_phone( $user_search ) {
		global $wpdb, $pagenow;
		$number_search = filter_input( INPUT_GET, 'number_search', FILTER_SANITIZE_SPECIAL_CHARS );
		if ( 'users.php' !== $pagenow || ! $number_search ) {

			return;
		}

		$search_value = sanitize_text_field( $number_search );

		$like_value = '%' . $wpdb->esc_like( $search_value ) . '%';

		$wawp_user_info_table = WAWP()->user_manager->get_table_name();
		$users_table          = $wpdb->users;
		$usermeta_table       = $wpdb->usermeta;

		$user_search->query_from .= $wpdb->prepare( ' LEFT JOIN %i AS wawp_info ON ( %i.ID = wawp_info.user_id ) LEFT JOIN %i AS meta_billing ON ( %i.ID = meta_billing.user_id AND meta_billing.meta_key = %s ) ', $wawp_user_info_table, $users_table, $usermeta_table, $users_table, 'billing_phone' );

		$condition = $wpdb->prepare( '(wawp_info.phone LIKE %s OR meta_billing.meta_value LIKE %s)', $like_value, $like_value );

		$user_search->query_where .= " AND $condition ";
		$user_search->query_where  = str_replace( 'ID =', "{$users_table}.ID =", $user_search->query_where );
	}
}
