<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Elementor Form Field - Range-Slider
 *
 * Add a new "Range Slider" field to Elementor form widget.
 *
 * @since 1.0.0
 */

 if(!class_exists('Cfkef_Create_range_field')) {	
class Cfkef_Create_range_field  extends \ElementorPro\Modules\Forms\Fields\Field_Base {


    
	public $depended_scripts = array( 'rsfe-icon-range-slider', 'rsfe-icon-range-slider-custom' );
	public $depended_styles = array( 'rsfe-icon-range-slider-style', 'rsfe-icon-range-slider-custom-style' );


	/**
	 * Get field type.
	 *
	 * Retrieve range-slider field unique ID.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return string Field type.
	 */
	public function get_type() {
		return 'slider';
	}

	/**
	 * Get field name.
	 *
	 * Retrieve Range-Slider field label.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return string Field name.
	 */
	public function get_name() {
		return esc_html__( 'Range Slider', 'cool-formkit' );
	}


	/**
	 * Render field output on the frontend.
	 *
	 * Written in PHP and used to generate the final HTML.
	 *
	 * @since 1.0.0
	 * @access public
	 * @param mixed $item
	 * @param mixed $item_index
	 * @param mixed $form
	 * @return void
	 */
	public function render( $item, $item_index, $form ) {
		$min      = empty( $item['rsfe_minimum_value'] ) ? 0 : $item['rsfe_minimum_value'];
		$max      = (int) $item['rsfe_maximum_value'];
		$input_id = esc_attr( $item['_id'] );
		if ( ( empty( $item['rsfe_maximum_value'] ) && ! empty( $item['rsfe_minimum_value'] ) ) && $min >= $max ) {
			$max = ( $min * 3 );
		}
		$skin = isset( $item['rsfe_skin'] ) && 'custom' === $item['rsfe_skin'] ? 'custom' : '';

		$form->add_render_attribute(
			'input' . $item_index,
			array(
				'size'                => '1',
				'class'               => 'elementor-field-textual form-range-field ',
				'data-min'            => esc_attr( $min ),
				'data-max'            => empty( $item['rsfe_maximum_value'] ) && empty( $item['rsfe_minimum_value'] ) ? esc_attr( $item['rsfe_maximum_value'] ) : esc_attr( $max ),
				'data-step'           => esc_attr( $item['rsfe_step_value'] ),
				'data-skin'           => isset( $item['rsfe_skin'] ) && 'custom' !== $item['rsfe_skin'] ? esc_attr( $item['rsfe_skin'] ) : '',
				'data-custom-skin'    => esc_attr( $skin ),
				'data-type'    => esc_attr( $item['rsfe_range_type'] ),
				'data-prefix'         => esc_attr( wp_kses_post($item['rsfe_prefix']) ),
				'data-postfix'        => esc_attr( wp_kses_post($item['rsfe_postfix']) ),
				'active-color'        => esc_attr( $item['resfe_active_slider_color'] ),
				'data-input-id'       => esc_attr( $input_id ),
				'data-from'           => esc_attr( $item['rsfe_from_value'] ),
				'data-to'           => esc_attr( $item['rsfe_to_value'] ),
				'data-inactive-color' => esc_attr( $item['resfe_inactive_line_color'] ),
			)
		);

       // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $form->get_render_attribute_string() is safe
		echo '<input ' . $form->get_render_attribute_string( 'input' . $item_index ) . '>';
	}


	/**
	 * Field validation.
	 *
	 * Validate range slider field value to ensure it complies to certain rules.
	 *
	 * @since 1.0.0
	 * @access public
	 * @param \ElementorPro\Modules\Forms\Classes\Field_Base   $field
	 * @param \ElementorPro\Modules\Forms\Classes\Form_Record  $record
	 * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
	 * @return void
	 */
	public function validation( $field, $record, $ajax_handler ) {

		$field_id                = $field['id'];
		$field_type              = $field['type'];
		$field_value             = empty( $field['value'] ) ? '' : (int) $field['value'];
		$field_require           = $field['required'];
		$min_value               = '';
		$max_value               = '';
		$rsfe_step_value         = '';
		$submitted_form_settings = $record->get( 'form_settings' );
		foreach ( $submitted_form_settings['form_fields'] as $id => $form_field[] ) {

			foreach ( $form_field as $key => $data ) {
				if ( ( $field_id == $data['custom_id'] ) && ( $field_type == $data['field_type'] ) ) {
					$min_value       = empty( $data['rsfe_minimum_value'] ) ? '' : (int) $data['rsfe_minimum_value'];
					$max_value       = empty( $data['rsfe_maximum_value'] ) ? '' : (int) $data['rsfe_maximum_value'];
					$rsfe_step_value = (int) $data['rsfe_step_value'];
				}
			}
		}

		if ( empty( $max_value ) && ! empty( $min_value ) && $min_value >= $max_value ) {
			$max_value = $min_value * 3;
		}

		$max_value = empty( $max_value ) ? 100 : $max_value;
		$min_value = empty( $min_value ) ? 0 : $min_value;

		if ( ! empty( $field_value ) && ! preg_match( '/^[0-9-]*$/', $field_value ) ) {
			$ajax_handler->add_error( $field_id, sprintf( esc_html__( 'The field value only contains number.', 'cool-formkit' ), $min_value ) );
		}

		 // Add an error message if the field value is less than the minimum value
		if ( ! empty( $field_value ) && ! empty( $min_value ) && ( $field_value < $min_value ) ) {
			// translators: %s is the input field min value.
			$ajax_handler->add_error( $field_id, sprintf( esc_html__( 'The field value must be greater than or equal to %s.', 'cool-formkit' ), $min_value ) );
		}

		// Add an error message if the field value is greater than the maximum value
		if ( ! empty( $field_value ) && ! empty( $max_value ) && ( $field_value > $max_value ) ) {
			// translators: %s is the input field max value.
			$ajax_handler->add_error( $field_id, sprintf( esc_html__( 'The field value must be less than or equal to %s.', 'cool-formkit' ), $max_value ) );
		}

		// Additional validation for required fields
		if ( $field_require && empty( $field_value ) ) {
			$ajax_handler->add_error( $field_id, esc_html__( 'This field is required.', 'cool-formkit' ) );
		}
	}

	/**
	 * Update form widget controls.
	 *
	 * Add input fields to allow the user to customize the Range  field form for elementor.
	 *
	 * @since 1.0.0
	 * @access public
	 * @param \Elementor\Widget_Base $widget The form widget instance.
	 * @return void
	 */
	public function update_controls( $widget ) {
		$elementor = \ElementorPro\Plugin::elementor();

		$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(

			// minimum value setting
			'rsfe_minimum_value'        => array(
				'name'         => 'rsfe_minimum_value',
				'label'        => esc_html__( 'Min Value', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::NUMBER,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'default'      => '5',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			// maximum value setting
			'rsfe_maximum_value'        => array(
				'name'         => 'rsfe_maximum_value',
				'label'        => esc_html__( 'Max Value', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::NUMBER,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'default'      => '100',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			// step value setting
			'rsfe_step_value'           => array(
				'name'         => 'rsfe_step_value',
				'label'        => esc_html__( 'Step', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::NUMBER,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'default'      => '5',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			// default value setting
			'rsfe_from_value'           => array(
				'name'         => 'rsfe_from_value',
				'label'        => esc_html__( 'Start From ', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::NUMBER,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'default'      => '25',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			'rsfe_to_value'           => array(
				'name'         => 'rsfe_to_value',
				'label'        => esc_html__( 'End Value', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::NUMBER,
				'condition'    => array(
					'field_type' => $this->get_type(),
					'rsfe_range_type' => 'double'
				),
				'description' => esc_html__( 'Set the default (end) value for the double-ended range slider.', 'elementor-range-slider' ),

				'default'      => '100',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			// styles setting for range slider

			'rsfe_skin'                 => array(
				'name'         => 'rsfe_skin',
				'label'        => esc_html__( 'Styles', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SELECT,
				'default'      => 'round',
				'options'      => array(
					'custom' => esc_html__( 'Simple', 'cool-formkit' ),
					'flat'   => esc_html__( 'Flat', 'cool-formkit' ),
					'round'  => esc_html__( 'Round', 'cool-formkit' ),
					'square' => esc_html__( 'Square', 'cool-formkit' ),
					'modern' => esc_html__( 'Modern', 'cool-formkit' ),
					'sharp' => esc_html__( 'Sharp', 'cool-formkit' ),
					'big' => esc_html__( 'big', 'cool-formkit' ),

				),
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			'rsfe_range_type'                 => array(
				'name'         => 'rsfe_range_type',
				'label'        => esc_html__( 'Range Type', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SELECT,
				'default'      => 'single',
				'options'      => array(
					'single' => esc_html__( 'Single', 'cool-formkit' ),
					'double'   => esc_html__( 'Double', 'cool-formkit' ),
				),
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			// prefix setting
			'rsfe_prefix'               => array(
				'name'         => 'rsfe_prefix',
				'label'        => esc_html__( 'Before', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				// 'ai'           => array(
				// 'active' => false,
				// ),
			),

			// postfix setting
			'rsfe_postfix'              => array(
				'name'         => 'rsfe_postfix',
				'label'        => esc_html__( 'After', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				 // 'ai'           => array(
				// 'active' => false,
				// ),
			),

			// active color setting
			'resfe_active_slider_color' =>
			array(
				'name'         => 'resfe_active_slider_color',
				'label'        => esc_html__( 'Active Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .elementor-field-type-slider.elementor-field-group{{CURRENT_ITEM}}' => '--rsfe-skin-color: {{VALUE}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

			// inactive color setting
			'resfe_inactive_line_color' =>
			array(
				'name'         => 'resfe_inactive_line_color',
				'label'        => esc_html__( 'Inactive color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .elementor-field-type-slider.elementor-field-group{{CURRENT_ITEM}}' => '--rsfe-inactive-color: {{VALUE}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),
		);

		$control_data['fields'] = $this->inject_field_controls( $control_data['fields'], $field_controls );

		$widget->update_control( 'form_fields', $control_data );
	}


	/**
	 * Field constructor.
	 *
	 * Used to add a script to the Elementor editor preview.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return void
	 */
	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' ) );
	}

	public function add_assets_files(){
		$js_common_dep = array( 'jquery', 'rsfe-icon-range-slider', '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);
        }

		// Enqueue Ion.RangeSlider JavaScript file
		wp_register_script( 'rsfe-icon-range-slider', CFKEF_PLUGIN_URL . 'assets/js/icon-range-slider.js', array( 'jquery' ), CFKEF_PLUGIN_VERSION, true );
		// Enqueue Ion.RangeSlider CSS file
		wp_register_style( 'rsfe-icon-range-slider-style', CFKEF_PLUGIN_URL . 'assets/css/icon-range-slider-css.css', array(), CFKEF_PLUGIN_VERSION );

		// Enqueue Custom Css file
		wp_register_style( 'rsfe-icon-range-slider-custom-style', CFKEF_PLUGIN_URL . 'assets/css/range-slider-custom.css', array(), CFKEF_PLUGIN_VERSION );
		// Enqueue Custom Javascrit file
		wp_register_script( 'rsfe-icon-range-slider-custom', CFKEF_PLUGIN_URL . 'assets/js/range-slider-custom.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );
		
	}

	/**
     * Get script dependencies for this field.
     *
     * @return array
     */
    public function get_script_depends() : array {
        return $this->depended_scripts;
    }

	/**
     * Get style dependencies for this field.
     *
     * @return array
     */
    public function get_style_depends() : array {
        return $this->depended_styles;
    }


	/**
	 * Elementor editor preview.
	 *
	 * Add a hook to the footer of the editor preview screen.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return void
	 */
	public function editor_preview_footer() {
		add_action( 'wp_footer', array( $this, 'content_template_script' ) );
	}



	/**
	 * Content template script.
	 *
	 * Add content template alternative, to display the field in Elemntor editor.
	 *
	 * @since 1.0.0
	 * @access public
	 * @return void
	 */
	public function content_template_script() {         ?>
		<script>
			jQuery(document).ready(() => {
				elementor.hooks.addFilter(
					'elementor_pro/forms/content_template/field/<?php echo esc_html( $this->get_type() ); ?>',

					function(inputField, item, i) {
						const fieldId = `form_field_${i}`;
						const fieldClass = `elementor-field-textual form-range-field  elementor-field ${item.css_classes}`;
						const dataMinEmpty = undefined === item['rsfe_minimum_value'] || '' === item['rsfe_minimum_value'];
						const dataMaxEmpty = undefined === item['rsfe_maximum_value'] || '' === item['rsfe_maximum_value'];
						const rangeType = item['rsfe_range_type'];
						const dataMin = dataMinEmpty ? 0: item['rsfe_minimum_value'];
						let dataMax = dataMaxEmpty ? 100: item['rsfe_maximum_value'];
						
						if((dataMaxEmpty && !dataMinEmpty) && (dataMin >= dataMax)){
							dataMax=dataMin * 3;
						}
						const skin='custom' === item['rsfe_skin'] ? 'custom' : '';
						const dataStep = undefined === item['rsfe_maximum_value'] || '' === item['rsfe_maximum_value'] ? 0 : item['rsfe_step_value'];
						const skinType ='custom' !== item['rsfe_skin'] ? item['rsfe_skin'] : '';
						const preFixValue = undefined === item['rsfe_prefix'] ? '': item['rsfe_prefix'];
						const postFixValue = undefined === item['rsfe_postfix'] ? '': item['rsfe_postfix'];
						const formValue = item['rsfe_from_value'];
						const toValue = item['rsfe_to_value'];
						const inputId = item['_id'];
						
						
			
						return `<input id="${fieldId}" class="${fieldClass}" data-min="${dataMin}" data-max="${dataMax}" data-step="${dataStep}" data-skin="${skinType}" data-prefix="${preFixValue}" data-postfix="${postFixValue}" data-custom-skin="${skin}" data-from="${formValue}" data-to="${toValue}" data-type="${rangeType}"   data-input-id="${inputId}">`;
					}, 10, 3
				);

			});
		</script>
		<?php
	}
}
}
