<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Cfkef_Toggle_Field extends \ElementorPro\Modules\Forms\Fields\Field_Base {

    public $depended_styles = array('cfkef-toggle-field-main-css');
    public $depended_scripts = array('cfkef-toggle-field-main-js');

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

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

    public function render( $item, $item_index, $form_instance ) {
        $field_id     = esc_attr( $item['custom_id'] );
        $unique_id = $item['_id'];
        $field_name   = method_exists( $form_instance, 'get_attribute_name' )
            ? $form_instance->get_attribute_name( $item )
            : sanitize_title( $field_id );

        $item['css_classes'] .= 'cfefuniqueId_' .$unique_id;
        $field_value  = ! empty( $item['field_value'] ) ? $item['field_value'] : '';
        $default_checked = ! empty( $item['toggle_check_default'] ) && $item['toggle_check_default'] === 'yes';
        $is_checked = checked( $field_value === 'on' || ( empty( $field_value ) && $default_checked ), true, false );
        $is_required  = ! empty( $item['required'] ) ? 'required' : '';
        $css_classes  = esc_attr( $item['css_classes'] ?? '' );
        $off_text = ! empty( $item['toggle_off_text'] ) ? esc_html( $item['toggle_off_text'] ) : '';
        $on_text  = ! empty( $item['toggle_on_text'] ) ? esc_html( $item['toggle_on_text'] ) : '';
        $toggle_text_position = ! empty( $item['toggle_text_position'] ) ? esc_attr( $item['toggle_text_position'] ) : '';
        
        echo '<div class="elementor-field-subgroup ' . $css_classes . ' elementor-toggle-switch-wrapper cfkef-switcher" data-toggle-text-position="'.$toggle_text_position.'">';
            echo '<span class="toggle-field-switch-option">';
                echo '<input type="hidden" name="' . esc_attr( $field_name ) . '" value="' . esc_attr( $off_text ) . '">';
                echo '<input 
                    type="checkbox"
                    name="' . esc_attr( $field_name ) . '" 
                    id="form-field-' . esc_attr( $field_id ) . '" 
                    value="' . ( $field_value === 'on' || ( empty( $field_value ) && $default_checked ) ? esc_attr( $on_text ) : esc_attr( $off_text ) ) . '" 
                    ' . $is_checked . ' 
                    ' . $is_required . ' 
                    class="cfkef-switch-Input" 
                    data-on-text="' . esc_attr( $on_text ) . '" 
                    data-off-text="' . esc_attr( $off_text ) . '">';

                    echo '<label for="form-field-' . esc_attr( $field_id ) . '" class="cfkef-switch-label">';

                    if ( $toggle_text_position === 'before_only' ) {
                        echo esc_html( $off_text ) . '<span class="toggle-span"></span>';
                    } elseif ( $toggle_text_position === 'after_only' ) {
                        echo '<span class="toggle-span"></span>' . esc_html( $on_text );
                    } else { 
                        echo esc_html( $off_text ) . '<span class="toggle-span"></span>' . esc_html( $on_text );
                    }

                    echo '</label>';

            echo '</span>';
        echo '</div>';
    }


	public function validation( $field, $record, $ajax_handler ) {
		if ( ! empty( $field['required'] ) && empty( $field['value'] ) ) {
			$ajax_handler->add_error( $field['id'], esc_html__( 'This field is required.', 'cool-formkit' ) );
		}
	}

	public function update_controls( $widget ) {
		$elementor = \ElementorPro\Plugin::elementor();

		$control_data = $elementor->controls_manager->get_control_from_stack( $widget->get_unique_name(), 'form_fields' );

		if ( is_wp_error( $control_data ) ) {
			return;
		}

		$toggle_controls = [
            'toggle_off_text' => [
                'name'      => 'toggle_off_text',
                'label'     => esc_html__( 'Off Text', 'cool-formkit' ),
                'type'      => \Elementor\Controls_Manager::TEXT,
                'default'   => 'Off',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab'          => 'content',
                'inner_tab'    => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
                'ai'           => array(
					'active' => false,
				),
            ],
            'toggle_on_text' => [
                'name'      => 'toggle_on_text',
                'label'     => esc_html__( 'On Text', 'cool-formkit' ),
                'type'      => \Elementor\Controls_Manager::TEXT,
                'default'   => 'On',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab'          => 'content',
                'inner_tab'    => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
                'ai'           => array(
					'active' => false,
				),
            ],
            'toggle_text_position' => [
                'name'    => 'toggle_text_position',
                'label'   => esc_html__( 'Text Position', 'cool-formkit' ),
                'type'    => \Elementor\Controls_Manager::SELECT,
                'default' => 'before_after',
                'options' => [
                    'before_after'    => esc_html__( 'Before / After', 'cool-formkit' ),
                    'after_only'   => esc_html__( 'After Only', 'cool-formkit' ),
                    'before_only'       => esc_html__( 'Before Only', 'cool-formkit' ),
                ],
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab'          => 'content',
                'inner_tab'    => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
                'ai'           => array(
					'active' => false,
				),
            ],
            'toggle_size' => [
                'name'    => 'toggle_size',
                'label'   => esc_html__( 'Toggle Size', 'cool-formkit' ),
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => ['px'],
				'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 20,
                        'step' => 1,
                    ],
                ],
				'default' => [
                    'unit' => 'px',
                    'size' => 0,
                ],
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab'          => 'content',
                'inner_tab'    => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
                'selectors'    => array(
					'{{WRAPPER}} :where(.elementor-field-type-toggle).elementor-field-group{{CURRENT_ITEM}}' => '--toggle-size: {{SIZE}}px',
				),
            ],
            'toggle_default_color' => [
                'name'    => 'toggle_default_color',
                'label'   => esc_html__( 'Unselected Color', 'cool-formkit' ),
				'type' => \Elementor\Controls_Manager::COLOR,
				'default' => '#E0E0E0',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab'          => 'content',
                'inner_tab'    => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
                'ai'           => array(
					'active' => false,
				),
                'selectors'    => array(
					'{{WRAPPER}} :where(.elementor-field-type-toggle).elementor-field-group{{CURRENT_ITEM}}' => '--toggle-default-color: {{VALUE}}',
				),
            ],
            'toggle_selected_color' => [
                'name'    => 'toggle_selected_color',
                'label'   => esc_html__( 'Selected Color', 'cool-formkit' ),
				'type' => \Elementor\Controls_Manager::COLOR,
				'default' => '#E0E0E0',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab'          => 'content',
                'inner_tab'    => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
                'ai'           => array(
					'active' => false,
				),
                'selectors'    => array(
					'{{WRAPPER}} :where(.elementor-field-type-toggle).elementor-field-group{{CURRENT_ITEM}}' => '--toggle-selected-color: {{VALUE}}',
				),
            ],
            'toggle_check_default' => [
                'name'    => 'toggle_check_default',
                'label'   => esc_html__( 'Checked By Default', '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'      => 'no',
                'condition' => [
                    'field_type' => $this->get_type(),
                ],
                'tab'          => 'content',
                'inner_tab'    => 'form_fields_content_tab',
                'tabs_wrapper' => 'form_fields_tabs',
                'ai'           => array(
					'active' => false,
				),
            ],
		];

		$control_data['fields'] = $this->inject_field_controls( $control_data['fields'], $toggle_controls );

		$widget->update_control( 'form_fields', $control_data );
	}

	public function __construct() {
		parent::__construct();

        add_action( 'wp_enqueue_scripts', array( $this, 'add_assets_files' ) );
        add_action( 'elementor/preview/init', [ $this, 'editor_preview_footer' ] );
	}

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

    public function add_assets_files(){
		// Enqueue Custom Css file
		wp_register_style( 'cfkef-toggle-field-main-css', CFKEF_PLUGIN_URL . 'assets/css/toggle-field-main.css', array(), CFKEF_PLUGIN_VERSION );
		wp_register_script( 'cfkef-toggle-field-main-js', CFKEF_PLUGIN_URL . 'assets/js/toggle-field-main.js', array(), CFKEF_PLUGIN_VERSION );
	}

    public function content_template_script() {
        ?>
        <script>
        jQuery(document).ready(function () {
            elementor.hooks.addFilter(
                'elementor_pro/forms/content_template/field/<?php echo $this->get_type(); ?>',
                function (inputField, item, i) {
                    const fieldId    = item.custom_id || `field_${i}`;
                    const fieldName  = item.custom_id || `custom_toggle_${i}`;
                    const isChecked =
                        item.field_value === 'on' ||
                        (!item.field_value && item.toggle_check_default === 'yes') ? 'checked' : '';
                    const isRequired = item.required ? 'required' : '';
                    const cssClass   = item.css_classes || '';
                    const onText     = item.toggle_on_text || '';
                    const offText    = item.toggle_off_text || '';
                    const position   = item.toggle_text_position || '';
                    const uniqueId   = item._id || i;

                    return `
                        <div class="elementor-field-subgroup ${cssClass} elementor-toggle-switch-wrapper cfkef-switcher cfefuniqueId_${uniqueId}" data-toggle-text-position="${position}">
                            <span class="toggle-field-switch-option">
                                <input type="hidden" name="${fieldName}" value="${offText}" />
                                <input 
                                    type="checkbox" 
                                    id="form-field-${fieldId}" 
                                    name="${fieldName}" 
                                    value="${isChecked ? onText : offText}"
                                    ${isChecked} 
                                    ${isRequired}
                                    class="cfkef-switch-Input" 
                                    data-on-text="${onText}" 
                                    data-off-text="${offText}" 
                                />

                                <label for="form-field-${fieldId}" class="cfkef-switch-label">
                                    ${
                                        position === 'before_only'
                                            ? `${offText}<span class="toggle-span"></span>`
                                            : position === 'after_only'
                                            ? `<span class="toggle-span"></span>${onText}`
                                            : `${offText}<span class="toggle-span"></span>${onText}`
                                    }
                                </label>
                            </span>
                        </div>
                    `;
                },
                10,
                3
            );
        });
        </script>
        <?php
    }

    /**
     * Get style dependencies for this field.
     *
     * @return array
     */
    public function get_style_depends() : array {
        return $this->depended_styles;
    }

    /**
     * Get script dependencies for this field.
     *
     * @return array
     */
    public function get_script_depends() : array {
        return $this->depended_scripts;
    }
}
