<?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\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;

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

/**
 * Breadcrumbs Widget
 *
 * @since 1.0.0
 */
class Breadcrumbs extends Widget_Base
{
    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     */
    public function get_name()
    {
        return 'unlockafe-breadcrumbs';
    }

    /**
     * Retrieve the widget title.
     */
    public function get_title()
    {
        return __('Breadcrumbs', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     */
    public function get_icon()
    {
        return 'eicon-navigation-horizontal ulicon';
    }

    /**
     * Retrieve the list of categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of keywords.
     */
    public function get_keywords()
    {
        return ['breadcrumb', 'breadcrumbs', 'navigation', 'path', 'trail'];
    }

    /**
     * Retrieve the list of scripts.
     */
    public function get_script_depends()
    {
        return [];
    }

    /**
     * Retrieve the list of styles.
     */
    public function get_style_depends()
    {
        return ['unlockafe-breadcrumbs-style', 'font-awesome'];
    }

    /**
     * Register widget controls.
     */
    protected function register_controls()
    {
        $this->register_content_controls();
        $this->register_style_controls();
    }

    /**
     * Register content controls.
     */
    protected function register_content_controls()
    {
        // General Settings
        $this->start_controls_section(
            'general_section',
            [
                'label' => __('General Settings', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'breadcrumb_layout',
            [
                'label' => __('Layout', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'layout-1' => __('Design 1 - Simple Text', 'unlock-addons-for-elementor'),
                    'layout-2' => __('Design 2 - Pills with Icons', 'unlock-addons-for-elementor'),
                    'layout-3' => __('Design 3 - Text with Line', 'unlock-addons-for-elementor'),
                    'layout-4' => __('Design 4 - Pills Pink', 'unlock-addons-for-elementor'),
                    'layout-5' => __('Design 5 - Pills Gradient', 'unlock-addons-for-elementor'),
                    'layout-6' => __('Design 6 - Text Slash', 'unlock-addons-for-elementor'),
                    'layout-7' => __('Design 7 - Pills Blue', 'unlock-addons-for-elementor'),
                ],
                'default' => 'layout-1',
            ]
        );

        $this->add_control(
            'breadcrumb_source',
            [
                'label' => __('Breadcrumb Source', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'auto' => __('Auto (WordPress)', 'unlock-addons-for-elementor'),
                    'manual' => __('Manual', 'unlock-addons-for-elementor'),
                ],
                'default' => 'auto',
            ]
        );

        $repeater = new Repeater();

        $repeater->add_control(
            'item_text',
            [
                'label' => __('Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('Home', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter breadcrumb text', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'item_link',
            [
                'label' => __('Link', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::URL,
                'placeholder' => __('https://your-link.com', 'unlock-addons-for-elementor'),
                'show_external' => true,
                'default' => [
                    'url' => '#',
                    'is_external' => false,
                    'nofollow' => false,
                ],
            ]
        );

        $repeater->add_control(
            'item_icon',
            [
                'label' => __('Icon', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::ICONS,
                'default' => [
                    'value' => 'fas fa-home',
                    'library' => 'fa-solid',
                ],
            ]
        );

        $repeater->add_control(
            'is_active',
            [
                'label' => __('Active Item', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'breadcrumb_items',
            [
                'label' => __('Breadcrumb Items', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [
                    [
                        'item_text' => __('Home', 'unlock-addons-for-elementor'),
                        'item_link' => ['url' => home_url()],
                        'item_icon' => ['value' => 'fas fa-home', 'library' => 'fa-solid'],
                        'is_active' => '',
                    ],
                    [
                        'item_text' => __('Pages', 'unlock-addons-for-elementor'),
                        'item_link' => ['url' => '#'],
                        'is_active' => '',
                    ],
                    [
                        'item_text' => __('Elementor Breadcrumb Widget Demo', 'unlock-addons-for-elementor'),
                        'item_link' => ['url' => '#'],
                        'is_active' => 'yes',
                    ],
                ],
                'title_field' => '{{{ item_text }}}',
                'condition' => [
                    'breadcrumb_source' => 'manual',
                ],
            ]
        );

        $this->add_control(
            'separator',
            [
                'label' => __('Separator', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    '>' => __('> (Greater Than)', 'unlock-addons-for-elementor'),
                    '/' => __('/ (Slash)', 'unlock-addons-for-elementor'),
                    '|' => __('| (Pipe)', 'unlock-addons-for-elementor'),
                    '→' => __('→ (Arrow)', 'unlock-addons-for-elementor'),
                    '·' => __('· (Dot)', 'unlock-addons-for-elementor'),
                ],
                'default' => '>',
                'condition' => [
                    'breadcrumb_layout' => ['layout-1', 'layout-3', 'layout-6'],
                ],
            ]
        );

        $this->add_control(
            'show_home_icon',
            [
                'label' => __('Show Home Icon', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register style controls.
     */
    protected function register_style_controls()
    {
        // Container Style
        $this->start_controls_section(
            'container_style_section',
            [
                'label' => __('Container', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'container_alignment',
            [
                'label' => __('Alignment', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::CHOOSE,
                'options' => [
                    'left' => [
                        'title' => __('Left', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-left',
                    ],
                    'center' => [
                        'title' => __('Center', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-center',
                    ],
                    'right' => [
                        'title' => __('Right', 'unlock-addons-for-elementor'),
                        'icon' => 'eicon-text-align-right',
                    ],
                ],
                'default' => 'left',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumbs-wrapper' => 'text-align: {{VALUE}};',
                ],
            ]
        );

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

        $this->end_controls_section();

        // Item Style
        $this->start_controls_section(
            'item_style_section',
            [
                'label' => __('Breadcrumb Item', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'item_background',
            [
                'label' => __('Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumb-item' => 'background-color: {{VALUE}};',
                ],
                'condition' => [
                    'breadcrumb_layout' => ['layout-2', 'layout-4', 'layout-5', 'layout-7'],
                ],
            ]
        );

        $this->add_control(
            'item_text_color',
            [
                'label' => __('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumb-item' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'item_typography',
                'selector' => '{{WRAPPER}} .unlockafe-breadcrumb-item',
            ]
        );

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

        $this->add_control(
            'item_border_radius',
            [
                'label' => __('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumb-item' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
                'condition' => [
                    'breadcrumb_layout' => ['layout-2', 'layout-4', 'layout-5', 'layout-7'],
                ],
            ]
        );

        $this->end_controls_section();

        // Active Item Style
        $this->start_controls_section(
            'active_item_style_section',
            [
                'label' => __('Active Item', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'active_item_background',
                'label' => __('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlockafe-breadcrumb-item.active',
            ]
        );

        $this->add_control(
            'active_item_text_color',
            [
                'label' => __('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumb-item.active' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->end_controls_section();

        // Separator Style
        $this->start_controls_section(
            'separator_style_section',
            [
                'label' => __('Separator', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'separator_color',
            [
                'label' => __('Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumb-separator' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'separator_typography',
                'selector' => '{{WRAPPER}} .unlockafe-breadcrumb-separator',
            ]
        );

        $this->end_controls_section();

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

        $this->add_control(
            'icon_color',
            [
                'label' => __('Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumb-icon' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'icon_size',
            [
                'label' => __('Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => 10,
                        'max' => 50,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 14,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-breadcrumb-icon' => 'font-size: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Get WordPress breadcrumbs
     */
    private function get_wp_breadcrumbs() {
        $breadcrumbs = [];
        
        // Home
        $breadcrumbs[] = [
            'text' => __('Home', 'unlock-addons-for-elementor'),
            'link' => home_url(),
            'icon' => 'fas fa-home',
            'is_active' => false,
        ];

        if (is_front_page()) {
            $breadcrumbs[0]['is_active'] = true;
            return $breadcrumbs;
        }

        // Category
        if (is_category()) {
            $category = get_queried_object();
            $breadcrumbs[] = [
                'text' => $category->name,
                'link' => get_category_link($category->term_id),
                'icon' => '',
                'is_active' => true,
            ];
        }
        // Single Post
        elseif (is_single()) {
            $post = get_queried_object();
            $categories = get_the_category($post->ID);
            if (!empty($categories)) {
                $category = $categories[0];
                $breadcrumbs[] = [
                    'text' => $category->name,
                    'link' => get_category_link($category->term_id),
                    'icon' => '',
                    'is_active' => false,
                ];
            }
            $breadcrumbs[] = [
                'text' => get_the_title($post->ID),
                'link' => get_permalink($post->ID),
                'icon' => '',
                'is_active' => true,
            ];
        }
        // Page
        elseif (is_page()) {
            $page = get_queried_object();
            $breadcrumbs[] = [
                'text' => get_the_title($page->ID),
                'link' => get_permalink($page->ID),
                'icon' => '',
                'is_active' => true,
            ];
        }
        // Archive
        elseif (is_archive()) {
            $breadcrumbs[] = [
                'text' => get_the_archive_title(),
                'link' => '',
                'icon' => '',
                'is_active' => true,
            ];
        }

        return $breadcrumbs;
    }

    /**
     * Render widget output on the frontend.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $layout = $settings['breadcrumb_layout'] ?? 'layout-1';
        $breadcrumb_source = $settings['breadcrumb_source'] ?? 'auto';
        $separator = $settings['separator'] ?? '>';
        $show_home_icon = $settings['show_home_icon'] === 'yes';

        // Get breadcrumb items
        $items = [];
        if ($breadcrumb_source === 'auto') {
            $items = $this->get_wp_breadcrumbs();
        } else {
            $manual_items = !empty($settings['breadcrumb_items']) ? $settings['breadcrumb_items'] : [];
            foreach ($manual_items as $item) {
                $items[] = [
                    'text' => !empty($item['item_text']) ? esc_html($item['item_text']) : '',
                    'link' => !empty($item['item_link']['url']) ? esc_url($item['item_link']['url']) : '',
                    'icon' => !empty($item['item_icon']['value']) ? $item['item_icon']['value'] : '',
                    'is_active' => $item['is_active'] === 'yes',
                ];
            }
        }

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

        $wrapper_class = 'unlockafe-breadcrumbs-wrapper';
        $wrapper_class .= ' unlockafe-breadcrumbs-' . esc_attr($layout);

        ?>
        <div class="<?php echo esc_attr($wrapper_class); ?>">
            <nav class="unlockafe-breadcrumbs-nav" aria-label="Breadcrumb">
                <ol class="unlockafe-breadcrumbs-list">
                    <?php foreach ($items as $index => $item): 
                        $is_last = ($index === count($items) - 1);
                        $is_active = $item['is_active'] || $is_last;
                        $item_text = $item['text'];
                        $item_link = $item['link'];
                        $item_icon = !empty($item['icon']) ? $item['icon'] : '';
                        
                        // Handle home icon visibility for first item
                        if ($index === 0) {
                            if ($show_home_icon) {
                                // Show home icon if enabled and not already set
                                if (empty($item_icon)) {
                                    $item_icon = 'fas fa-home';
                                }
                            } else {
                                // Hide home icon if disabled
                                $item_icon = '';
                            }
                        }
                    ?>
                        <?php if ($index > 0): ?>
                            <li class="unlockafe-breadcrumb-separator-wrapper">
                                <?php if (in_array($layout, ['layout-1', 'layout-3', 'layout-6'])): ?>
                                    <span class="unlockafe-breadcrumb-separator"><?php echo esc_html($separator); ?></span>
                                <?php elseif ($layout === 'layout-2'): ?>
                                    <span class="unlockafe-breadcrumb-separator-line"></span>
                                <?php endif; ?>
                            </li>
                        <?php endif; ?>
                        
                        <li class="unlockafe-breadcrumb-item-wrapper">
                            <?php if ($item_link && !$is_active): ?>
                                <a href="<?php echo esc_url($item_link); ?>" class="unlockafe-breadcrumb-item<?php echo $is_active ? ' active' : ''; ?>">
                                    <?php if ($item_icon): ?>
                                        <i class="unlockafe-breadcrumb-icon <?php echo esc_attr($item_icon); ?>"></i>
                                    <?php endif; ?>
                                    <span class="unlockafe-breadcrumb-text"><?php echo $item_text; ?></span>
                                </a>
                            <?php else: ?>
                                <span class="unlockafe-breadcrumb-item<?php echo $is_active ? ' active' : ''; ?>">
                                    <?php if ($item_icon): ?>
                                        <i class="unlockafe-breadcrumb-icon <?php echo esc_attr($item_icon); ?>"></i>
                                    <?php endif; ?>
                                    <span class="unlockafe-breadcrumb-text"><?php echo $item_text; ?></span>
                                </span>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ol>
            </nav>
        </div>
        <?php
    }
}


