<?php
namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

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

if ( ! class_exists( 'HelloPlus_date_field_formatter' ) ) {

	class HelloPlus_date_field_formatter {

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

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

		/**
		 * Constructor method to initialize hooks.
		 */
		public function __construct() {
			add_action( 'wp_enqueue_scripts', array( $this, 'register_assets' ) );
			add_action( 'elementor/element/ehp-form/section_form_fields/before_section_end', array( $this, 'update_controls' ), 100, 2 );
			add_action( 'hello_plus/forms/render/item', array( $this, 'render_custom_date_format' ), 10, 3 );
		}

		/**
		 * Register scripts/styles if needed.
		 */
		public function register_assets() {
            wp_register_script(
                'helloplus-date-formatter',
                CFKEF_PLUGIN_URL . 'assets/helloplus-addons/js/helloplus-date-format.js',
                array( 'jquery' ),
                CFKEF_PLUGIN_VERSION,
                true
            );

            wp_enqueue_script( 'helloplus-date-formatter' );
		}

		/**
		 * Add custom date format control to Date field.
		 *
		 * @param \Elementor\Element_Base $widget
		 */
		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 = $control_data['fields'];

            // Define your custom control
            $date_format_control = array(
                'form_date_format' => array(
                    'name'         => 'form_date_format',
                    'label'        => esc_html__( 'Date Format', 'cool-formkit' ),
                    'type'         => \Elementor\Controls_Manager::SELECT2,
                    'options'      => array(
                        'Y-m-d' => esc_html__( 'YYYY-MM-DD', 'cool-formkit' ),
                        'Y/m/d' => esc_html__( 'YYYY/MM/DD', 'cool-formkit' ),
                        'd/m/Y' => esc_html__( 'DD/MM/YYYY', 'cool-formkit' ),
                        'd-m-Y' => esc_html__( 'DD-MM-YYYY', 'cool-formkit' ),
                        'm/d/Y' => esc_html__( 'MM/DD/YYYY', 'cool-formkit' ),
                        'm-d-Y' => esc_html__( 'MM-DD-YYYY', 'cool-formkit' ),
						
                    ),
                    'default'      => 'Y-m-d',
                    'condition'    => array(
                        'field_type' => 'date',
                    ),
                    'tab'          => 'content',
                    'inner_tab'    => 'form_fields_content_tab',
                    'tabs_wrapper' => 'form_fields_tabs',
                ),
            );

            // Insert after the "required" field
            $new_fields = array();
            foreach ( $field_controls as $key => $control ) {
                $new_fields[ $key ] = $control;

                if ( 'required' === $key ) {
                    // Insert our custom control right after "required"
                    $new_fields = array_merge( $new_fields, $date_format_control );
                }
            }

            $control_data['fields'] = $new_fields;
            $widget->update_control( 'form_fields', $control_data );
        }


		/**
		 * Render the date format value on frontend.
		 *
		 * @param array $item
		 * @param int $item_index
		 * @param \ElementorPro\Modules\Forms\Classes\Form_Record $form
		 * @return array
		 */
		public function render_custom_date_format( $item, $item_index, $form ) {
			if ( 'date' !== $item['field_type'] ) {
				return $item;
			}

			try {
				$reflection = new \ReflectionClass( $form );
				$property = $reflection->getProperty( 'widget' );
				$property->setAccessible( true );
				$widget = $property->getValue( $form );

			} catch ( \ReflectionException $e ) {
				return $field; 
			}

			if ( ! empty( $item['form_date_format'] ) ) {
				// Inject placeholder and data attribute for JS control (optional)
				$widget->add_render_attribute(
					'input' . $item_index,
					array(
						'data-date-format'   => esc_attr( $item['form_date_format'] ),
					)
				);
			}

			return $item;
		}
	}
}
