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

use SabaiApps\Directories\Component\Form\Form;

/**
 * ColorPickerField provides a text field with a color picker UI.
 * Handles initialization, rendering, and JavaScript integration for color selection.
 */
class ColorPickerField extends TextField {

	/**
	 * Initializes the ColorPicker field and registers the pre-render callback.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		// Enable clear button unless hidden input or explicitly disabled
		$data['#add_clear']   = empty( $data['#hide_input'] ) && ( ! isset( $data['#add_clear'] ) || $data['#add_clear'] );
		$data['#placeholder'] = __( 'Select a color', 'directories-pro' );
		$data['#min_length']  = $data['#max_length'] = 7;
		// Register pre-render callback for color picker
		$form->settings['#pre_render'][ __CLASS__ ] = array( $this, 'preRenderCallback' );
		parent::formFieldInit( $name, $data, $form );
	}

	/**
	 * Renders the ColorPicker field as an input or hidden field.
	 *
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldRender( array &$data, Form $form ) {
		if ( ! empty( $data['#hide_input'] ) ) {
			// Render as hidden input if input is hidden
			$data['#attributes']['data-static-open'] = 1;
			$type                                    = 'hidden';
		} else {
			// Render as text input with max width
			$data['#attributes']['style'] = 'max-width:200px;';
			$type                         = 'text';
		}
		$this->_render( $this->_renderInput( $data, $form, $type ), $data, $form );
	}

	/**
	 * Pre-render callback to load scripts and initialize the color picker UI.
	 *
	 * @param Form $form
	 */
	public function preRenderCallback( Form $form ) {
		// Load color picker scripts
		$this->_application->Form_Scripts( array( 'colorpicker' ) );
		// Add JavaScript to initialize color picker on the form
		$form->settings['#js_ready'][] = sprintf(
			'(function() {
    $("#%s").find(".drts-form-type-colorpicker").each(function(){
        DRTS.Form.field.colorpicker($(this)); 
    });
})();',
			$form->settings['#id']
		);
	}
}
