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

use SabaiApps\Directories\Component\Form\Form;

/**
 * AddMoreField provides a field that allows users to dynamically add more items to a form.
 * Handles initialization, rendering, and JavaScript integration for "Add More" functionality.
 */
class AddMoreField extends ItemField {

	/**
	 * Initializes the AddMore field and registers the pre-render callback.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		$form->settings['#pre_render'][ __CLASS__ ] = array( $this, 'preRenderCallback' );

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

	/**
	 * Renders the AddMore button and passes rendering to the parent.
	 *
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldRender( array &$data, Form $form ) {
		$data['#markup'] = sprintf(
			'<button type="button" class="%1$sbtn %1$sbtn-outline-secondary %1$sbtn-sm drts-form-field-add" data-field-max-num="%2$d" data-field-next-index="%3$d"><i class="fas fa-plus fa-fw"></i> %4$s</button>',
			DRTS_BS_PREFIX,
			empty( $data['#max_num'] ) ? 0 : $data['#max_num'],
			empty( $data['#next_index'] ) ? 1 : $data['#next_index'],
			$this->_application->H( isset( $data['#add_more_text'] ) ? $data['#add_more_text'] : __( 'Add More', 'directories-pro' ) )
		);
		parent::formFieldRender( $data, $form );
	}

	/**
	 * Pre-render callback to load required scripts and initialize the AddMore field.
	 *
	 * @param Form $form
	 */
	public function preRenderCallback( $form ) {
		$this->_application->getPlatform()->loadJqueryUiJs( array( 'sortable' ) );
		$this->_application->getPlatform()->addJsFile( 'form-field-addmore.min.js', 'drts-form-field-addmore', array( 'drts-form' ) );
		$form->settings['#js_ready'][] = sprintf(
			'DRTS.Form.field.addmore("#%s");',
			$form->settings['#id']
		);
	}
}
