<?php
namespace Cool_FormKit_Pro\Widgets\Addons;

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


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

if(!class_exists('CoolForm_Image_Radio')) {	
class CoolForm_Image_Radio extends Field_Base {

    public $depended_scripts = ['coolform-image-radio-script'];

	public $depended_styles = ['coolform-image-radio-style'];

    public function get_type() {
        return 'image_radio';
    }

    public function get_name() {
        return esc_html__('Image Radio', 'cool-formkit');
    }

    public function get_script_depends(): array {
		return $this->depended_scripts;
	}

	public function get_style_depends(): array {
		return $this->depended_styles;
	}
    public function render($item, $item_index, $form) {
        $field_name = $form->get_attribute_name($item, $item_index);
        $choose_field_type = $item['choose_field_type'];
        $choices = $item['choices'];
        $choose_style = $item['choose_style'];
    
        // Initialize an empty string to store the generated HTML
        $html_output = '';
    
        switch ($choose_field_type) {
            case 'radio':
                foreach ($choices as $choice) {
                    $form->add_render_attribute(
                        $field_name . '-' . $choice['value'],
                        [
                            'type' => 'radio',
                            'id' => 'form-field-' . $item["custom_id"],
                            'name' => $field_name,
                            'value' => $choice['value'],
                            'class' => 'cool-form__field coolform-radio',
                            'data-widget-id' => $item['_id']
                        ]
                    );
    
                    $html_output .= '<label class="image-radio-label ' . $choose_style . ' elementor-field">';
                    if ($choice['image_or_icon'] === "image_opt" && !empty($choice['image']['url'])) {
                        $html_output .= '<img src="' . esc_url($choice['image']['url']) . '" alt="' . esc_attr($choice['label']) . '">';
                    } elseif ($choice['image_or_icon'] === "icon_opt" && !empty($choice['icon'])) {
                        ob_start();
                        \Elementor\Icons_Manager::render_icon($choice['icon'], ['aria-hidden' => 'true']);
                        $html_output .= ob_get_clean();
                    }
                    $html_output .= '<input ' . $form->get_render_attribute_string($field_name . '-' . $choice['value']) . '>';
                    $html_output .= esc_html($choice['label']);
                    $html_output .= '</label>';
                }
                break;
    
            case 'checkbox':
                foreach ($choices as $choice) {
                    $form->add_render_attribute(
                        $field_name . '-' . $choice['value'],
                        [
                            'type' => 'checkbox',
                            'id' => 'form-field-' . $item["custom_id"],
                            'name' => $field_name . '[]',
                            'value' => $choice['value'],
                            'class' => 'cool-form__field coolform-checkbox',
                            'data-widget-id' => $item['_id']
                        ]
                    );
    
                    $html_output .= '<label class="image-radio-label ' . $choose_style . ' elementor-field">';
                    if ($choice['image_or_icon'] === "image_opt" && !empty($choice['image']['url'])) {
                        $html_output .= '<img src="' . esc_url($choice['image']['url']) . '" alt="' . esc_attr($choice['label']) . '">';
                    } elseif ($choice['image_or_icon'] === "icon_opt" && !empty($choice['icon'])) {
                        ob_start();
                        \Elementor\Icons_Manager::render_icon($choice['icon'], ['aria-hidden' => 'true']);
                        $html_output .= ob_get_clean();
                    }
                    $html_output .= '<input ' . $form->get_render_attribute_string($field_name . '-' . $choice['value']) . '>';
                    $html_output .= esc_html($choice['label']);
                    $html_output .= '</label>';
                }
                break;
    
            case 'select':
                $form->add_render_attribute(
                    $field_name,
                    [
                        'name' => $field_name,
                        'id' => 'form-field-' . $item["custom_id"],
                        'class' => 'cool-form__field elementor-select',
                    ]
                );
    
                $html_output .= '<select ' . $form->get_render_attribute_string($field_name) . '>';
                foreach ($choices as $choice) {
                    $html_output .= '<option value="' . esc_attr($choice['value']) . '">' . esc_html($choice['label']) . '</option>';
                }
                $html_output .= '</select>';
                break;
        }
    
        // Echo the generated HTML inside a div wrapper
        echo '<div class="elementor-field-subgroup">' . $html_output . '</div>';
    }
    

    public function update_controls($widget) {
        $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 = [
            'choose_field_type' => [
                'name' => 'choose_field_type',
                'label' => esc_html__('Field Type', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'radio' => esc_html__('Radio', 'cool-formkit'),
                    'checkbox' => esc_html__('Checkbox', 'cool-formkit'),
                    // 'select' => esc_html__('Select', 'cool-formkit'),
                ],
                'default' => 'radio',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            'choose_style' => [
                'name' => 'choose_style',
                'label' => esc_html__('Choose Style', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => [
                    'horizontal' => esc_html__('Horizontal', 'cool-formkit'),
                    'vertical' => esc_html__('Vertical', 'cool-formkit'),
                ],
                'default' => 'vertical',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_selected_border_color' => [
				'name'         => 'radio_image_selected_border_color',
				'label'        => esc_html__( 'Selected Border Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-selected-border-color: {{VALUE}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_selected_background_color' => [
				'name'         => 'radio_image_selected_background_color',
				'label'        => esc_html__( 'Selected Background Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-selected-background-color: {{VALUE}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_selected_text_color' => [
				'name'         => 'radio_image_selected_text_color',
				'label'        => esc_html__( 'Selected Text Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-selected-text-color: {{VALUE}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_hover_border_color' => [
				'name'         => 'radio_image_hover_border_color',
				'label'        => esc_html__( 'Hover Border Color', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::COLOR,
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-hover-border-color: {{VALUE}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_icon_img_size' => [
				'name'         => 'radio_image_icon_img_size',
				'label'        => esc_html__( 'Image/Icon Size', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SLIDER,
				'size_units'   => array( 'px' ),
				'range'        => array(
					'px' => array(
						'min' => 10,
						'max' => 200,
                    )
                ),
                'default'        => array(
					'size' => 100,
					'unit' => 'px',
				),
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-image-icon-size: {{SIZE}}{{UNIT}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_gap' => [
				'name'         => 'radio_image_gap',
				'label'        => esc_html__( 'Gap Between Fields', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SLIDER,
				'size_units'   => array( 'px' ),
				'range'        => array(
					'px' => array(
						'min' => 1,
						'max' => 50,
                    )
                ),
                'default'        => array(
					'size' => 5,
					'unit' => 'px',
				),
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-field-gap: {{SIZE}}{{UNIT}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_min_width' => [
				'name'         => 'radio_image_min_width',
				'label'        => esc_html__( 'Min Width', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SLIDER,
				'size_units'   => array( '%' ),
				'range'        => array(
					'%' => array(
						'min' => 1,
						'max' => 100,
                    )
                ),
                'default'        => array(
					'size' => 20,
					'unit' => '%',
				),
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-field-min-width: {{SIZE}}{{UNIT}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'radio_image_padding' => [
				'name'         => 'radio_image_padding',
				'label'        => esc_html__( 'Padding', 'cool-formkit' ),
				'type'         => \Elementor\Controls_Manager::SLIDER,
				'size_units'   => array( 'px' ),
				'range'        => array(
					'px' => array(
						'min' => 1,
						'max' => 100,
                    )
                ),
                'default'        => array(
					'size' => 20,
					'unit' => 'px',
				),
				'condition'    => array(
					'field_type' => $this->get_type(),
				),
				'selectors'    => array(
					'{{WRAPPER}} .is-field-type-image_radio.cool-form__field-group{{CURRENT_ITEM}}' => '--ri-field-padding: {{SIZE}}{{UNIT}}',
				),
				'tab'          => 'content',
				'inner_tab'    => 'form_fields_advanced_tab',
				'tabs_wrapper' => 'form_fields_tabs',
            ],
            'choices' => [
                'name' => 'choices',
                'label' => esc_html__('Fields', 'cool-formkit'),
                'type' => \Elementor\Controls_Manager::REPEATER,
                'fields' => [
                    [
                        'name' => 'label',
                        'label' => esc_html__('Label', 'cool-formkit'),
                        'type' => \Elementor\Controls_Manager::TEXT,
                        'default' => esc_html__('Item ', 'cool-formkit'),
                    ],
                    [
                        'name' => 'value',
                        'label' => esc_html__('Value', 'cool-formkit'),
                        'type' => \Elementor\Controls_Manager::TEXT,
                        'default' => '',
                    ],
                    [
                        'name' => 'image_or_icon',
                        'label' => esc_html__('Image/Icon', 'cool-formkit'),
                        'type' => \Elementor\Controls_Manager::SELECT,
                        'default' => 'image_opt',
                        'options' => [
                            'image_opt' => esc_html__('Image', 'cool-formkit'),
                            'icon_opt' => esc_html__('Icon', 'cool-formkit'),
                        ],
                    ],
                    [
                        'name' => 'image',
                        'label' => esc_html__('Image', 'cool-formkit'),
                        'type' => \Elementor\Controls_Manager::MEDIA,
                        'default' => [],
                        'condition' => [
                            'image_or_icon' => 'image_opt',
                        ],
                    ],
                    [
                        'name' => 'icon',
                        'label' => esc_html__('Icon', 'cool-formkit'),
                        'type' => \Elementor\Controls_Manager::ICONS,
                        'default' => [],
                        'condition' => [
                            'image_or_icon' => 'icon_opt',
                        ],
                    ],
                ],
                'default' => [
                    [
                        'label' => esc_html__('Item 1', 'cool-formkit'),
                        'value' => 'item',
                    ],
                ],
				'title_field'    => '{{{ label  }}}',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab' => 'content',
                'inner_tab' => 'form_fields_content_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);
    }

    public function __construct() {
        parent::__construct();
        add_action('elementor/preview/init', [$this, 'editor_preview_footer']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
    }

    public function editor_preview_footer() {
        add_action('wp_footer', [$this, 'content_template_script']);
    }

    public function enqueue_scripts() {
        wp_register_style('coolform-image-radio-style', CFKEF_PLUGIN_URL . 'assets/addons/css/coolform-image-radio.css', null, CFKEF_PLUGIN_VERSION);
        wp_register_script('coolform-image-radio-script', CFKEF_PLUGIN_URL . 'assets/addons/js/coolform-image-radio.js', array('jquery'), CFKEF_PLUGIN_VERSION, true);
    }

    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) {
                    const fieldId = `form_field_${i}`;
                    const chooseFieldType = item['choose_field_type'];
                    const chooseStyle = item['choose_style']
                    let html = '<div class="elementor-field-subgroup">';

                    if (chooseFieldType === 'select') {
                        html += `<select id="${fieldId}" class="cool-form__field elementor-select" name="${item.custom_id}">`;
                        item.choices.forEach(choice => {
                            html += `<option value="${choice.value}">${choice.label}</option>`;
                        });
                        html += '</select>';
                    } else {
                        item.choices.forEach(choice => {
                            const inputType = chooseFieldType === 'radio' ? 'radio' : 'checkbox';
                            html += `<label class="image-radio-label ${chooseStyle} elementor-field">`;
                            if ((chooseFieldType === 'radio' || chooseFieldType === 'checkbox') && choice['image_or_icon'] === "image_opt" && choice['image'] && choice['image']['url']) {
                                html += `<img src="${choice['image']['url']}" alt="${choice.label}">`;
                            } else if ((chooseFieldType === 'radio' || chooseFieldType === 'checkbox') && choice['image_or_icon'] === "icon_opt" && choice['icon']) {
                                if(choice['icon']['library'] === 'svg'){
                                    html += `<img src="${choice['icon']['value']['url']}" />`;
                                }else{
                                    html += `<i class="${choice['icon']['value']}"></i>`;
                                }
                            }

                            html += `<input type="${inputType}" id="${fieldId}-${choice.value}" class="cool-form__field coolform-${inputType}" name="${item.custom_id}" value="${choice.value}" data-widget-id="${item._id}"> ${choice.label}`;
                            html += '</label>';
                        });
                    }

                    html += '</div>';
                    return html;
                }, 10, 3
            );
        });
        </script>
        <?php
    }

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