<?php
/**
 * Search
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Resets;

/**
 * Setup user details.
 */
function search() {
	add_filter( 'user_search_columns', __NAMESPACE__ . '\filter_user_search_columns' );
	add_action( 'pre_user_query', __NAMESPACE__ . '\filter_search_query' );
}
add_action( 'init', __NAMESPACE__ . '\search' );

/**
 * Change user search columns
 */
function filter_user_search_columns() {
	$search_columns = [ 'user_login', 'user_nicename' ];

	return $search_columns;
}

/**
 * Optimize search query.
 *
 * @param object $query Query params.
 */
function filter_search_query( $query ) {
	if ( $query->query_vars['search'] ) {
		global $wpdb;

		$search_query = trim( $query->query_vars['search'], '*' );

		$query->query_from .= " JOIN {$wpdb->usermeta} fname ON fname.user_id = {$wpdb->users}.ID AND fname.meta_key = 'first_name'";
		$query->query_from .= " JOIN {$wpdb->usermeta} lname ON lname.user_id = {$wpdb->users}.ID AND lname.meta_key = 'last_name'";

		$search_by = [
			'user_login',
			'user_email',
			'user_nicename',
			'fname.meta_value',
			'lname.meta_value',
		];

		$query->query_where = 'WHERE 1=1' . $query->get_search_sql( $search_query, $search_by, 'both' );
	}
}
