<?php

namespace WeDevs\Wpuf\Pro\Integrations\Elementor;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Elementor integration for WPUF Pro (step field style controls, etc.).
 *
 * @since 4.2.12
 */
class Elementor {

    public function __construct() {
        add_action( 'wpuf_elementor_widget_register_style_controls', [ $this, 'register_step_style_controls' ], 10, 1 );
        add_filter( 'wpuf_elementor_styles_to_enqueue', [ $this, 'add_step_styles_to_enqueue' ], 10, 1 );
        add_filter( 'wpuf_elementor_widget_script_depends', [ $this, 'add_step_script_depends' ], 10, 1 );
        add_filter( 'wpuf_elementor_widget_wrapper_classes', [ $this, 'add_elementor_step_preview_class' ], 10, 3 );
        add_filter( 'wpuf_elementor_widget_wrapper_attributes', [ $this, 'add_elementor_step_preview_attributes' ], 10, 3 );
        add_filter( 'wpuf_render_fields', [ $this, 'limit_to_first_step_in_elementor_preview' ], 10, 2 );
        add_action( 'wpuf_elementor_widget_after_render', [ $this, 'output_step_preview_script' ] );
    }

    /**
     * In Elementor editor/preview, show only the first step of multistep forms (progress bar + first step fields).
     *
     * @since 4.2.12
     *
     * @param array $fields   Form fields.
     * @param int   $form_id Form ID.
     * @return array
     */
    public function limit_to_first_step_in_elementor_preview( $fields, $form_id ) {
        if ( ! $this->is_elementor_edit_or_preview() ) {
            return $fields;
        }

        $settings    = wpuf_get_form_settings( $form_id );
        $multistep_on = ! empty( $settings['enable_multistep'] ) && ( $settings['enable_multistep'] === 'yes' || $settings['enable_multistep'] === 'on' );

        if ( ! $multistep_on ) {
            return $fields;
        }

        $step_start_count = 0;
        foreach ( $fields as $index => $field ) {
            $is_step_start = ( isset( $field['template'] ) && $field['template'] === 'step_start' )
                || ( isset( $field['input_type'] ) && $field['input_type'] === 'step_start' );
            if ( $is_step_start ) {
                $step_start_count++;
                if ( $step_start_count === 2 ) {
                    return array_slice( $fields, 0, $index );
                }
            }
        }

        return $fields;
    }

    /**
     * Whether the current request is in Elementor edit or preview mode.
     *
     * @since 4.2.12
     *
     * @return bool
     */
    private function is_elementor_edit_or_preview() {
        if ( ! class_exists( '\Elementor\Plugin' ) ) {
            return false;
        }
        $plugin = \Elementor\Plugin::$instance;
        if ( isset( $plugin->preview ) && $plugin->preview->is_preview_mode() ) {
            return true;
        }
        if ( isset( $plugin->editor ) && $plugin->editor->is_edit_mode() ) {
            return true;
        }
        return false;
    }

    /**
     * Add step (multistep) styles to the list of styles enqueued in Elementor context.
     *
     * @since 4.2.12
     *
     * @param string[] $style_handles Array of style handles.
     * @return string[]
     */
    public function add_step_styles_to_enqueue( $style_handles ) {
        $style_handles[] = 'wpuf-form-step';
        $style_handles[] = 'wpuf-css-stars';

        if ( $this->is_elementor_edit_or_preview() ) {
            $style_handles[] = 'wpuf-elementor';
        }

        return $style_handles;
    }

    /**
     * Enqueue step (multistep) style and script in Elementor editor and frontend.
     *
     * In editor/preview, form-step.css hides all fieldsets (display: none) until JS adds
     * .field-active to the current step. When that JS runs late or in a different context,
     * the first step stays hidden. We add an override via elementor.css so the fieldset is visible.
     *
     * @since 4.2.12
     *
     * @return void
     */
    public function enqueue_step_assets_in_elementor() {
        wp_enqueue_script( 'jquery-ui-progressbar' );
        wp_enqueue_script( 'wpuf-form-step' );
    }

    /**
     * Add step preview script to widget script dependencies.
     *
     * @since 4.2.12
     *
     * @param string[] $depends Array of script handles.
     * @return string[]
     */
    public function add_step_script_depends( $depends ) {
        if ( $this->is_elementor_edit_or_preview() ) {
            $depends[] = 'wpuf-elementor-step-preview';
        }

        $depends[] = 'wpuf-barrating';

        return $depends;
    }

