<?php
namespace SabaiApps\Directories\Component\Form\Controller;

use SabaiApps\Directories\Controller;
use SabaiApps\Directories\Context;

/**
 * User controller for AJAX user search in forms.
 * Handles AJAX requests to search for user identities by name.
 */
class User extends Controller {

	protected function _doExecute( Context $context ) {
		// Only allow AJAX requests
		if ( ! $context->getRequest()->isAjax() ) {
			$context->setBadRequestError();
			return;
		}

		// Get the search term from the request
		$term = trim( $context->getRequest()->asStr( 'query' ) );
		if ( strlen( $term ) < 2 ) {
			$context->setBadRequestError();
			return;
		}

		// Set pagination and fetch user identities
		$limit               = 20;
		$offset              = ( $context->getRequest()->asInt( $this->getPlatform()->getPageParam(), 1 ) - 1 ) * $limit;
		$context->identities = $this->getPlatform()->getUserIdentityFetcher()->search( $term, $limit, $offset, 'name', 'ASC' );
		$context->addTemplate( 'form_user' );
	}
}
