<?php

namespace GravityKit\GravityActions;

use WP_User_Query;

/**
 * Class AJAX
 *
 * @since   1.3
 *
 * @package GravityKit\GravityActions
 */
class AJAX extends AbstractSingleton {
	/**
	 * Initialize the class and set its properties.
	 *
	 * @since       1.0.0
	 */
	protected function register() {

	}

	/**
	 * Nonce Action name for fetching users.
	 *
	 * @since 1.3
	 *
	 * @var string
	 */
	public static $get_users_nonce_action = 'gravitykit_actions_ajax_get_users';

	/**
	 * Get users for created_by field.
	 *
	 * @since 1.3
	 *
	 * @return void
	 */
	public function get_users() {
		check_ajax_referer( static::$get_users_nonce_action, 'nonce' );

		if ( empty( $_POST['search'] ) ) {
			wp_send_json_error();
		}

		$search = sanitize_text_field( $_POST['search'] );

		$return = [
			'results' => [],
		];

		$args = [
			'search'         => '*' . esc_attr( $search ) . '*',
			'search_columns' => [ 'user_login', 'user_email', 'display_name', 'user_nicename' ],
			'fields'         => [ 'ID', 'display_name' ],
		];

		$user_query = new WP_User_Query( $args );

		foreach ( $user_query->get_results() as $result ) {
			$return['results'][] = [
				'id'   => $result->ID,
				'text' => $result->display_name,
			];
		}

		wp_send_json_success( $return );
	}
}