    /**
     * Output any necessary markup for Elementor preview.
     *
     * The JavaScript is handled by the external wpuf-elementor-step-preview.js file
     * and the CSS is handled by wpuf-elementor.css.
     *
     * @since 4.2.12
     *
     * @param \Elementor\Widget_Base $widget The widget instance.
     * @return void
     */
    public function output_step_preview_script( $widget ) {
        if ( ! $this->is_elementor_edit_or_preview() ) {
            return;
        }

        $settings = $widget->get_settings_for_display();
        $form_id  = isset( $settings['form_id'] ) ? $settings['form_id'] : null;

        if ( empty( $form_id ) ) {
            return;
        }

        $form_settings = wpuf_get_form_settings( $form_id );
        $multistep_on  = ! empty( $form_settings['enable_multistep'] ) && ( $form_settings['enable_multistep'] === 'yes' || $form_settings['enable_multistep'] === 'on' );

        if ( ! $multistep_on ) {
            return;
        }
    }

    /**
     * Add wrapper class in Elementor so the first-step fieldset is visible (overrides form-step.css display: none).
     *
     * @since 4.2.12
     *
     * @param string[] $wrapper_classes Current wrapper classes.
     * @param array    $settings       Widget settings.
     * @param int      $form_id        Form ID.
     * @return string[]
     */
    public function add_elementor_step_preview_class( $wrapper_classes, $settings, $form_id ) {
        if ( ! $this->is_elementor_edit_or_preview() || ! $form_id ) {
            return $wrapper_classes;
        }
        $form_settings = wpuf_get_form_settings( $form_id );
        $multistep_on  = ! empty( $form_settings['enable_multistep'] ) && ( $form_settings['enable_multistep'] === 'yes' || $form_settings['enable_multistep'] === 'on' );

        if ( ! $multistep_on ) {
            return $wrapper_classes;
        }
        $wrapper_classes[] = 'wpuf-elementor-step-preview';
        return $wrapper_classes;
    }

    /**
     * Add wrapper data attribute for multistep type so step JS can run in Elementor preview when the hidden input is missing.
     *
     * @since 4.2.12
     *
     * @param array    $attributes Current wrapper attributes.
     * @param array    $settings   Widget settings.
     * @param int|null $form_id    Form ID.
     * @return array
     */
    public function add_elementor_step_preview_attributes( $attributes, $settings, $form_id ) {
        if ( ! $this->is_elementor_edit_or_preview() || ! $form_id ) {
            return $attributes;
        }
        $form_settings = wpuf_get_form_settings( $form_id );
        $multistep_on  = ! empty( $form_settings['enable_multistep'] ) && ( $form_settings['enable_multistep'] === 'yes' || $form_settings['enable_multistep'] === 'on' );

        if ( ! $multistep_on ) {
            return $attributes;
        }
        $type = isset( $form_settings['multistep_progressbar_type'] ) ? $form_settings['multistep_progressbar_type'] : 'step_by_step';
        $attributes['data-wpuf-multistep-type'] = $type;

        // Count total steps from all fields (not limited)
        $all_fields = wpuf_get_form_fields( $form_id );
        $total_steps = 0;
        foreach ( $all_fields as $field ) {
            $is_step_start = ( isset( $field['template'] ) && $field['template'] === 'step_start' )
                || ( isset( $field['input_type'] ) && $field['input_type'] === 'step_start' );
            if ( $is_step_start ) {
                $total_steps++;
            }
        }

        if ( $total_steps > 0 ) {
            $attributes['data-wpuf-total-steps'] = (string) $total_steps;
        }

        return $attributes;
    }

