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

use SabaiApps\Directories\Component\Form\Form;
use SabaiApps\Directories\Request;

/**
 * UserField provides a user selection field using select2 with AJAX search.
 * Supports displaying user avatars and usernames, and loading default options.
 */
class UserField extends SelectField {

	/**
	 * Initializes the User field with select2 AJAX settings and default options callback.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		$data += array(
			'#select2'                  => true, // Enable select2 for enhanced dropdown
			'#select2_ajax'             => true, // Enable AJAX loading for select2
			'#select2_ajax_url'         => (string) $this->_application->MainUrl(
				'/_drts/form/user',
				array( Request::PARAM_CONTENT_TYPE => 'json' )
			),
			'#select2_tags'             => false, // Disable tag creation
			'#select2_item_image_key'   => 'gravatar', // Use gravatar as item image
			'#select2_item_text_key'    => 'username', // Use username as item text
			'#default_options_callback' => array( $this, '_getDefaultOptions' ), // Callback for default options
		);

		return parent::formFieldInit( $name, $data, $form );
	}

	/**
	 * Loads default user options for the select2 dropdown.
	 *
	 * @param mixed $defaultValue
	 * @param array $options
	 */
	public function _getDefaultOptions( $defaultValue, array &$options ) {
		$identities = $this->_application->UserIdentity( $defaultValue );
		foreach ( $identities as $identity ) {
			$options[ $identity->id ] = $identity->name;
			// Example for more detailed option structure:
			// $id = $identity->id;
			// $text = $identity->name;
			// $defaultItems[] = [
			// 'id' => $id,
			// 'text' => $this->_application->H($text),
			// 'username' => $identity->username,
			// 'gravatar' => $this->_application->System_Url_gravatar($identity->email, 24),
			// ];
		}
	}
}
