<?php

/** @var yii\web\View $this */
/** @var string $content */

use app\assets\AppAsset;
use app\widgets\Alert;
use yii\bootstrap5\Breadcrumbs;
use yii\bootstrap5\Html;
use yii\bootstrap5\Nav;
use yii\bootstrap5\NavBar;
use mdm\admin\components\MenuHelper;
use yii\web\View;
AppAsset::register($this);

$this->registerCsrfMetaTags();
$this->registerMetaTag(['charset' => Yii::$app->charset], 'charset');
$this->registerMetaTag(['name' => 'viewport', 'content' => 'width=device-width, initial-scale=1, shrink-to-fit=no']);
$this->registerMetaTag(['name' => 'description', 'content' => $this->params['meta_description'] ?? '']);
$this->registerMetaTag(['name' => 'keywords', 'content' => $this->params['meta_keywords'] ?? '']);
$this->registerLinkTag(['rel' => 'icon', 'type' => 'image/x-icon', 'href' => Yii::getAlias('@web/favicon.ico')]);

// Función para transformar los elementos del menú al formato que necesitamos
function transformMenuItems($items) {
    $result = [];
    foreach ($items as $item) {
        if (!isset($item['url'])) {
            continue;
        }
        
        // Determinar el icono basado en la ruta o usar un icono por defecto
        $icon = 'bi bi-cast';
        $url = is_array($item['url']) ? $item['url'][0] : $item['url'];
        
        // Asignar iconos según la ruta
        $iconMap = [
            'site/index' => 'bi bi-house',
            'user' => 'bi bi-people',
            'cliente' => 'bi bi-person-vcard',
            'pedido' => 'bi bi-cart3',
            'inventario' => 'bi bi-box-seam',
            'almacen' => 'bi bi-building',
            'novedades' => 'bi bi-newspaper',
            'chat' => 'bi bi-chat-dots',
            'devoluciones' => 'bi bi-box-arrow-in-left',
            'integracion' => 'bi bi-bezier2',
            'regiones' => 'bi bi-geo-alt',
            'dias-festivos' => 'bi bi-calendar-event',
            'configuracion' => 'bi bi-sliders',
            'rbac' => 'bi bi-shield',
            'admin' => 'bi bi-gear',
            'site/login' => 'bi bi-box-arrow-in-right',
            'site/logout' => 'bi bi-box-arrow-right',
        ];
        
        // Buscar coincidencias de iconos
        foreach ($iconMap as $route => $routeIcon) {
            if (strpos($url, $route) !== false) {
                $icon = $routeIcon;
                break;
            }
        }
        
        // Determinar si es la ruta activa
        $isActive = false;
        $routeWithoutParams = explode('?', Yii::$app->controller->route)[0];
        $itemRoute = is_array($item['url']) ? trim($item['url'][0], '/') : '';
        $isActive = ($routeWithoutParams == $itemRoute);
        
        // Crear el elemento con el formato correcto
        $newItem = [
            'label' => $item['label'],
            'url' => $item['url'],
            'icon' => $icon,
            'active' => $isActive,
            'visible' => isset($item['visible']) ? $item['visible'] : true,
        ];
        
        // Manejar elementos del submenú
        if (isset($item['items']) && is_array($item['items']) && !empty($item['items'])) {
            $newItem['items'] = transformMenuItems($item['items']);
            // Verificar si algún elemento hijo está activo
            foreach ($newItem['items'] as $child) {
                if (isset($child['active']) && $child['active']) {
                    $newItem['active'] = true;
                    break;
                }
            }
        }
        
        $result[] = $newItem;
    }
    return $result;
}

