<?php

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

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

	public $depended_scripts = array(
		'month-week-field-script' , 'flatpickr', 'month-flatpickr-script', 'week-flatpickr-script',
	);

	public $depended_styles = array(
		'flatpickr', 'month-flatpickr-style', 'month-field-style',
	);

    /**
     * Get field type.
     *
     * Retrieve calculator field unique ID.
     *
     * @since 1.0.0
     * @return string
     */
	public function get_type() {
		return 'monthWeek';
	}

    /**
     * Get field name.
     *
     * Retrieve calculator field label.
     *
     * @since 1.0.0
     * @return string
     */
	public function get_name() {
		return __( 'Month/Week', 'cool-formkit' );
	}

	/**
	 * @param      $item
	 * @param      $item_index
	 * @param Form       $form
	 */

     public function render($item, $item_index, $form) {
        $form_settings = $form->get_settings_for_display();
        $field_name = $form->get_attribute_name($item, $item_index);


        $field_type = isset($item['cfkef-pick']) ? esc_attr($item['cfkef-pick']) : 'month';
        $placeholder = isset($item['cfkef-monthWeek-placeholder']) ? esc_attr($item['cfkef-monthWeek-placeholder']) : '';
        // Add attributes directly to the input field
        $form->add_render_attribute(
            $field_name,
            [
                'id' => 'form-field-' . esc_attr($item["custom_id"]),
                'class' => 'elementor-field-textual elementor-' . $field_type . ' elementor-repeater-item-' . $item['_id'] , 
                'placeholder' => esc_attr($placeholder),
                'data-min' => esc_attr($item['cfkef-monthWeek-min']),
                'data-max' => esc_attr($item['cfkef-monthWeek-max']),
                'data-default' => esc_attr($item['cfkef-monthWeek-default']),
                'name' => esc_attr($field_name),
                'value' => esc_attr($item['cfkef-monthWeek-default']),
                'readonly' => 'readonly', // Add readonly attribute if necessary
            ]
        );
    
        // Output the input field
        echo '<input type="text" ' . $form->get_render_attribute_string($field_name) . '>';
    }
    
    /**
     * Field constructor.
     *
     * @since 1.0.0
     */
	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' ) );
	}

	/**
	 * Register common assets for the plugin.
	 */
	public function add_assets_files() {
		$js_common_dep = array( 'jquery', '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);
        }

        /** MonthSelect scripts and styles */
		wp_register_script( 'month-week-field-script', CFKEF_PLUGIN_URL . 'assets/js/monthWeek.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );
		wp_register_script( 'month-flatpickr-script', CFKEF_PLUGIN_URL . 'assets/js/flatpickr/monthSelect/index.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );

        wp_register_style( 'month-flatpickr-style', CFKEF_PLUGIN_URL . 'assets/css/flatpickr/monthSelect/style.css', array(), CFKEF_PLUGIN_VERSION, 'all' );
        wp_register_style( 'month-field-style', CFKEF_PLUGIN_URL . 'assets/css/month-field.css', array(), CFKEF_PLUGIN_VERSION, 'all' );

        /** WeekSelect scripts and styles */
		wp_register_script( 'week-flatpickr-script', CFKEF_PLUGIN_URL . 'assets/js/flatpickr/weekSelect/index.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.
     *
     * @since 1.0.0
     * @return void
     */
	public function editor_preview_footer() {
        wp_enqueue_script('flatpickr');
		add_action( 'wp_footer', array( $this, 'content_template_script' ) );
	}

     /**
     * Content template script.
     *
     * @since 1.0.0
     * @return void
     */
    public function content_template_script() {
        ?>
   <script>
    jQuery( document ).ready( () => {

        elementor.hooks.addFilter(
            'elementor_pro/forms/content_template/field/<?php echo esc_attr( $this->get_type() ); ?>',
            function ( inputField, item, i ) {
                <?php if ( 'monthWeek' === esc_attr( $this->get_type() ) ) { ?>

                const field_type_choosen = '' !== item['cfkef-pick'] ? item['cfkef-pick'] : 'month';
                const placeholder = undefined !== item['cfkef-monthWeek-placeholder'] ? item['cfkef-monthWeek-placeholder'] : '';

                const min = undefined !== item['cfkef-monthWeek-min'] ? item['cfkef-monthWeek-min'] : '';
                const max = undefined !== item['cfkef-monthWeek-max'] ? item['cfkef-monthWeek-max'] : '';
                const defaultVal = undefined !== item['cfkef-monthWeek-default'] ? item['cfkef-monthWeek-default'] : '';
                const fieldName = 'form_field_' + i;
                <?php } ?> 

                const fieldType  = 'text';  
                const fieldId    = `form_field_${i}`;
                const fieldClass = `elementor-field-textual elementor-field elementor-${item['cfkef-pick']} elementor-repeater-item-${item['_id']}`;

                // Return the updated input HTML structure
                return `
                    <input type="${fieldType}" 
                           id="${fieldId}" 
                           class="${fieldClass}" 
                           value="${defaultVal}" 
                           placeholder="${placeholder}"
                           data-min="${min}"
                           data-max="${max}"
                           data-default="${defaultVal}"
                           readonly="readonly">`;
            }, 10, 3  
        );
    });
    </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(
            'cfkef-monthWeek-placeholder'  => array(
				'name'         => 'cfkef-monthWeek-placeholder',
				'label'        => esc_html__( 'Placeholder', 'cool-formkit' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'condition' => array(
                    'field_type' => 'monthWeek',
                    ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
            'cfkef-pick'  => array(
				'name'         => 'cfkef-pick',
				'label'        => esc_html__( 'Pick', 'cool-formkit' ),
                'type'         => \Elementor\Controls_Manager::SELECT,
                'options'      => array(
                    'month' => esc_html__( 'Month', 'cool-formkit' ),
                    'week'   => esc_html__( 'Week', 'cool-formkit' )
                    ),
                'condition' => array(
                    'field_type' => 'monthWeek',
                    ),
                'default'      => 'month',
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
            'cfkef-monthWeek-min'  => array(
				'name'         => 'cfkef-monthWeek-min',
				'label'        => esc_html__( 'Min. Date', 'cool-formkit' ),
                'type' => \Elementor\Controls_Manager::DATE_TIME,
                'label_block'    => false,
                'condition' => array(
                    'field_type' => 'monthWeek',
                    'cfkef-pick' => 'month',
                    ),
                'picker_options' => [
                    'enableTime'  => false,
                    'weekNumbers' => true,
                ],
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
            'cfkef-monthWeek-max'  => array(
				'name'         => 'cfkef-monthWeek-max',
				'label'        => esc_html__( 'Max. Date', 'cool-formkit' ),
                'type' => \Elementor\Controls_Manager::DATE_TIME,
                'label_block'    => false,
                'condition' => array(
                    'field_type' => 'monthWeek',
                    'cfkef-pick' => 'month',
                    ),
                'picker_options' => [
                    'enableTime'  => false,
                    'weekNumbers' => true,
                ],    
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
				'ai'           => array(
					'active' => false,
				),
			),
            'cfkef-monthWeek-default'  => array(
				'name'         => 'cfkef-monthWeek-default',
				'label'        => esc_html__( 'Default Value', 'cool-formkit' ),
                'type' => \Elementor\Controls_Manager::TEXT,
                'condition' => array(
                    'field_type' => 'monthWeek',
                    ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_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 );
	}
}
}
?>
