<?php
namespace Cool_FormKit_Pro\Widgets\HelloPlusAddons;

use HelloPlus\Modules\Forms\Fields\Field_Base;
use HelloPlus\Includes\Utils;

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

/**
 * Elementor Form Field - Calculator
 *
 * Add a new "Calculator" field to Elementor form widget.
 *
 * @since 1.0.0
 */
if(!class_exists('HelloPlus_Cfkef_Calculator_Field')) { 
class HelloPlus_Cfkef_Calculator_Field extends Field_Base {

    public $depended_scripts = array(
		'helloplus-calculator-script',
	);
    public $depended_styles = array(
		'helloplus-calculator-style',
	);

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

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

    /**
     * Render field output on the frontend.
     *
     * @since 1.0.0
     * @param mixed $item
     * @param mixed $item_index
     * @param mixed $form
     * @return void
     */
    public function render($item, $item_index, $form) {
        $form_settings = $form->get_settings_for_display();
        $input_size = !empty($form_settings['input_size']) ? $form_settings['input_size'] : 'md';
        $font_family = !empty($form_settings['field_typography_font_family']) ? $form_settings['field_typography_font_family']:"";
        $field_name = $form->get_attribute_name($item, $item_index);
        $repeater_wrapper = 'wrapper-'.$item['custom_id'];

        // 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 coolform-calculator coolform-calculator-result elementor-size-'.esc_attr($input_size) ,
                'readonly' => 'readonly',
                'name' => esc_attr($field_name),
                'style' => 'display: none',
            ]
        );
    
        $form->add_render_attribute(
            $repeater_wrapper,
            [
                'class' => 'cfkef-calculator-wrapper elementor-repeater-item-'.$item['_id'],
                'data-calculation-formula' => esc_attr($item['calculation_formula']),
                'data-before-text' => esc_attr($item['before_text']),
                'data-after-text' => esc_attr($item['after_text']),
                'data-decimal-seperator' => esc_attr($item['decimal_seperator']),
                'data-thousand-seperator' => esc_attr($item['thousand_seperator']),
                'data-decimal-count' => esc_attr($item['decimal_count']),
            ]
        );
        // Render the input field with the attributes
        echo '<div class="cfkef-calculator-container">';
            echo '<div ' . $form->get_render_attribute_string($repeater_wrapper) . '>';
                echo '<div class="cfkef-calculator-outputbox"></div>';
            echo '</div>';
        echo '</div>';

        echo '<input type="text" ' . $form->get_render_attribute_string($field_name) . '>';
    }
    

    /**
     * Update form widget controls.
     *
     * Add input fields to allow the user to customize the calculator field.
     *
     * @since 1.0.0
     * @param \Elementor\Widget_Base $widget The form widget instance.
     * @return void
     */
    public function update_controls($widget) {
        $widget_name = $widget->get_name();
        
        if($widget_name !== 'ehp-form'){
            return;
        }

        $elementor = Utils::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 = [
            'calculation_formula' => [
                'name' => 'calculation_formula',
                'label' => esc_html__('Calculation Formula', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::TEXTAREA,
                'description' => esc_html__('Enter the calculation formula using field IDs. Example: field_1 * field_2', 'cool-formkit'),
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'ai' => [
					'active' => false,
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            'number_format' => [
                'name' => 'number_format',
                'label' => esc_html__('Number Format', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => esc_html__( 'Yes', 'cool-formkit' ),
				'label_off' => esc_html__( 'No', 'cool-formkit' ),
                'return_value' => 'yes',
                'default' => 'yes',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            
            'before_text' => [
                'name' => 'before_text',
                'label' => esc_html__('Before Text', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'description' => esc_html__('Enter text to display before the calculated value. For example, to show "$" before the number, enter ($) (space included).', 'cool-formkit'),
                'condition' => [
                    'field_type' => $this->get_type(),
                    'number_format' => 'yes',
                ],
                'ai' => [
					'active' => false,
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            'after_text' => [
                'name' => 'after_text',
                'label' => esc_html__('After Text', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'description' => esc_html__('Enter text to display after the calculated value. For example, to show "USD" after the number, enter (USD) (space included).', 'cool-formkit'),
                'condition' => [
                    'field_type' => $this->get_type(),
                    'number_format' => 'yes',
                ],
                'ai' => [
					'active' => false,
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            'decimal_seperator' => [
                'name' => 'decimal_seperator',
                'label' => esc_html__('Decimal Seperator', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    '.' => esc_html__( 'Period ( . )', 'cool-formkit' ),
                    ',' => esc_html__( 'Comma ( , )', 'cool-formkit' ),
				],
                'default' => '.',
                'condition' => [
                    'field_type' => $this->get_type(),
                    'number_format' => 'yes',
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            'thousand_seperator' => [
                'name' => 'thousand_seperator',
                'label' => esc_html__('Thousand Seperator', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    '' => esc_html__( 'None', 'cool-formkit' ),
                    ',' => esc_html__( 'Comma ( , )', 'cool-formkit' ),
                    '.' => esc_html__( 'Period ( . )', 'cool-formkit' ),
				],
                'default' => ',',
                'condition' => [
                    'field_type' => $this->get_type(),
                    'number_format' => 'yes',
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            'decimal_count' => [
                'name' => 'decimal_count',
                'label' => esc_html__('Decimal Count', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::NUMBER,
				'step' => 1,
				'default' => 2,
                'condition' => [
                    'field_type' => $this->get_type(),
                    'number_format' => 'yes',
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            // style controls
            'cal_border_color' => [
				'name'         => 'cal_border_color',
				'label'        => esc_html__( 'Border Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
                // 'default'      => '#69727d', 
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
                'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-border-color: {{VALUE}}',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'cal_background_color' => [
				'name'         => 'cal_background_color',
				'label'        => esc_html__( 'Background Color', 'cool-formkit' ),
                'default'      => '#F2F2F2',
				'type'         => \Elementor\Controls_Manager::COLOR,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
                'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-background-color: {{VALUE}}',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_input_background_color' => [
				'name'         => 'cal_input_background_color',
				'label'        => esc_html__( 'Output Box Background', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
                'default'      => '#3e3ff0',
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
                'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-input-background-color: {{VALUE}}',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_text_color' => [
				'name'         => 'cal_text_color',
				'label'        => esc_html__( 'Label Text Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
                'default'      => '#000', 
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
                'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-text-color: {{VALUE}}',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'outputbox_color' => [
				'name'         => 'outputbox_color',
				'label'        => esc_html__( 'Output Box Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
                'default'      => '#fff', 
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
                'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-outputbox-color: {{VALUE}}',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_font_size' => [
				'name'         => 'cal_font_size',
				'label'        => esc_html__( 'Font Size', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SLIDER,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),  
                'size_units' => [ 'px', '%', 'em', 'rem' ],
				'range'        => array(
					'px' => array(
						'min' => 0,
						'max' => 200,
                    )
                ),
                'default'        => array(
					'size' => '24',
					'unit' => 'px',
				),
                'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-font-size: {{SIZE}}{{UNIT}}',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_border_radius' => [
				'name'         => 'cal_border_radius',
				'label'        => esc_html__( 'Border Radius', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::DIMENSIONS,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
                'size_units' => [ 'px', 'em', 'rem' ],
                'default' => [
					'top' => 17,
					'right' => 17,
					'bottom' => 17,
					'left' => 17,
					'unit' => 'px',
					'isLinked' => true,
				],
                'selectors'    => [
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_height' => [
				'name'         => 'cal_height',
				'label'        => esc_html__( 'Height', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SLIDER,
                'size_units' => [ 'px', 'em', 'rem' ],
				'range'        => array(
					'px' => array(
						'min' => 100,
						'max' => 500,
                    )
                ),
                'default'        => array(
					'size' => 100,
					'unit' => 'px',
				),
				'condition'    => array(
					'field_type' => $this->get_type(),
				),  
                'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-height: {{SIZE}}{{UNIT}}',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_border_width' => [
				'name'         => 'cal_border_width',
				'label'        => esc_html__( 'Border Width', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%', 'em', 'rem' ],
                'default' => [
					'top' => 1,
					'right' => 1,
					'bottom' => 1,
					'left' => 1,
					'unit' => 'px',
					'isLinked' => true,
				],
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
			    'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-border-width: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_padding' => [
				'name'         => 'cal_padding',
				'label'        => esc_html__( 'Padding', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%', 'em', 'rem' ],
                'default' => [
					'top' => 0,
					'right' => 5,
					'bottom' => 0,
					'left' => 5,
					'unit' => 'px',
					'isLinked' => true,
				],
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
			    'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-top-padding: {{TOP}}{{UNIT}};
                    --cal-bottom-padding: {{BOTTOM}}{{UNIT}};
                    --cal-left-padding: {{LEFT}}{{UNIT}};
                    --cal-right-padding: {{RIGHT}}{{UNIT}};',
                ),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],

            'cal_margin' => [
				'name'         => 'cal_margin',
				'label'        => esc_html__( 'Margin', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%', 'em', 'rem' ],
                'default' => [
					'top' => 0,
					'right' => 5,
					'bottom' => 10,
					'left' => 5,
					'unit' => 'px',
					'isLinked' => true,
				],
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
			    'selectors'    => array(
                    '{{WRAPPER}} .is-field-type-calculator.ehp-form__field-group .cfkef-calculator-wrapper{{CURRENT_ITEM}}' => '--cal-margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
				'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.
     *
     * @since 1.0.0
     */
    public function __construct() {
        parent::__construct();
        add_action('elementor/preview/init', [$this, 'editor_preview_footer']);
        add_action( 'wp_enqueue_scripts', array( $this, 'add_assets_files' ) );

        add_action( 'elementor/element/ehp-form/section_form_fields/before_section_end', [ $this, 'update_controls' ] );

    }


    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);
        }

        wp_register_script('helloplus-calculator-script', CFKEF_PLUGIN_URL . 'assets/helloplus-addons/js/helloplus-calculator.js', $js_common_dep, CFKEF_PLUGIN_VERSION, true);
        wp_register_style('helloplus-calculator-style', CFKEF_PLUGIN_URL . 'assets/css/calculator.css', null, CFKEF_PLUGIN_VERSION);

    }


    /**
     * 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() {
        add_action('wp_footer', [$this, 'content_template_script']);
    }

    /**
     * Content template script.
     *
     * @since 1.0.0
     * @return void
     */
    public function content_template_script() {
        ?>
        <script>
        jQuery(document).ready(function() {
            elementor.hooks.addFilter(
                'cool_formkit/forms/content_template/field/<?php echo $this->get_type(); ?>',
                function(inputField, item, i, settings) {

                    const fieldId = `form-field-${item.custom_id}`;
                    const fieldName = `form_fields[${item.custom_id}]`;
                    const inputSize = settings['input_size'] || 'md';
                    const repeaterId = item['_id'];

                    const beforeText = item['before_text'] || '';
                    const afterText = item['after_text'] || '';
                    const calculationFormula = item['calculation_formula'] || '';
                    const decimalSeperator = item['decimal_seperator'] || '';
                    const thousandSeperator = item['thousand_seperator'] || '';
                    const decimalCount = item['decimal_count'] || '';

                    return `
                    <div class="cfkef-calculator-container">
                        <div 
                            class="cfkef-calculator-wrapper elementor-repeater-item-${repeaterId}"
                            data-calculation-formula="${calculationFormula}"
                            data-before-text="${beforeText}"
                            data-after-text="${afterText}"
                            data-decimal-seperator="${decimalSeperator}"
                            data-thousand-seperator="${thousandSeperator}"
                            data-decimal-count="${decimalCount}"
                        >
                            <div class="cfkef-calculator-outputbox"></div>
                        </div>
                    </div>
                    <input 
                        type="text" 
                        id="${fieldId}" 
                        class="elementor-field-textual elementor-calculator elementor-calculator-result elementor-size-${inputSize}"
                        readonly="readonly"
                        name="${fieldName}"
                        style="display: none;"
                    >
                    `;
                }, 10, 3
            );
        });
        </script>
        <?php
    }    

    /**
		 * 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_value   = empty( $field['value'] ) ? '' : $field['value'];
		$field_require = $field['required'];

        if ( $field_require && empty( $field_value ) ) {
			$ajax_handler->add_error(
				$field['id'],
				esc_html__( 'This field is required and cannot be left blank.', 'cool-formkit' )
			);
			return;
		}
    }
}
}