// Obtener los elementos del menú desde mdmsoft
$menuItems = MenuHelper::getAssignedMenu(Yii::$app->user->id);
// Transformar los elementos al formato que necesitamos
$sidebarItems = transformMenuItems($menuItems);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>" class="h-100">
<head>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        :root {
            --sidebar-width: 240px;
            --sidebar-bg: #ffffff;
            --sidebar-text: #656565;
            --sidebar-hover: #f5f5f5;
            --sidebar-active: #e9ecef;
            --sidebar-icon: #656565;
            --content-bg: #f5f7fb;
            --header-height: 60px;
            --logo-height: 70px;
        }

        body {
            background-color: var(--content-bg);
            overflow-x: hidden;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            height: 100%;
            width: var(--sidebar-width);
            background-color: var(--sidebar-bg);
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            z-index: 1000;
            transition: all 0.3s ease;
            overflow-y: auto;
        }

        .sidebar.collapsed {
            margin-left: calc(-1 * var(--sidebar-width));
        }

        .sidebar-logo {
            height: var(--logo-height);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 10px 15px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }

        .sidebar-logo img {
            max-height: 100%;
            max-width: 100%;
        }

        .sidebar-menu {
            padding: 15px 0;
            list-style: none;
            margin: 0;
        }

        .sidebar-item {
            margin-bottom: 5px;
        }

        .sidebar-link {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            color: var(--sidebar-text);
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .sidebar-link:hover {
            background-color: var(--sidebar-hover);
            color: #212529;
        }

        .sidebar-link.active {
            background-color: var(--sidebar-active);
            color: #212529;
            font-weight: 500;
        }

        .sidebar-icon {
            margin-right: 10px;
            font-size: 1.2rem;
            width: 30px;
            color: var(--sidebar-icon);
            text-align: center;
        }

        .sidebar-toggle {
            display: none;
            background: none;
            border: none;
            cursor: pointer;
            padding: 10px;
            font-size: 1.5rem;
        }

        /* Main content area */
        .main-content {
            margin-left: var(--sidebar-width);
            min-height: 100vh;
            transition: all 0.3s ease;
        }

        .main-header {
            height: var(--header-height);
            background-color: #fff;
            box-shadow: 0 1px 5px rgba(0,0,0,0.05);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
        }

        .main-container {
            padding: 20px;
        }

        .breadcrumb-container {
            background: #fff;
            padding: 10px 20px;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .sidebar {
                margin-left: calc(-1 * var(--sidebar-width));
            }

            .sidebar.mobile-show {
                margin-left: 0;
            }

            .main-content {
                margin-left: 0;
            }

            .sidebar-toggle {
                display: block;
            }
        }

        /* Dropdown menu in sidebar */
        .dropdown-menu {
            position: static;
            float: none;
            width: 100%;
            border: none;
            box-shadow: none;
            background-color: rgba(0,0,0,0.02);
            padding: 0;
            margin: 0;
        }

        .sidebar-item.has-submenu > .sidebar-link:after {
            content: "\f128";
            font-family: "bootstrap-icons";
            margin-left: auto;
            transition: transform 0.3s ease;
        }

        .sidebar-item.has-submenu.show > .sidebar-link:after {
            transform: rotate(90deg);
        }

        .submenu-link {
            padding-left: 60px;
            font-size: 0.95rem;
        }

        .user-dropdown {
            position: relative;
        }
        .user-dropdown .dropdown-menu {
            display: block;
            right: 0;
            left: auto;
            min-width: 200px;
            z-index: 1050;
        }
    </style>
</head>
<body class="d-flex flex-column h-100">
<?php $this->beginBody() ?>

<!-- Sidebar -->
<div class="sidebar" id="sidebar">
    <div class="sidebar-logo">
        <?= Html::img('@web/img/logo.png', ['alt' => Yii::$app->name, 'class' => 'img-fluid']) ?>
    </div>
    <ul class="sidebar-menu">
        <?php foreach ($sidebarItems as $item): ?>
            <?php if (isset($item['visible']) && !$item['visible']) continue; ?>
            
            <?php if (isset($item['items']) && !empty($item['items'])): ?>
                <!-- Elemento con submenu -->
                <li class="sidebar-item has-submenu <?= $item['active'] ? 'show' : '' ?>">
                    <a href="#" class="sidebar-link dropdown-toggle" data-bs-toggle="collapse" data-bs-target="#submenu-<?= md5($item['label']) ?>">
                        <i class="<?= $item['icon'] ?> sidebar-icon"></i>
                        <span><?= $item['label'] ?></span>
                    </a>
                    <div class="collapse <?= $item['active'] ? 'show' : '' ?>" id="submenu-<?= md5($item['label']) ?>">
                        <ul class="sidebar-menu">
                            <?php foreach ($item['items'] as $subItem): ?>
                                <?php if (isset($subItem['visible']) && !$subItem['visible']) continue; ?>
                                <li class="sidebar-item">
                                    <a href="<?= Yii::$app->urlManager->createUrl($subItem['url']) ?>" class="sidebar-link submenu-link <?= $subItem['active'] ? 'active' : '' ?>">
                                        <span><?= $subItem['label'] ?></span>
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </li>
            <?php else: ?>
                <!-- Elemento normal -->
                <li class="sidebar-item">
                    <a href="<?= Yii::$app->urlManager->createUrl($item['url']) ?>" class="sidebar-link <?= $item['active'] ? 'active' : '' ?>">
                        <i class="<?= $item['icon'] ?> sidebar-icon"></i>
                        <span><?= $item['label'] ?></span>
                    </a>
                </li>
            <?php endif; ?>
        <?php endforeach; ?>
    </ul>
</div>

<!-- Main Content -->
<div class="main-content" id="main-content">
    <!-- Header -->
    <div class="main-header">
        <button class="sidebar-toggle" id="sidebarToggle">
            <i class="bi bi-list"></i>
        </button>
        
        <div class="header-actions ms-auto">
            <?php if (Yii::$app->user->isGuest): ?>
                <?= Html::a('Login', ['/site/login'], ['class' => 'btn btn-outline-primary btn-sm']) ?>
            <?php else: ?>
                <div class="dropdown">
                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="toggleUserMenu()">
                        <i class="bi bi-person-circle me-1"></i>
                        <?= Yii::$app->user->identity->usr_nombre ?> 
                        <i class="bi bi-chevron-down ms-1"></i>
                    </button>
                    <div id="userDropdownMenu" class="dropdown-menu dropdown-menu-end" style="position: absolute; right: 20px;">
                        <div class="dropdown-divider"></div>
                        <?= Html::a(
                            '<i class="bi bi-box-arrow-right me-2"></i>Cerrar sesión',
                            ['/site/logout'],
                            [
                                'class' => 'dropdown-item',
                                'data' => ['method' => 'post'],
                            ]
                        ) ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>


    </div>
    
    <!-- Main Container -->
    <div class="main-container">
        <!-- Breadcrumbs -->
        <?php if (!empty($this->params['breadcrumbs'])): ?>
            <div class="breadcrumb-container">
                <?= Breadcrumbs::widget([
                    'links' => $this->params['breadcrumbs'],
                    'homeLink' => [
                        'label' => '<i class="bi bi-house-door"></i> Inicio',
                        'url' => Yii::$app->homeUrl,
                        'encode' => false,
                    ],
                ]) ?>
            </div>
        <?php endif; ?>
        
        <!-- Alert Messages -->
        <?= Alert::widget() ?>
        
        <!-- Main Content -->
        <?= $content ?>
    </div>
</div>

<?php
// JavaScript para la funcionalidad del menú
// Reemplaza el JavaScript al final del archivo main.php con este código:

$this->registerJs("
    // Toggle sidebar en móviles
    document.getElementById('sidebarToggle').addEventListener('click', function() {
        document.getElementById('sidebar').classList.toggle('mobile-show');
    });
    
    // Funcionalidad de submenús
    const submenuToggles = document.querySelectorAll('.sidebar-item.has-submenu > .sidebar-link');
    submenuToggles.forEach(toggle => {
        toggle.addEventListener('click', function(e) {
            e.preventDefault(); // Prevenir la navegación
            
            // Referencia al ID del submenú
            const targetId = this.getAttribute('data-bs-target');
            const targetElement = document.querySelector(targetId);
            
            // Alternar la clase 'show' en el elemento padre
            this.closest('.sidebar-item').classList.toggle('show');
            
            // Alternar manualmente la clase 'show' en el submenú
            // porque Bootstrap 5 puede no estar inicializado correctamente
            if (targetElement) {
                if (targetElement.classList.contains('show')) {
                    targetElement.classList.remove('show');
                } else {
                    targetElement.classList.add('show');
                }
            }
        });
    });
    
    // Si estamos en móvil, cerrar el menú cuando se hace click en un enlace
    const menuLinks = document.querySelectorAll('.sidebar-link:not(.dropdown-toggle)');
    menuLinks.forEach(link => {
        link.addEventListener('click', function() {
            if (window.innerWidth < 768) {
                document.getElementById('sidebar').classList.remove('mobile-show');
            }
        });
    });

    function toggleUserMenu() {
        var menu = document.getElementById('userDropdownMenu');
        if (menu.style.display === 'block') {
            menu.style.display = 'none';
        } else {
            menu.style.display = 'block';
        }
    }
    
    // Cerrar el menú cuando se hace clic fuera de él
    document.addEventListener('click', function(event) {
        var menu = document.getElementById('userDropdownMenu');
        var button = document.querySelector('.header-actions .btn');
        
        if (menu && !menu.contains(event.target) && !button.contains(event.target)) {
            menu.style.display = 'none';
        }
    });


", View::POS_END);
?>

<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>