<?php

namespace Unlockafe_addons\Widgets;

use Unlockafe_addons\Traits\Utils as UnlockafeUtils;
use Unlockafe_addons\Traits\Widget_helper;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Background;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

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

/**
 * Header Search Widget
 *
 * @since 1.0.0
 */
class Header_Search extends Widget_Base
{

    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget name.
     */
    public function get_name()
    {
        return 'unlockafe-header-search';
    }

    /**
     * Retrieve the widget title.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget title.
     */
    public function get_title()
    {
        return __('Header Search', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget icon.
     */
    public function get_icon()
    {
        return 'eicon-search ulicon';
    }

    /**
     * Retrieve the list of categories the widget belongs to.
     *
     * Used to determine where to display the widget in the editor.
     *
     * Note that currently Elementor supports only one category.
     * When multiple categories passed, Elementor uses the first one.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return array Widget categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of scripts the widget depended on.
     *
     * Used to set scripts dependencies required to run the widget.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return array Widget scripts dependencies.
     */
    public function get_script_depends()
    {
        return [];
    }

    public function get_style_depends()
    {
        return ['unlockafe-global', 'font-awesome', 'unlockafe-header-search-style'];
    }

    /**
     * Register the widget controls.
     *
     * Adds different input fields to allow the user to change and customize the widget settings.
     *
     * @since 1.0.0
     *
     * @access protected
     */

    protected function register_controls()
    {
        $this->register_controls_section();
        $this->style_tab_content();
    }

    protected function register_controls_section()
    {
        // layout Panel
        $this->start_controls_section(
            'wpr_layout',
            [
                'label' => esc_html__('Design Layout', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'wpr_design_style',
            [
                'label' => esc_html__('Select Layout', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'layout-1' => esc_html__('Inline Search', 'unlock-addons-for-elementor'),
                    'layout-2' => esc_html__('Popup Search', 'unlock-addons-for-elementor'),
                    'layout-3' => esc_html__('Icon Only + Options Popup', 'unlock-addons-for-elementor'),
                ],
                'default' => 'layout-1',
            ]
        );

        $this->add_control(
            'wpr_search_placeholder',
            [
                'label' => esc_html__('Placeholder Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('What are you looking for?', 'unlock-addons-for-elementor'),
                'label_block' => true,
            ]
        );

        $this->add_control(
            'wpr_search_button_text',
            [
                'label' => esc_html__('Button Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('Search', 'unlock-addons-for-elementor'),
                'label_block' => true,
            ]
        );

        $this->add_control(
            'wpr_search_toggle_text',
            [
                'label' => esc_html__('Toggle Button Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('Search', 'unlock-addons-for-elementor'),
                'label_block' => true,
                'condition' => [
                    'wpr_design_style' => 'layout-2',
                ],
            ]
        );

        $this->add_control(
            'wpr_popup_animation',
            [
                'label' => esc_html__('Popup Animation', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'none' => esc_html__('None', 'unlock-addons-for-elementor'),
                    'fade' => esc_html__('Fade', 'unlock-addons-for-elementor'),
                    'slide-down' => esc_html__('Slide Down', 'unlock-addons-for-elementor'),
                    'slide-up' => esc_html__('Slide Up', 'unlock-addons-for-elementor'),
                    'zoom-in' => esc_html__('Zoom In', 'unlock-addons-for-elementor'),
                    'zoom-out' => esc_html__('Zoom Out', 'unlock-addons-for-elementor'),
                ],
                'default' => 'fade',
                'condition' => [
                    'wpr_design_style' => ['layout-2', 'layout-3'],
                ],
            ]
        );

        $this->add_control(
            'wpr_popup_search_options',
            [
                'label' => esc_html__('Popup Search Options', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => [
                    [
                        'name' => 'search_type',
                        'label' => esc_html__('Search Type', 'unlock-addons-for-elementor'),
                        'type' => Controls_Manager::SELECT,
                        'options' => [
                            'keywords' => esc_html__('All', 'unlock-addons-for-elementor'),
                            'blog' => esc_html__('Blog', 'unlock-addons-for-elementor'),
                            'course' => esc_html__('Course', 'unlock-addons-for-elementor'),
                            'product' => esc_html__('Products', 'unlock-addons-for-elementor'),
                        ],
                        'default' => 'keywords',
                    ],
                    [
                        'name' => 'label',
                        'label' => esc_html__('Label Override', 'unlock-addons-for-elementor'),
                        'type' => Controls_Manager::TEXT,
                        'default' => '',
                        'placeholder' => esc_html__('Leave empty to use default', 'unlock-addons-for-elementor'),
                    ],
                ],
                'default' => [
                    ['search_type' => 'keywords', 'label' => ''],
                    ['search_type' => 'blog', 'label' => ''],
                    ['search_type' => 'course', 'label' => ''],
                ],
                'title_field' => '{{{ search_type }}}',
                'condition' => [
                    'wpr_design_style' => 'layout-3',
                ],
            ]
        );

        $this->add_control(
            'wpr_search_type',
            [
                'label' => esc_html__('Search Type', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'keywords' => esc_html__('Keywords (All Content)', 'unlock-addons-for-elementor'),
                    'blog' => esc_html__('Blog Search', 'unlock-addons-for-elementor'),
                    'course' => esc_html__('Course Search', 'unlock-addons-for-elementor'),
                ],
                'default' => 'keywords',
                'description' => esc_html__('Select what type of content to search', 'unlock-addons-for-elementor'),
            ]
        );

        // Get available post types that might be courses
        $course_post_types = $this->get_course_post_types();
        
        $this->add_control(
            'wpr_course_post_type',
            [
                'label' => esc_html__('Course Post Type', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => $course_post_types,
                'default' => !empty($course_post_types) ? array_key_first($course_post_types) : 'course',
                'label_block' => true,
                'description' => esc_html__('Select the post type for courses. If your course post type is not listed, you can enter it manually below.', 'unlock-addons-for-elementor'),
                'condition' => [
                    'wpr_search_type' => 'course',
                ],
            ]
        );

        $this->add_control(
            'wpr_course_post_type_custom',
            [
                'label' => esc_html__('Custom Post Type Slug', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '',
                'label_block' => true,
                'description' => esc_html__('If your course post type is not in the list above, enter the post type slug here (e.g., lp_course, courses, sfwd-courses)', 'unlock-addons-for-elementor'),
                'condition' => [
                    'wpr_search_type' => 'course',
                ],
            ]
        );

        $this->end_controls_section();
    }

    protected function style_tab_content()
    {
        $this->start_controls_section(
            'unlockafe_search_container_style',
            [
                'label' => esc_html__('Container', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_alignment',
            [
                'label' => esc_html__('Alignment', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'flex-start' => [
                        'title' => esc_html__('Left', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => esc_html__('Center', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'flex-end' => [
                        'title' => esc_html__('Right', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-right',
                    ],
                ],
                'default' => 'flex-end',
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_header_search' => 'justify-content: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_container_width',
            [
                'label' => esc_html__('Max Width', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'range' => [
                    'px' => [
                        'min' => 100,
                        'max' => 1200,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_form' => 'max-width: {{SIZE}}{{UNIT}};',
                ],
                'condition' => [
                    'wpr_design_style' => 'layout-1',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_container_padding',
            [
                'label' => esc_html__('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_header_search' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'unlockafe_search_input_style',
            [
                'label' => esc_html__('Input Field', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'unlockafe_search_input_typography',
                'selector' => '{{WRAPPER}} .unlock_addon_search_field',
            ]
        );

        $this->add_control(
            'unlockafe_search_input_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'unlockafe_search_input_placeholder_color',
            [
                'label' => esc_html__('Placeholder Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field::placeholder' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_search_input_background',
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlock_addon_search_field_group',
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'unlockafe_search_input_border',
                'selector' => '{{WRAPPER}} .unlock_addon_search_field_group',
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_input_radius',
            [
                'label' => esc_html__('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field_group' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_input_padding',
            [
                'label' => esc_html__('Input Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Search Icon Style Section
        $this->start_controls_section(
            'unlockafe_search_icon_style',
            [
                'label' => esc_html__('Search Icon', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_icon_size',
            [
                'label' => esc_html__('Icon Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em', 'rem'],
                'range' => [
                    'px' => [
                        'min' => 10,
                        'max' => 100,
                        'step' => 1,
                    ],
                    'em' => [
                        'min' => 0.5,
                        'max' => 5,
                        'step' => 0.1,
                    ],
                    'rem' => [
                        'min' => 0.5,
                        'max' => 5,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 18,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_icon i' => 'font-size: {{SIZE}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_icon_spacing',
            [
                'label' => esc_html__('Icon Spacing', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 50,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 12,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_icon' => 'margin-right: {{SIZE}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->start_controls_tabs('unlockafe_search_icon_tabs');

        $this->start_controls_tab(
            'unlockafe_search_icon_normal',
            [
                'label' => esc_html__('Normal', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_color',
            [
                'label' => esc_html__('Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_icon' => 'color: {{VALUE}} !important;',
                    '{{WRAPPER}} .unlock_addon_search_icon i' => 'color: {{VALUE}} !important;',
                ],
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_bg_color',
            [
                'label' => esc_html__('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_icon' => 'background-color: {{VALUE}} !important;',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_icon_padding',
            [
                'label' => esc_html__('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_icon' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_icon_border_radius',
            [
                'label' => esc_html__('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_icon' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'unlockafe_search_icon_border',
                'label' => esc_html__('Border', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlock_addon_search_icon',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'unlockafe_search_icon_box_shadow',
                'label' => esc_html__('Box Shadow', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlock_addon_search_icon',
            ]
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'unlockafe_search_icon_hover',
            [
                'label' => esc_html__('Hover', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_hover_color',
            [
                'label' => esc_html__('Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon' => 'color: {{VALUE}} !important;',
                    '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon i' => 'color: {{VALUE}} !important;',
                ],
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_hover_bg_color',
            [
                'label' => esc_html__('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon' => 'background-color: {{VALUE}} !important;',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'unlockafe_search_icon_hover_border',
                'label' => esc_html__('Border', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon',
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_icon_hover_border_radius',
            [
                'label' => esc_html__('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'unlockafe_search_icon_hover_box_shadow',
                'label' => esc_html__('Box Shadow', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon',
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_hover_transform',
            [
                'label' => esc_html__('Hover Effect', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'none' => esc_html__('None', 'unlock-addons-for-elementor'),
                    'scale' => esc_html__('Scale', 'unlock-addons-for-elementor'),
                    'rotate' => esc_html__('Rotate', 'unlock-addons-for-elementor'),
                    'translate' => esc_html__('Translate', 'unlock-addons-for-elementor'),
                ],
                'default' => 'none',
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_hover_transform_scale',
            [
                'label' => esc_html__('Scale Amount', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'range' => [
                    'px' => [
                        'min' => 0.5,
                        'max' => 2,
                        'step' => 0.1,
                    ],
                ],
                'default' => [
                    'size' => 1.1,
                ],
                'condition' => [
                    'unlockafe_search_icon_hover_transform' => 'scale',
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon' => 'transform: scale({{SIZE}}) !important;',
                ],
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_hover_transform_rotate',
            [
                'label' => esc_html__('Rotate Degree', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'range' => [
                    'px' => [
                        'min' => -360,
                        'max' => 360,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'size' => 360,
                ],
                'condition' => [
                    'unlockafe_search_icon_hover_transform' => 'rotate',
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon' => 'transform: rotate({{SIZE}}deg) !important;',
                ],
            ]
        );

        $this->add_control(
            'unlockafe_search_icon_hover_transform_translate',
            [
                'label' => esc_html__('Translate Y', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => -50,
                        'max' => 50,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => -5,
                ],
                'condition' => [
                    'unlockafe_search_icon_hover_transform' => 'translate',
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_field_group:hover .unlock_addon_search_icon' => 'transform: translateY({{SIZE}}{{UNIT}}) !important;',
                ],
            ]
        );

        $this->end_controls_tab();

        $this->end_controls_tabs();

        $this->end_controls_section();

        $this->start_controls_section(
            'unlockafe_search_button_style',
            [
                'label' => esc_html__('Submit Button', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'unlockafe_search_button_typography',
                'selector' => '{{WRAPPER}} .unlock_addon_search_submit',
            ]
        );

        $this->start_controls_tabs('unlockafe_search_button_tabs');

        $this->start_controls_tab(
            'unlockafe_search_button_normal',
            [
                'label' => esc_html__('Normal', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'unlockafe_search_button_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_submit' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_search_button_bg',
                'selector' => '{{WRAPPER}} .unlock_addon_search_submit',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'unlockafe_search_button_shadow',
                'selector' => '{{WRAPPER}} .unlock_addon_search_submit',
            ]
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'unlockafe_search_button_hover',
            [
                'label' => esc_html__('Hover', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'unlockafe_search_button_hover_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_submit:hover' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_search_button_hover_bg',
                'selector' => '{{WRAPPER}} .unlock_addon_search_submit:hover',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'unlockafe_search_button_hover_shadow',
                'selector' => '{{WRAPPER}} .unlock_addon_search_submit:hover',
            ]
        );

        $this->end_controls_tab();

        $this->end_controls_tabs();

        $this->add_responsive_control(
            'unlockafe_search_button_radius',
            [
                'label' => esc_html__('Button Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_submit' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'unlockafe_search_toggle_style',
            [
                'label' => esc_html__('Toggle Button', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'wpr_design_style' => ['layout-2', 'layout-3'],
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'unlockafe_search_toggle_typography',
                'selector' => '{{WRAPPER}} .unlock_addon_search_toggle',
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_toggle_padding',
            [
                'label' => esc_html__('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_toggle' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'unlockafe_search_toggle_border',
                'selector' => '{{WRAPPER}} .unlock_addon_search_toggle',
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_toggle_radius',
            [
                'label' => esc_html__('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_toggle' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->start_controls_tabs('unlockafe_search_toggle_tabs');

        $this->start_controls_tab(
            'unlockafe_search_toggle_normal',
            [
                'label' => esc_html__('Normal', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'unlockafe_search_toggle_color',
            [
                'label' => esc_html__('Text/Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_toggle' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_search_toggle_bg',
                'selector' => '{{WRAPPER}} .unlock_addon_search_toggle',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'unlockafe_search_toggle_shadow',
                'selector' => '{{WRAPPER}} .unlock_addon_search_toggle',
            ]
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'unlockafe_search_toggle_hover',
            [
                'label' => esc_html__('Hover', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'unlockafe_search_toggle_hover_color',
            [
                'label' => esc_html__('Text/Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_toggle:hover' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_search_toggle_hover_bg',
                'selector' => '{{WRAPPER}} .unlock_addon_search_toggle:hover',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'unlockafe_search_toggle_hover_shadow',
                'selector' => '{{WRAPPER}} .unlock_addon_search_toggle:hover',
            ]
        );

        $this->end_controls_tab();

        $this->end_controls_tabs();

        $this->end_controls_section();

        $this->start_controls_section(
            'unlockafe_search_panel_style',
            [
                'label' => esc_html__('Popup Panel', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'wpr_design_style' => ['layout-2', 'layout-3'],
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_panel_width',
            [
                'label' => esc_html__('Panel Width', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'range' => [
                    'px' => [
                        'min' => 240,
                        'max' => 900,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_panel_inner' => 'max-width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_search_panel_bg',
                'selector' => '{{WRAPPER}} .unlock_addon_search_panel_inner',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'unlockafe_search_panel_shadow',
                'selector' => '{{WRAPPER}} .unlock_addon_search_panel_inner',
            ]
        );

        $this->add_responsive_control(
            'unlockafe_search_panel_radius',
            [
                'label' => esc_html__('Panel Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%', 'em'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_panel_inner' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'unlockafe_search_overlay_color',
            [
                'label' => esc_html__('Overlay Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_search_overlay' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render the widget output on the frontend.
     *
     * Written in PHP and used to generate the final HTML.
     *
     * @since 1.0.0
     *
     * @access protected
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $layout = !empty($settings['wpr_design_style']) ? $settings['wpr_design_style'] : 'layout-1';
        $placeholder = !empty($settings['wpr_search_placeholder']) ? $settings['wpr_search_placeholder'] : esc_html__('What are you looking for?', 'unlock-addons-for-elementor');
        $button_text = !empty($settings['wpr_search_button_text']) ? $settings['wpr_search_button_text'] : esc_html__('Search', 'unlock-addons-for-elementor');
        $toggle_text = !empty($settings['wpr_search_toggle_text']) ? $settings['wpr_search_toggle_text'] : esc_html__('Search', 'unlock-addons-for-elementor');

        $wrapper_id = 'unlockafe-search-' . $this->get_id();
        $panel_id = $wrapper_id . '-panel';
        $overlay_id = $wrapper_id . '-overlay';
        $input_id = $wrapper_id . '-input';

        $wrapper_classes = [
            'unlock_addon_header_search',
            'unlock_addon_header_search_' . $layout,
        ];

        $search_type = !empty($settings['wpr_search_type']) ? $settings['wpr_search_type'] : 'keywords';

        // Use custom post type if provided, otherwise use selected one
        $course_post_type = !empty($settings['wpr_course_post_type_custom'])
            ? $settings['wpr_course_post_type_custom']
            : (!empty($settings['wpr_course_post_type']) ? $settings['wpr_course_post_type'] : 'course');

        $popup_animation = in_array($layout, ['layout-2', 'layout-3'], true) && !empty($settings['wpr_popup_animation'])
            ? $settings['wpr_popup_animation']
            : 'fade';
        $panel_animation_class = 'unlock_addon_search_panel--' . sanitize_html_class($popup_animation);

        $form_markup = $this->get_search_form_markup($input_id, $placeholder, $button_text, $search_type, $course_post_type);
        $post_type_input_id = $wrapper_id . '-post-type';
        $form_options_popup_markup = $this->get_search_form_markup_for_options_popup($input_id, $placeholder, $button_text, $post_type_input_id);

        $popup_options = [];
        if ($layout === 'layout-3' && !empty($settings['wpr_popup_search_options']) && is_array($settings['wpr_popup_search_options'])) {
            $popup_options = array_slice($settings['wpr_popup_search_options'], 0, 4);
        }
?>

        <div id="<?php echo esc_attr($wrapper_id); ?>" class="<?php echo esc_attr(implode(' ', array_map('sanitize_html_class', $wrapper_classes))); ?>">
            <?php if ($layout === 'layout-2'): ?>
                <button type="button" class="unlock_addon_search_toggle" data-search-toggle="<?php echo esc_attr($panel_id); ?>" aria-controls="<?php echo esc_attr($panel_id); ?>" aria-expanded="false">
                    <span class="unlock_addon_search_toggle_icon" aria-hidden="true">
                        <i class="fa-solid fa-magnifying-glass"></i>
                    </span>
                    <span class="unlock_addon_search_toggle_label">
                        <?php echo esc_html($toggle_text); ?>
                    </span>
                </button>

                <div id="<?php echo esc_attr($panel_id); ?>" class="unlock_addon_search_panel <?php echo esc_attr($panel_animation_class); ?>" aria-hidden="true" data-popup-animation="<?php echo esc_attr($popup_animation); ?>">
                    <div class="unlock_addon_search_panel_inner">
                        <button type="button" class="unlock_addon_search_close" data-search-close="<?php echo esc_attr($panel_id); ?>" aria-label="<?php esc_attr_e('Close search', 'unlock-addons-for-elementor'); ?>">
                            <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                        </button>
                        <?php echo $form_markup; ?>
                    </div>
                </div>

                <div id="<?php echo esc_attr($overlay_id); ?>" class="unlock_addon_search_overlay" data-search-overlay="<?php echo esc_attr($panel_id); ?>" aria-hidden="true"></div>

                <script id="<?php echo esc_attr('unlockafe-search-script-' . $this->get_id()); ?>">
                    (function () {
                        const initSearchPopup = function () {
                            const wrapper = document.getElementById('<?php echo esc_js($wrapper_id); ?>');
                            if (!wrapper) return;
                            const toggle = wrapper.querySelector('[data-search-toggle="<?php echo esc_js($panel_id); ?>"]');
                            const panel = document.getElementById('<?php echo esc_js($panel_id); ?>');
                            const overlay = document.getElementById('<?php echo esc_js($overlay_id); ?>');
                            if (!toggle || !panel || !overlay) return;
                            const closeButtons = panel.querySelectorAll('[data-search-close]');
                            const body = document.body;
                            const openPanel = function () {
                                panel.classList.add('is-open');
                                overlay.classList.add('is-visible');
                                body.classList.add('unlock_addon_search_open');
                                toggle.setAttribute('aria-expanded', 'true');
                                const focusField = panel.querySelector('.unlock_addon_search_field');
                                if (focusField) focusField.focus();
                            };
                            const closePanel = function () {
                                panel.classList.remove('is-open');
                                overlay.classList.remove('is-visible');
                                body.classList.remove('unlock_addon_search_open');
                                toggle.setAttribute('aria-expanded', 'false');
                            };
                            toggle.addEventListener('click', function (e) { e.preventDefault(); panel.classList.contains('is-open') ? closePanel() : openPanel(); });
                            overlay.addEventListener('click', closePanel);
                            closeButtons.forEach(function (btn) { btn.addEventListener('click', closePanel); });
                            document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && panel.classList.contains('is-open')) closePanel(); });
                        };
                        if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initSearchPopup);
                        else initSearchPopup();
                    })();
                </script>
            <?php elseif ($layout === 'layout-3'): ?>
                <button type="button" class="unlock_addon_search_toggle unlock_addon_search_toggle_icon_only" data-search-toggle="<?php echo esc_attr($panel_id); ?>" aria-controls="<?php echo esc_attr($panel_id); ?>" aria-expanded="false" aria-label="<?php esc_attr_e('Open search', 'unlock-addons-for-elementor'); ?>">
                    <span class="unlock_addon_search_toggle_icon" aria-hidden="true">
                        <i class="fa-solid fa-magnifying-glass"></i>
                    </span>
                </button>

                <div id="<?php echo esc_attr($panel_id); ?>" class="unlock_addon_search_panel <?php echo esc_attr($panel_animation_class); ?>" aria-hidden="true" data-popup-animation="<?php echo esc_attr($popup_animation); ?>">
                    <div class="unlock_addon_search_panel_inner">
                        <button type="button" class="unlock_addon_search_close" data-search-close="<?php echo esc_attr($panel_id); ?>" aria-label="<?php esc_attr_e('Close search', 'unlock-addons-for-elementor'); ?>">
                            <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                        </button>
                        <div class="unlock_addon_search_panel_options">
                            <?php
                            foreach ($popup_options as $index => $item) {
                                $opt_type = !empty($item['search_type']) ? $item['search_type'] : 'keywords';
                                $opt_label = !empty($item['label']) ? $item['label'] : $this->get_search_type_label($opt_type);
                                $opt_post_type = $this->get_post_type_for_search_type($opt_type, $course_post_type);
                                $is_first = $index === 0;
                                ?>
                                <button type="button" class="unlock_addon_search_option<?php echo $is_first ? ' is-active' : ''; ?>" data-post-type="<?php echo esc_attr($opt_post_type); ?>" data-search-type="<?php echo esc_attr($opt_type); ?>">
                                    <?php echo esc_html($opt_label); ?>
                                </button>
                            <?php } ?>
                        </div>
                        <?php echo $form_options_popup_markup; ?>
                    </div>
                </div>

                <div id="<?php echo esc_attr($overlay_id); ?>" class="unlock_addon_search_overlay" data-search-overlay="<?php echo esc_attr($panel_id); ?>" aria-hidden="true"></div>

                <script id="<?php echo esc_attr('unlockafe-search-script-' . $this->get_id()); ?>">
                    (function () {
                        const wrapperId = '<?php echo esc_js($wrapper_id); ?>';
                        const panelId = '<?php echo esc_js($panel_id); ?>';
                        const overlayId = '<?php echo esc_js($overlay_id); ?>';
                        const postTypeInputId = '<?php echo esc_js($post_type_input_id); ?>';
                        const firstPostType = '<?php echo count($popup_options) > 0 ? esc_js($this->get_post_type_for_search_type($popup_options[0]['search_type'] ?? 'keywords', $course_post_type)) : ''; ?>';
                        const initSearchPopup = function () {
                            const wrapper = document.getElementById(wrapperId);
                            if (!wrapper) return;
                            const toggle = wrapper.querySelector('[data-search-toggle="' + panelId + '"]');
                            const panel = document.getElementById(panelId);
                            const overlay = document.getElementById(overlayId);
                            const postTypeInput = document.getElementById(postTypeInputId);
                            if (!toggle || !panel || !overlay) return;
                            if (postTypeInput) postTypeInput.value = firstPostType;
                            const optionBtns = panel.querySelectorAll('.unlock_addon_search_option');
                            optionBtns.forEach(function (btn) {
                                btn.addEventListener('click', function () {
                                    const pt = this.getAttribute('data-post-type') || '';
                                    if (postTypeInput) postTypeInput.value = pt;
                                    optionBtns.forEach(function (b) { b.classList.remove('is-active'); });
                                    this.classList.add('is-active');
                                });
                            });
                            const closeButtons = panel.querySelectorAll('[data-search-close]');
                            const body = document.body;
                            const openPanel = function () {
                                panel.classList.add('is-open');
                                overlay.classList.add('is-visible');
                                body.classList.add('unlock_addon_search_open');
                                toggle.setAttribute('aria-expanded', 'true');
                                const focusField = panel.querySelector('.unlock_addon_search_field');
                                if (focusField) focusField.focus();
                            };
                            const closePanel = function () {
                                panel.classList.remove('is-open');
                                overlay.classList.remove('is-visible');
                                body.classList.remove('unlock_addon_search_open');
                                toggle.setAttribute('aria-expanded', 'false');
                            };
                            toggle.addEventListener('click', function (e) { e.preventDefault(); panel.classList.contains('is-open') ? closePanel() : openPanel(); });
                            overlay.addEventListener('click', closePanel);
                            closeButtons.forEach(function (btn) { btn.addEventListener('click', closePanel); });
                            document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && panel.classList.contains('is-open')) closePanel(); });
                        };
                        if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initSearchPopup);
                        else initSearchPopup();
                    })();
                </script>
            <?php else: ?>
                <div class="unlock_addon_search_inline">
                    <?php echo $form_markup; ?>
                </div>
            <?php endif; ?>
        </div>
<?php
    }

    /**
     * Render search form markup.
     *
     * @param string $input_id
     * @param string $placeholder
     * @param string $button_text
     * @param string $search_type
     * @param string $course_post_type
     * @return string
     */
    private function get_search_form_markup($input_id, $placeholder, $button_text, $search_type = 'keywords', $course_post_type = 'course')
    {
        ob_start();
        
        // Determine form action and hidden fields based on search type
        $form_action = home_url('/');
        $hidden_fields = '';
        
        switch ($search_type) {
            case 'blog':
                // Blog search - search only in posts
                $form_action = home_url('/');
                $hidden_fields = '<input type="hidden" name="post_type" value="post" />';
                break;
                
            case 'course':
                // Course search - search in custom post type
                $form_action = home_url('/');
                $hidden_fields = '<input type="hidden" name="post_type" value="' . esc_attr($course_post_type) . '" />';
                break;
                
            case 'keywords':
            default:
                // Keywords search - default WordPress search (all content)
                $form_action = home_url('/');
                $hidden_fields = '';
                break;
        }
?>
        <form class="unlock_addon_search_form" action="<?php echo esc_url($form_action); ?>" role="search" method="get" data-search-type="<?php echo esc_attr($search_type); ?>">
            <label class="screen-reader-text" for="<?php echo esc_attr($input_id); ?>">
                <?php esc_html_e('Search for:', 'unlock-addons-for-elementor'); ?>
            </label>
            <?php echo $hidden_fields; ?>
            <div class="unlock_addon_search_field_group">
                <span class="unlock_addon_search_icon" aria-hidden="true">
                    <i class="fa-solid fa-magnifying-glass"></i>
                </span>
                <input type="search" id="<?php echo esc_attr($input_id); ?>" class="unlock_addon_search_field" name="s" value="<?php echo esc_attr(get_search_query()); ?>" placeholder="<?php echo esc_attr($placeholder); ?>" />
                <button type="submit" class="unlock_addon_search_submit">
                    <span><?php echo esc_html($button_text); ?></span>
                    <i class="fa-solid fa-arrow-right" aria-hidden="true"></i>
                </button>
            </div>
        </form>
<?php
        return ob_get_clean();
    }

    /**
     * Get default label for a search type.
     *
     * @param string $search_type
     * @return string
     */
    private function get_search_type_label($search_type)
    {
        $labels = [
            'keywords' => __('All', 'unlock-addons-for-elementor'),
            'blog' => __('Blog', 'unlock-addons-for-elementor'),
            'course' => __('Courses', 'unlock-addons-for-elementor'),
            'product' => __('Products', 'unlock-addons-for-elementor'),
        ];
        return isset($labels[$search_type]) ? $labels[$search_type] : $search_type;
    }

    /**
     * Get post_type value for search type (empty string for keywords = all).
     *
     * @param string $search_type
     * @param string $course_post_type
     * @return string
     */
    private function get_post_type_for_search_type($search_type, $course_post_type = 'course')
    {
        switch ($search_type) {
            case 'blog':
                return 'post';
            case 'course':
                return $course_post_type;
            case 'product':
                return 'product';
            case 'keywords':
            default:
                return '';
        }
    }

    /**
     * Search form markup for layout-3 (options popup) with dynamic post_type via JS.
     *
     * @param string $input_id
     * @param string $placeholder
     * @param string $button_text
     * @param string $post_type_input_id
     * @return string
     */
    private function get_search_form_markup_for_options_popup($input_id, $placeholder, $button_text, $post_type_input_id)
    {
        ob_start();
        $form_action = home_url('/');
?>
        <form class="unlock_addon_search_form unlock_addon_search_form_options_popup" action="<?php echo esc_url($form_action); ?>" role="search" method="get">
            <label class="screen-reader-text" for="<?php echo esc_attr($input_id); ?>">
                <?php esc_html_e('Search for:', 'unlock-addons-for-elementor'); ?>
            </label>
            <input type="hidden" id="<?php echo esc_attr($post_type_input_id); ?>" name="post_type" value="" />
            <div class="unlock_addon_search_field_group">
                <span class="unlock_addon_search_icon" aria-hidden="true">
                    <i class="fa-solid fa-magnifying-glass"></i>
                </span>
                <input type="search" id="<?php echo esc_attr($input_id); ?>" class="unlock_addon_search_field" name="s" value="<?php echo esc_attr(get_search_query()); ?>" placeholder="<?php echo esc_attr($placeholder); ?>" />
                <button type="submit" class="unlock_addon_search_submit">
                    <span><?php echo esc_html($button_text); ?></span>
                    <i class="fa-solid fa-arrow-right" aria-hidden="true"></i>
                </button>
            </div>
        </form>
<?php
        return ob_get_clean();
    }

    /**
     * Get available course post types.
     *
     * @return array
     */
    private function get_course_post_types()
    {
        $post_types = get_post_types(['public' => true, 'show_ui' => true], 'objects');
        $course_types = [];
        
        // Common course post type slugs
        $common_course_slugs = [
            'course',
            'courses',
            'lp_course',
            'sfwd-courses',
            'tutor_course',
            'llms_course',
        ];
        
        foreach ($post_types as $post_type) {
            $slug = $post_type->name;
            
            // Include if it's a common course slug or contains "course"
            if (in_array($slug, $common_course_slugs) || 
                strpos(strtolower($slug), 'course') !== false ||
                strpos(strtolower($post_type->label), 'course') !== false) {
                $course_types[$slug] = $post_type->label . ' (' . $slug . ')';
            }
        }
        
        // If no course types found, add default option
        if (empty($course_types)) {
            $course_types['course'] = esc_html__('Course (course)', 'unlock-addons-for-elementor');
        }
        
        return $course_types;
    }
}


