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

use SabaiApps\Directories\Component\Form\Form;

/**
 * IconPickerField provides a button for selecting icons from a set.
 * Supports different icon sets and customizable layout.
 */
class IconPickerField extends AbstractField {

	// Static property to store icon sets used in the form.
	protected static $_iconsets = array();
	// Static property to ensure JS is loaded only once.
	protected static $_jsLoaded;

	/**
	 * Initializes the IconPicker field and registers the pre-render callback.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		$data['#id'] = $form->getFieldId( $name );
		if ( ! isset( $data['#iconset'] ) ) {
			$data['#iconset'] = 'fontawesome';
		}
		self::$_iconsets[ $data['#iconset'] ]       = $data['#iconset'];
		$form->settings['#pre_render'][ __CLASS__ ] = array( $this, 'preRenderCallback' );
	}

	/**
	 * Renders the IconPicker field as a button with icon selection attributes.
	 *
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldRender( array &$data, Form $form ) {
		$data['#attributes']['data-iconset'] = $data['#iconset'];
		if ( isset( $data['#placement'] ) ) {
			$data['#attributes']['data-bs-placement'] = $data['#placement'];
		}
		if ( isset( $data['#default_value'] ) ) {
			$data['#attributes']['data-current'] = trim( $data['#default_value'] );
		}
		if ( isset( $data['#rows'] ) ) {
			$data['#attributes']['data-rows'] = (int) $data['#rows'];
		}
		if ( isset( $data['#cols'] )
			&& in_array( $data['#cols'], array( 1, 2, 3, 4, 6, 12 ) )
		) {
			$data['#attributes']['data-cols'] = $data['#rows'];
		}
		foreach ( array( 'rows', 'cols' ) as $key ) {
			if ( isset( $data[ '#' . $key ] ) ) {
				$data['#attributes'][ 'data-' . $key ] = (int) $data[ '#' . $key ];
			}
		}
		$html = sprintf(
			'<button type="button" name="%1$s" class="%2$sbtn %2$sbtn-outline-secondary %3$s"%4$s></button>',
			$data['#name'],
			DRTS_BS_PREFIX,
			isset( $data['#attributes']['class'] ) ? $this->_application->H( $data['#attributes']['class'] ) : '',
			$this->_application->Attr( $data['#attributes'], 'class' )
		);

		$this->_render( $html, $data, $form );
	}

	/**
	 * Pre-render callback to load icon picker scripts and initialize icon sets.
	 *
	 * @param Form $form
	 */
	public function preRenderCallback( $form ) {
		if ( ! isset( self::$_jsLoaded ) ) {
			self::$_jsLoaded = array();
			$this->_application->Form_Scripts_iconpicker( self::$_iconsets );
		}
		if ( empty( self::$_jsLoaded[ $form->getId() ] ) ) {
			self::$_jsLoaded[ $form->getId() ] = true;
			$form->settings['#js_ready'][]     = sprintf(
				'$("#%s").find(".drts-form-type-iconpicker button").each(function(val) {
    DRTS.Form.field.iconpicker.factory($(this));
});',
				$form->getId()
			);
		}
	}
}