    /**
     * Register Elementor style controls for the multistep (step) field.
     *
     * @since 4.2.12
     *
     * @param \Elementor\Widget_Base $widget The WPUF form widget instance.
     * @return void
     */
    public function register_step_style_controls( $widget ) {
        $prev_btn_selector = '{{WRAPPER}} .wpuf-form .wpuf-multistep-fieldset .wpuf-multistep-prev-btn';
        $next_btn_selector = '{{WRAPPER}} .wpuf-form .wpuf-multistep-fieldset .wpuf-multistep-next-btn';
        $inactive_selector = '{{WRAPPER}} .wpuf-form .wpuf-multistep-progressbar .wpuf-step-wizard .wpuf-step-item';
        $active_selector   = '{{WRAPPER}} .wpuf-form .wpuf-multistep-progressbar .wpuf-step-wizard .wpuf-step-item.active-step';
        $progressive_fill  = '{{WRAPPER}} .wpuf-form .wpuf-multistep-progressbar .wpuf-progressbar-fill';
        $progressive_track = '{{WRAPPER}} .wpuf-form .wpuf-multistep-progressbar .wpuf-progressbar-track';
        $percent_selector  = '{{WRAPPER}} .wpuf-form .wpuf-multistep-progressbar .wpuf-progressbar-percent';

        $widget->start_controls_section(
            'section_step_style',
            [
                'label' => __( 'Steps', 'wpuf-pro' ),
                'tab'   => Controls_Manager::TAB_STYLE,
            ]
        );

        // Navigation buttons.
        $widget->add_control(
            'step_nav_heading',
            [
                'label' => __( 'Navigation Buttons', 'wpuf-pro' ),
                'type'  => Controls_Manager::HEADING,
            ]
        );

        $widget->start_controls_tabs( 'tabs_step_nav_buttons_style' );

        $widget->start_controls_tab( 'tab_step_nav_buttons_normal', [ 'label' => __( 'Normal', 'wpuf-pro' ) ] );

        $widget->add_control(
            'step_nav_buttons_bg_color',
            [
                'label'     => __( 'Background Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#6b7280',
                'selectors' => [
                    $prev_btn_selector => 'background-color: {{VALUE}};',
                    $next_btn_selector => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_control(
            'step_nav_buttons_text_color',
            [
                'label'     => __( 'Text Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#ffffff',
                'selectors' => [
                    $prev_btn_selector => 'color: {{VALUE}};',
                    $next_btn_selector => 'color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name'     => 'step_nav_buttons_typography',
                'selector' => $prev_btn_selector . ', ' . $next_btn_selector,
                'fields_options' => [
                    'font_weight' => [
                        'default' => '500',
                    ],
                    'font_size' => [
                        'default' => [
                            'unit' => 'px',
                            'size' => '16',
                        ],
                    ],
                ],
            ]
        );

        $widget->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name'     => 'step_nav_buttons_border',
                'selector' => $prev_btn_selector . ', ' . $next_btn_selector,
                'fields_options' => [
                    'border' => [
                        'default' => 'solid',
                    ],
                    'width' => [
                        'default' => [
                            'top'    => '0',
                            'right'  => '0',
                            'bottom' => '0',
                            'left'   => '0',
                        ],
                    ],
                    'color' => [
                        'default' => 'transparent',
                    ],
                ],
            ]
        );

        $widget->add_control(
            'step_nav_buttons_border_radius',
            [
                'label'      => __( 'Border Radius', 'wpuf-pro' ),
                'type'       => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%' ],
                'default'    => [
                    'top'    => '6',
                    'right'  => '6',
                    'bottom' => '6',
                    'left'   => '6',
                    'unit'   => 'px',
                ],
                'selectors'  => [
                    $prev_btn_selector => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                    $next_btn_selector => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $widget->add_responsive_control(
            'step_nav_buttons_padding',
            [
                'label'      => __( 'Padding', 'wpuf-pro' ),
                'type'       => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', 'em', '%' ],
                'default'    => [
                    'top'    => '12',
                    'right'  => '24',
                    'bottom' => '12',
                    'left'   => '24',
                    'unit'   => 'px',
                ],
                'selectors'  => [
                    $prev_btn_selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                    $next_btn_selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $widget->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name'      => 'step_nav_buttons_box_shadow',
                'selector'  => $prev_btn_selector . ', ' . $next_btn_selector,
                'separator' => 'before',
                'fields_options' => [
                    'box_shadow_type' => [
                        'default' => 'yes',
                    ],
                    'box_shadow' => [
                        'default' => [
                            'horizontal' => 0,
                            'vertical'   => 1,
                            'blur'       => 3,
                            'spread'     => 0,
                            'color'      => 'rgba(0, 0, 0, 0.1)',
                        ],
                    ],
                ],
            ]
        );

        $widget->end_controls_tab();

        $widget->start_controls_tab( 'tab_step_nav_buttons_focus', [ 'label' => __( 'Focus', 'wpuf-pro' ) ] );

        $widget->add_control(
            'step_nav_buttons_focus_bg_color',
            [
                'label'     => __( 'Background Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#6b7280',
                'selectors' => [
                    $prev_btn_selector . ':focus' => 'background-color: {{VALUE}};',
                    $next_btn_selector . ':focus' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_control(
            'step_nav_buttons_focus_text_color',
            [
                'label'     => __( 'Text Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#ffffff',
                'selectors' => [
                    $prev_btn_selector . ':focus' => 'color: {{VALUE}};',
                    $next_btn_selector . ':focus' => 'color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_control(
            'step_nav_buttons_focus_border_color',
            [
                'label'     => __( 'Border Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    $prev_btn_selector . ':focus' => 'border-color: {{VALUE}};',
                    $next_btn_selector . ':focus' => 'border-color: {{VALUE}};',
                ],
            ]
        );

        $widget->end_controls_tab();

        $widget->start_controls_tab( 'tab_step_nav_buttons_hover', [ 'label' => __( 'Hover', 'wpuf-pro' ) ] );

        $widget->add_control(
            'step_nav_buttons_hover_bg_color',
            [
                'label'     => __( 'Background Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#4b5563',
                'selectors' => [
                    $prev_btn_selector . ':hover' => 'background-color: {{VALUE}};',
                    $next_btn_selector . ':hover' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_control(
            'step_nav_buttons_hover_text_color',
            [
                'label'     => __( 'Text Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#ffffff',
                'selectors' => [
                    $prev_btn_selector . ':hover' => 'color: {{VALUE}};',
                    $next_btn_selector . ':hover' => 'color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_control(
            'step_nav_buttons_hover_border_color',
            [
                'label'     => __( 'Border Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [
                    $prev_btn_selector . ':hover' => 'border-color: {{VALUE}};',
                    $next_btn_selector . ':hover' => 'border-color: {{VALUE}};',
                ],
            ]
        );

        $widget->end_controls_tab();

        $widget->end_controls_tabs();

        // Progress bar - Step by Step wizard.
        $widget->add_control(
            'step_progress_heading_wizard',
            [
                'label'     => __( 'Progress Bar - Step by Step', 'wpuf-pro' ),
                'type'      => Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $widget->add_control(
            'step_progress_inactive_bg_color',
            [
                'label'     => __( 'Inactive Step Background', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#E4E4E4',
                'selectors' => [
                    $inactive_selector           => 'background-color: {{VALUE}};',
                    $inactive_selector . '::after' => 'border-left-color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_control(
            'step_progress_inactive_text_color',
            [
                'label'     => __( 'Inactive Step Text', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [ $inactive_selector => 'color: {{VALUE}};' ],
            ]
        );

        $widget->add_control(
            'step_progress_active_bg_color',
            [
                'label'     => __( 'Active Step Background', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#00a0d2',
                'selectors' => [
                    $active_selector => 'background-color: {{VALUE}};',
                    $active_selector . '::after' => 'border-left-color: {{VALUE}};',
                ],
            ]
        );

        $widget->add_control(
            'step_progress_active_text_color',
            [
                'label'     => __( 'Active Step Text', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#ffffff',
                'selectors' => [ $active_selector => 'color: {{VALUE}};' ],
            ]
        );

        $widget->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name'     => 'step_progress_wizard_typography',
                'selector' => $inactive_selector,
            ]
        );

        // Progress bar - Progressive.
        $widget->add_control(
            'step_progress_heading_progressive',
            [
                'label'     => __( 'Progress Bar - Progressive', 'wpuf-pro' ),
                'type'      => Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $widget->add_responsive_control(
            'step_progress_track_height',
            [
                'label'      => __( 'Track Height', 'wpuf-pro' ),
                'type'       => Controls_Manager::SLIDER,
                'size_units' => [ 'px' ],
                'range'      => [ 'px' => [ 'min' => 10, 'max' => 80, 'step' => 1 ] ],
                'default'    => [ 'size' => 25 ],
                'selectors'  => [ $progressive_track => 'height: {{SIZE}}{{UNIT}};' ],
            ]
        );

        $widget->add_control(
            'step_progress_track_bg_color',
            [
                'label'     => __( 'Track Background', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#eeeeee',
                'selectors' => [ $progressive_track => 'background-color: {{VALUE}}; border-color: {{VALUE}};' ],
            ]
        );

        $widget->add_control(
            'step_progress_fill_color',
            [
                'label'     => __( 'Fill Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'default'   => '#00a0d2',
                'selectors' => [ $progressive_fill => 'background: {{VALUE}};' ],
            ]
        );

        $widget->add_control(
            'step_progress_track_border_radius',
            [
                'label'      => __( 'Border Radius', 'wpuf-pro' ),
                'type'       => Controls_Manager::DIMENSIONS,
                'size_units' => [ 'px', '%' ],
                'selectors'  => [ $progressive_track => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};' ],
            ]
        );

        $widget->add_control(
            'step_progress_percentage_heading',
            [
                'label'     => __( 'Percentage Text', 'wpuf-pro' ),
                'type'      => Controls_Manager::HEADING,
                'separator' => 'before',
            ]
        );

        $widget->add_control(
            'step_progress_percentage_color',
            [
                'label'     => __( 'Text Color', 'wpuf-pro' ),
                'type'      => Controls_Manager::COLOR,
                'selectors' => [ $percent_selector => 'color: {{VALUE}};' ],
            ]
        );

        $widget->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name'     => 'step_progress_percentage_typography',
                'selector' => $percent_selector,
            ]
        );

        $widget->end_controls_section();
    }
}
