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

use SabaiApps\Directories\Component\Form\Form;

/**
 * PasswordField provides a password input field with show/hide toggle.
 * Disables autocomplete and prevents value redisplay for security.
 */
class PasswordField extends TextField {

	/**
	 * Initializes the Password field, disables autocomplete, and sets up pre-render callback.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		unset( $data['#separator'], $data['#mask'] );
		parent::formFieldInit( $name, $data, $form );

		$data['#attributes']['autocomplete'] = 'off';
		if ( empty( $data['#redisplay'] ) ) {
			// Do not display value in HTML to prevent password theft
			$data['#value'] = '';
		}

		if ( ! isset( $form->settings['#pre_render'][ __CLASS__ ] ) ) {
			$form->settings['#pre_render'][ __CLASS__ ] = array( $this, 'preRenderCallbackPassword' );
		}
	}

	/**
	 * Returns the HTML for the password input with an eye icon for toggling visibility.
	 *
	 * @param array  $data
	 * @param string $type
	 * @return string
	 */
	protected function _getInput( array $data, $type ) {
		return parent::_getInput( $data, $type )
			. '<i class="drts-form-password-eye fas fa-eye"></i>';
	}

	/**
	 * Pre-render callback to add JavaScript for toggling password visibility.
	 *
	 * @param Form $form
	 */
	public function preRenderCallbackPassword( Form $form ) {
		$form->settings['#js_ready'][] = '$("#__FORM_ID__").find(".drts-form-password-eye").click(function(){
    var $this = $(this), input = $this.prev("input");
    if (input.attr("type") === "password") {
        input.attr("type", "text");
        $this.removeClass("fa-eye").addClass("fa-eye-slash");
    } else {
        input.attr("type", "password");
        $this.removeClass("fa-eye-slash").addClass("fa-eye");
    }
});';
	}
}
