<?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_Month_Week_Field')) {	
class CoolForm_Month_Week_Field extends Field_Base {

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

	public $depended_styles = array(
		'flatpickr', 'coolform-month-flatpickr-style', 'coolform-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) {
        $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_type   = !empty($item['cfkef-pick']) ? esc_attr($item['cfkef-pick']) : 'month';
        $placeholder  = !empty($item['cfkef-monthWeek-placeholder']) ? esc_attr($item['cfkef-monthWeek-placeholder']) : '';
        $min          = !empty($item['cfkef-monthWeek-min']) ? esc_attr($item['cfkef-monthWeek-min']) : '';
        $max          = !empty($item['cfkef-monthWeek-max']) ? esc_attr($item['cfkef-monthWeek-max']) : '';
        $default_val  = !empty($item['cfkef-monthWeek-default']) ? esc_attr($item['cfkef-monthWeek-default']) : '';
        $input_size   = !empty($settings['input_size']) ? esc_attr($settings['input_size']) : 'md';
        $label        = !empty($item['field_label']) ? $item['field_label'] : '';
        $show_labels  = !empty($settings['show_labels']);

        ?>
        <label class="cool-form-text mdc-text-field mdc-text-field--outlined <?php echo ($label === '' || ! $show_labels) ? 'mdc-text-field--no-label' : ''; ?> cool-field-size-<?php echo $input_size; ?>">
            <span class="mdc-notched-outline">
                <span class="mdc-notched-outline__leading"></span>
                <span class="mdc-notched-outline__notch">
                    <?php if ($label && $show_labels) : ?>
                        <span class="mdc-floating-label" id="monthweek-label-<?php echo esc_attr($item_index); ?>">
                            <?php echo esc_html($label); ?>
                        </span>
                    <?php endif; ?>
                </span>
                <span class="mdc-notched-outline__trailing"></span>
            </span>

            <input 
                type="monthWeek"
                id="<?php echo esc_attr($field_id); ?>"
                name="<?php echo esc_attr($field_name); ?>"
                value="<?php echo $default_val; ?>"
                class="mdc-text-field__input cool-form__field elementor-field elementor-<?php echo $field_type; ?> elementor-size-<?php echo esc_attr($input_size); ?> elementor-repeater-item-<?php echo esc_attr($item['_id']); ?>"
                placeholder="<?php echo $placeholder; ?>"
                data-min="<?php echo $min; ?>"
                data-max="<?php echo $max; ?>"
                data-default="<?php echo $default_val; ?>"
                readonly
            >

            <i aria-hidden="true" class="material-icons mdc-text-field__icon mdc-text-field__icon--trailing cool-<?php echo esc_attr($field_type); ?>-error-icon" style="display:none">error</i>
        </label>

        <div class="mdc-text-field-helper-line">
            <div class="mdc-text-field-helper-text" id="cool-<?php echo esc_attr($field_type); ?>-error" aria-hidden="true"></div>
        </div>
        <?php
    }

    
    /**
     * 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( 'coolform-month-week-field-script', CFKEF_PLUGIN_URL . 'assets/addons/js/coolform-monthWeek.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );
		wp_register_script( 'coolform-month-flatpickr-script', CFKEF_PLUGIN_URL . 'assets/js/flatpickr/monthSelect/index.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true );

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

        /** WeekSelect scripts and styles */
		wp_register_script( 'coolform-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(
                'cool_formkit/forms/content_template/field/<?php echo esc_attr($this->get_type()); ?>',
                function (inputField, item, i, settings) {

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

                    const fieldType = item['cfkef-pick'] || 'month';
                    const placeholder = item['cfkef-monthWeek-placeholder'] || '';
                    const min = item['cfkef-monthWeek-min'] || '';
                    const max = item['cfkef-monthWeek-max'] || '';
                    const defaultVal = item['cfkef-monthWeek-default'] || '';
                    const label = item.field_label || '';
                    const showLabels = settings.show_labels;
                    const inputSize = settings.input_size || 'md';
                    const fieldId = `form_field_${i}`;
                    const inputClasses = `mdc-text-field__input cool-form__field elementor-field elementor-${fieldType} elementor-size-${inputSize} elementor-repeater-item-${item['_id']} ${item.css_classes || ''}`;

                    return `
                        <label class="cool-form-text mdc-text-field mdc-text-field--outlined ${(label === '' || !showLabels) ? 'mdc-text-field--no-label' : ''} cool-field-size-${inputSize}">
                            <span class="mdc-notched-outline">
                                <span class="mdc-notched-outline__leading"></span>
                                <span class="mdc-notched-outline__notch">
                                    ${(label && showLabels) ? `<span class="mdc-floating-label" id="monthweek-label-${i}">${_.escape(label)}</span>` : ''}
                                </span>
                                <span class="mdc-notched-outline__trailing"></span>
                            </span>
                            <input 
                                type="monthWeek"
                                id="${fieldId}"
                                name="form_field_${i}"
                                value="${_.escape(defaultVal)}"
                                class="${inputClasses}"
                                placeholder="${_.escape(placeholder)}"
                                data-min="${_.escape(min)}"
                                data-max="${_.escape(max)}"
                                data-default="${_.escape(defaultVal)}"
                                readonly
                            >
                            <i aria-hidden="true" class="material-icons mdc-text-field__icon mdc-text-field__icon--trailing cool-${fieldType}-error-icon" style="display:none">error</i>
                        </label>
                        <div class="mdc-text-field-helper-line">
                            <div class="mdc-text-field-helper-text" id="cool-${fieldType}-error" aria-hidden="true"></div>
                        </div>
                    `;
                },
                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 );
	}
}
}
?>
