<?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_Box_Shadow;
use \Elementor\Group_Control_Border;

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

/**
 * Header Shop Cart Widget
 *
 * @since 1.0.0
 */
class Header_Shop_Cart 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-shop-cart';
    }

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

    /**
     * Retrieve the widget icon.
     *
     * @since 1.0.0
     *
     * @access public
     *
     * @return string Widget icon.
     */
    public function get_icon()
    {
        return 'eicon-cart 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-shop-cart-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_header_top',
            [
                'label' => esc_html__('Header Info', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'wpr_header_cart_switch',
            [
                'label' => esc_html__('Enable Cart?', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Show', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('Hide', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );
        $this->tp_single_icon_control('header_cart', 'wpr_header_cart_switch', 'yes');
        $this->update_control(
            'tp_header_cart_icon',
            [
                'default' => [
                    'value' => 'fas fa-shopping-cart',
                    'library' => 'fa-solid',
                ],
            ]
        );

        $this->end_controls_section();
    }

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

        $this->add_responsive_control(
            'unlockafe_cart_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_cart_wrapper' => 'justify-content: {{VALUE}};',
                ],
            ]
        );

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

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

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

        $this->start_controls_tabs('unlockafe_cart_toggle_tabs');

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

        $this->add_control(
            'unlockafe_cart_toggle_color',
            [
                'label' => esc_html__('Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_cart_toggle, {{WRAPPER}} .unlock_addon_cart_toggle i, {{WRAPPER}} .unlock_addon_cart_toggle svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .unlock_addon_cart_toggle svg path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_cart_toggle_bg',
                'label' => esc_html__('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlock_addon_cart_toggle',
            ]
        );

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

        $this->end_controls_tab();

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

        $this->add_control(
            'unlockafe_cart_toggle_hover_color',
            [
                'label' => esc_html__('Icon Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_cart_toggle:hover, {{WRAPPER}} .unlock_addon_cart_toggle:hover i, {{WRAPPER}} .unlock_addon_cart_toggle:hover svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .unlock_addon_cart_toggle:hover svg path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_cart_toggle_hover_bg',
                'label' => esc_html__('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlock_addon_cart_toggle:hover',
            ]
        );

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

        $this->end_controls_tab();

        $this->end_controls_tabs();

        $this->add_responsive_control(
            'unlockafe_cart_icon_size',
            [
                'label' => esc_html__('Icon Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => 10,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_cart_toggle i' => 'font-size: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .unlock_addon_cart_toggle svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        $this->start_controls_section(
            'unlockafe_cart_badge_style',
            [
                'label' => esc_html__('Cart Badge', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

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

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

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

        $this->add_responsive_control(
            'unlockafe_cart_badge_size',
            [
                'label' => esc_html__('Badge Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => [
                        'min' => 16,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_cart_count' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_cart_badge_offset_x',
            [
                'label' => esc_html__('Horizontal Offset', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_cart_count' => 'right: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'unlockafe_cart_badge_offset_y',
            [
                'label' => esc_html__('Vertical Offset', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_cart_count' => 'top: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

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

        $this->end_controls_section();

        $this->start_controls_section(
            'unlockafe_cart_panel_style',
            [
                'label' => esc_html__('Cart Drawer', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

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

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'unlockafe_cart_panel_bg',
                'label' => esc_html__('Panel Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlock_addon_cartmini_panel',
            ]
        );

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

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

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

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

        $this->add_control(
            'unlockafe_cart_overlay_color',
            [
                'label' => esc_html__('Overlay Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlock_addon_cartmini_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();
        if ($settings['wpr_header_cart_switch'] !== 'yes') {
            return;
        }

        if (!class_exists('WooCommerce')) {
            echo '<div class="unlock_addon_cart_notice">' . esc_html__('WooCommerce plugin is required to display the cart.', 'unlock-addons-for-elementor') . '</div>';
            return;
        }

        $cart_wrapper_id = 'unlockafe-cart-wrapper-' . $this->get_id();
        $cart_panel_id = $cart_wrapper_id . '-panel';
        $cart_overlay_id = $cart_wrapper_id . '-overlay';
        $cart_count = (!is_null(WC()->cart)) ? WC()->cart->get_cart_contents_count() : 0;

        $icon_type = $settings['tp_header_cart_icon_type'] ?? 'icon';
        $has_custom_icon = false;

        if ($icon_type === 'icon' && !empty($settings['tp_header_cart_icon'])) {
            // Check if icon has a value (can be string or array)
            $icon_value = isset($settings['tp_header_cart_icon']['value']) ? $settings['tp_header_cart_icon']['value'] : '';
            if (!empty($icon_value)) {
                $has_custom_icon = true;
            }
        } elseif ($icon_type === 'image' && !empty($settings['tp_header_cart_image']['url'])) {
            $has_custom_icon = true;
        } elseif ($icon_type === 'svg' && !empty($settings['tp_header_cart_icon_svg'])) {
            $has_custom_icon = true;
        }

        $template_path = UNLOCKAFE_INCLUDE_PATH . 'Skins/header-cart/header-cart-mini.php';
        ?>

        <div id="<?php echo esc_attr($cart_wrapper_id); ?>" class="unlock_addon_cart_wrapper" data-cart-widget="<?php echo esc_attr($cart_panel_id); ?>">
            <div class="unlock_addon_cart_button">
                <button type="button" class="unlock_addon_cart_toggle" data-cart-toggle="<?php echo esc_attr($cart_panel_id); ?>" aria-controls="<?php echo esc_attr($cart_panel_id); ?>" aria-expanded="false">
                    <span class="unlock_addon_cart_icon" aria-hidden="true">
                        <?php
                        if ($has_custom_icon) {
                            $icon_rendered = false;
                            ob_start();
                            $this->tp_render_signle_icon_html($settings, 'header_cart', 'unlock_addon_cart_custom_icon');
                            $icon_output = ob_get_clean();
                            
                            // Check if icon was actually rendered
                            if (!empty(trim($icon_output))) {
                                echo $icon_output;
                                $icon_rendered = true;
                            }
                            
                            // If icon wasn't rendered, show fallback
                            if (!$icon_rendered) {
                                echo '<i class="fas fa-shopping-cart"></i>';
                            }
                        } else {
                            echo '<i class="fas fa-shopping-cart"></i>';
                        }
                        ?>
                    </span>
                </button>
                <span class="unlock_addon_cart_count" data-cart-count aria-live="polite">
                    <?php echo esc_html($cart_count); ?>
                </span>
            </div>

            <?php
            if (file_exists($template_path)) {
                $cart_panel_label = esc_html__('Shopping cart', 'unlock-addons-for-elementor');
                include $template_path;
            }
            ?>
        </div>

        <script id="<?php echo esc_attr('unlockafe-cart-script-' . $this->get_id()); ?>">
            (function () {
                const initCartDrawer = function () {
                    const wrapper = document.getElementById('<?php echo esc_js($cart_wrapper_id); ?>');
                    if (!wrapper) {
                        return;
                    }

                    const toggle = wrapper.querySelector('[data-cart-toggle="<?php echo esc_js($cart_panel_id); ?>"]');
                    const panel = document.getElementById('<?php echo esc_js($cart_panel_id); ?>');
                    const overlay = document.getElementById('<?php echo esc_js($cart_overlay_id); ?>');

                    if (!toggle || !panel || !overlay) {
                        return;
                    }

                    const closeButtons = panel.querySelectorAll('[data-cart-close]');
                    const body = document.body;

                    const openDrawer = function () {
                        panel.classList.add('is-open');
                        overlay.classList.add('is-visible');
                        body.classList.add('unlock_addon_cart_open');
                        toggle.setAttribute('aria-expanded', 'true');
                    };

                    const closeDrawer = function () {
                        panel.classList.remove('is-open');
                        overlay.classList.remove('is-visible');
                        body.classList.remove('unlock_addon_cart_open');
                        toggle.setAttribute('aria-expanded', 'false');
                    };

                    toggle.addEventListener('click', function (event) {
                        event.preventDefault();
                        if (panel.classList.contains('is-open')) {
                            closeDrawer();
                        } else {
                            openDrawer();
                        }
                    });

                    overlay.addEventListener('click', closeDrawer);

                    closeButtons.forEach(function (button) {
                        button.addEventListener('click', closeDrawer);
                    });

                    document.addEventListener('keydown', function (event) {
                        if (event.key === 'Escape' && panel.classList.contains('is-open')) {
                            closeDrawer();
                        }
                    });
                };

                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', initCartDrawer);
                } else {
                    initCartDrawer();
                }
            })();
        </script>

        <?php
    }
}


