<?php
namespace Cool_FormKit_Pro\Widgets\Addons;

use Cool_FormKit_Pro\Modules\Forms\Fields\Field_Base;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if(!class_exists('CoolForm_State_Field')) {	
class CoolForm_State_Field extends Field_Base {

	public $depended_scripts = array(
		'coolform-state-list-script',
		'coolform-state-field-script'
	);

	public $depended_styles = array(
		'coolform-state-field-css',
	);

	public function get_type() {
		return 'state';
	}

	public function get_name() {
		return __( 'State', 'cool-formkit' );
	}

	public function get_script_depends(): array {
		return $this->depended_scripts;
	}

	public function get_style_depends(): array {
		return $this->depended_styles;
	}

	/**
	 * @param      $item
	 * @param      $item_index
	 * @param Form       $form
	 */
	public function render( $item, $item_index, $form ) {
		$settings = $form->get_settings_for_display();

		$field_id   = 'form-field-' . esc_attr( $item['custom_id'] );
		$field_name = 'form_fields[' . esc_attr( $item['custom_id'] ) . ']';
		$field_label = ! empty( $item['field_label'] ) ? $item['field_label'] : '';
		$field_value = ! empty( $item['field_value'] ) ? esc_attr( $item['field_value'] ) : '';
		$placeholder = ! empty( $item['placeholder'] ) ? 'placeholder="' . esc_attr( $item['placeholder'] ) . '"' : '';
		$required    = ! empty( $item['required'] ) ? 'required' : '';
		$input_size  = ! empty( $settings['input_size'] ) ? esc_attr( $settings['input_size'] ) : 'md';
		$country_field_id = $item['sfef-field-id'] ?? '';

		?>

		<label class="cool-form-text mdc-text-field mdc-text-field--outlined <?php echo ( $field_label === '' || empty( $settings['show_labels'] ) ) ? 'mdc-text-field--no-label' : ''; ?> cool-field-size-<?php echo esc_attr( $input_size ); ?>">
			<span class="mdc-notched-outline">
				<span class="mdc-notched-outline__leading"></span>
				<span class="mdc-notched-outline__notch">
					<?php if ( $field_label && ! empty( $settings['show_labels'] ) ) : ?>
						<span class="mdc-floating-label" id="state-label-<?php echo esc_attr( $item_index ); ?>">
							<?php echo esc_html( $field_label ); ?>
						</span>
					<?php endif; ?>
				</span>
				<span class="mdc-notched-outline__trailing"></span>
			</span>
			<input 
				type="state"
				id="<?php echo esc_attr( $field_id ); ?>"
				name="<?php echo esc_attr( $field_name ); ?>"
				class="mdc-text-field__input cool-form__field elementor-state-field elementor-field-textual elementor-size-<?php echo esc_attr( $input_size ); ?>"
				value="<?php echo $field_value; ?>"
				<?php echo $placeholder; ?>
				<?php echo $required; ?>
			>
			<i aria-hidden="true" class="material-icons mdc-text-field__icon mdc-text-field__icon--trailing cool-state-error-icon" style="display:none">error</i>
		</label>

		<div class="mdc-text-field-helper-line">
			<div class="mdc-text-field-helper-text" id="cool-state-error" aria-hidden="true"></div>
		</div>

		<span 
			class="sfef-editor-intl-input"
			data-id="<?php echo esc_attr( $field_id ); ?>"
			data-field-id="<?php echo esc_attr( $item['_id'] ); ?>"
			data-country-field-id="<?php echo esc_attr( $country_field_id ); ?>"
			style="display:none;">
		</span>
		<?php
	}



	public function __construct() {
		parent::__construct();
		add_action( 'wp_enqueue_scripts', array( $this, 'add_assets_files' ) );
		add_action( 'elementor/preview/init', array( $this, 'editor_preview_footer' ) );
	}

	/**
     * Get script dependencies for this field.
     *
     * @return array
     */

	/**
	 * Register common assets for the plugin.
	 */
	public function add_assets_files() {
		$js_common_dep = array( 'jquery', 'coolform-state-list-script', 'elementor-frontend' );
        if ( ! \Elementor\Plugin::$instance->preview->is_preview_mode() && is_user_logged_in() ) {
            $js_common_dep = array_merge(array( 'elementor-common' ), $js_common_dep);
        }
		
		wp_register_script( 'coolform-state-list-script', CFKEF_PLUGIN_URL . 'assets/js/state-list.min.js', array(), CFKEF_PLUGIN_VERSION, true );
		wp_register_script( 'coolform-state-field-script', CFKEF_PLUGIN_URL . 'assets/addons/js/coolform-state-field.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );
		wp_register_style( 'coolform-state-field-css', CFKEF_PLUGIN_URL . 'assets/css/state-field.css', CFKEF_PLUGIN_VERSION, true );
	}

	public function editor_preview_footer() {
			add_action( 'wp_footer', array( $this, 'content_template_script' ) );
	}

	public function content_template_script() {
		?>
		<script>
		jQuery(document).ready(() => {
			elementor.hooks.addFilter(
				'cool_formkit/forms/content_template/field/<?php echo esc_attr( $this->get_type() ); ?>',
				function (inputField, item, i, settings) {

					if (item.field_type !== 'state') {
						return inputField;
					}

					const label = item.field_label || '';
					const value = _.escape(item.field_value || '');
					const placeholderAttr = item.placeholder ? `placeholder="${_.escape(item.placeholder)}"` : '';
					const requiredAttr = item.required ? 'required' : '';
					const inputId = `form_field_${i}`;
					const labelId = `state-label-${i}`;
					const countryFieldId = item['sfef-field-id'] || '';
					const inputClasses = `mdc-text-field__input cool-form__field elementor-state-field elementor-field-textual elementor-size-${settings.input_size} ${item.css_classes || ''}`;

					return `
						<label class="cool-form-text mdc-text-field mdc-text-field--outlined ${(label === '' || !settings.show_labels) ? 'mdc-text-field--no-label' : ''} cool-field-size-${settings.input_size}">
							<span class="mdc-notched-outline">
								<span class="mdc-notched-outline__leading"></span>
								<span class="mdc-notched-outline__notch">
									${(label && settings.show_labels)
										? `<span class="mdc-floating-label" id="${labelId}">${_.escape(label)}</span>`
										: ''
									}
								</span>
								<span class="mdc-notched-outline__trailing"></span>
							</span>
							<input 
								type="state"
								id="${inputId}"
								name="form_field_${i}"
								value="${value}"
								class="${inputClasses}"
								${placeholderAttr}
								${requiredAttr}
							>
							<i aria-hidden="true" class="material-icons mdc-text-field__icon mdc-text-field__icon--trailing cool-state-error-icon" style="display:none">error</i>
						</label>
						<div class="mdc-text-field-helper-line">
							<div class="mdc-text-field-helper-text" id="cool-state-error" aria-hidden="true"></div>
						</div>
						<span 
							class="sfef-editor-intl-input" 
							data-id="${inputId}" 
							data-field-id="${item['_id']}" 
							data-country-field-id="${countryFieldId}" 
							style="display: none;">
						</span>
					`;
				},
				10,
				4
			);
		});
		</script>
		<?php
	}




	/**
	 * Update form widget controls to include the country field control.
	 *
	 * Adds country field control to allow users to customize the country field.
	 *
	 * @since 1.0.0
	 * @access public
	 * @param \Elementor\Widget_Base $widget The form widget instance.
	 * @return void
	 */
	public function update_controls( $widget ) {
		$elementor    = \Elementor\Plugin::instance();
		$control_data = $elementor->controls_manager->get_control_from_stack( $widget->get_unique_name(), 'form_fields' );
		if ( is_wp_error( $control_data ) ) {
				return;
		}

		$field_controls = array(
			'sfef-field-id'             => array(
				'name'         => 'sfef-field-id',
				'label'        => esc_html__( 'Country Field Id', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'condition'    => array(
					'field_type' => 'state',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
		);

		$control_data['fields'] = \array_merge( $control_data['fields'], $field_controls );
		$widget->update_control( 'form_fields', $control_data );
	}
}
}
?>
