<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
/**
 * Class for managing the date field new setting in Elementor forms.
 *
 * This class adds new setting to date field of Elementor forms.
 *
 * @package ccfef
 *
 * @version 1.0.0
 */

if(!class_exists('Restrict_Date_Add_on')) { 
class Restrict_Date_Add_on {

	/**
	 * Plugin instance.
	 *
	 * @var Restrict_Date_Add_on
	 *
	 * @access private
	 * @var null
	 */
	private static $instance = null;

	/**
	 * Get the plugin instance.
	 *
	 * @return Restrict_Date_Add_on
	 * @static
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor method to initialize actions and assets.
	 */
	public function __construct() {
		add_action('wp_enqueue_scripts', array($this,'register_scripts'));
		add_action( 'elementor_pro/forms/render/item', array( $this, 'elementor_form_date_field_rendering'), 9, 3 );
		add_action( 'elementor/element/form/section_form_fields/before_section_end', array( $this, 'update_controls' ), 100, 2 );
		add_action( 'elementor/preview/init', array( $this, 'editor_inline_JS'));
	}

	/**
	 * Render method to append div element containing all the user data attributes.
	 */
	function elementor_form_date_field_rendering($field, $item, $form) {

		$link_min_fieldId = "";
		$link_max_fieldId = "";
		$data=array();
		if (isset($field['field_type']) && $field['field_type'] === 'date') {
			wp_enqueue_script( 'date-frontend-script' );

			$link_min_fieldId = isset($field['link_min_fieldId']) ? $field['link_min_fieldId'] : '';
			$link_max_fieldId = isset($field['link_max_fieldId']) ? $field['link_max_fieldId'] : '';
			$fieldId = isset($field['_id']) ? $field['_id'] : '';
			$customId = isset($field['custom_id']) ? $field['custom_id'] : '';

			if(!empty($link_max_fieldId)){
				$data['ccfef_link_max_fieldId']=$link_max_fieldId;
			}

			if(!empty($link_min_fieldId)){
				$data['ccfef_link_min_fieldId']=$link_min_fieldId;
			}
			if(!empty($fieldId)){
				$data['ccfef_fieldId']=$fieldId;
			}

			if(!empty($customId)){
				$data['ccfef_customId']=$customId;
			}

			$form->add_render_attribute(
				'input' . $item,
				$data
			);
		}
		return $field;  
	}
	

	public function editor_inline_JS() {
		wp_enqueue_script( 'restrict-date-editor-js', CFKEF_PLUGIN_URL . 'assets/js/restrict-date-editor.js', array(), CFKEF_PLUGIN_VERSION, true );
		wp_enqueue_script('date-frontend-script');
	}

	public function register_scripts(){
		// Detect if we are in the Elementor Preview iframe (safe for elementor-frontend)
		$is_preview = ( isset( $_GET['elementor-preview'] ) || isset( $_GET['preview'] ) );

		$deps = array('jquery');
		if ( $is_preview || ! is_admin() ) {
			$deps[] = 'elementor-frontend'; // ✅ only in preview or frontend
		}
		
		wp_register_script(
			'date-frontend-script',
			CFKEF_PLUGIN_URL . 'assets/js/restrict-date.js',
			$deps,
			CFKEF_PLUGIN_VERSION,
			true
		);
	}



	/**
	 * Update form widget controls to include for select field.
	 *
	 * Adds country code control to allow users to customize the select 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;
		}

		$minLink_placeholder_desc = sprintf(
			"%s",
			esc_html__( 'Enter the Field ID of the date field that will be linked to this field, will dynamically set its min attribute.', 'cool-formkit'),
	
		);
		$maxLink_placeholder_desc = sprintf(
			"%s",
			esc_html__( 'Enter the Field ID of the date field that will be linked to this field, will dynamically set its max attribute.', 'cool-formkit'),
	
		);

		$field_controls1 = array(
			'link_min_fieldId'   => array(
				'name'         => 'link_min_fieldId',
				'label'        => esc_html__( 'Link Min Field', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'condition'    => array(
					'field_type' => 'date',
				),
				'description'  => $minLink_placeholder_desc,
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

		);

		$field_controls2 = array(
			'link_max_fieldId'   => array(
				'name'         => 'link_max_fieldId',
				'label'        => esc_html__( 'Link Max Field', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::TEXT,
				'condition'    => array(
					'field_type' => 'date',
				),
				'description'  => $maxLink_placeholder_desc,
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_content_tab',
				'tabs_wrapper' => 'form_fields_tabs',
			),

		);

        $fields = $control_data['fields'];
        $new_fields = [];

        foreach ($fields as $key => $field) {
            $new_fields[$key] = $field;

            if ($key === 'min_date') {
                $new_fields = array_merge($new_fields, $field_controls1);
            }
            if ($key === 'max_date') {
                $new_fields = array_merge($new_fields, $field_controls2);
            }
        }

        // Update the control data with the new fields
        $control_data['fields'] = $new_fields;
        $widget->update_control( 'form_fields', $control_data );
	}
}

// Instantiate the handler
Restrict_Date_Add_on::get_instance();
}