<?php

namespace Modules\Admin\App\Services;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Modules\Admin\App\Models\Setting;

class VuexyAdminService
{
    private $vuexySearch;
    private $quicklinksRouteNames = [];

    protected $cacheTTL = 60 * 24 * 30; // 30 días en minutos

    private $homeRoute = [
        'name' => 'Inicio',
        'route' => 'admin.home.index',
    ];

    private $user;

    private $orientation;

    public function __construct()
    {
        $this->user = Auth::user();
        $this->vuexySearch = Auth::user() !== null;
        $this->orientation = config('custom.custom.myLayout');
    }

    /**
     * Obtiene el menú según el estado del usuario (autenticado o no).
     */
    public function getMenu()
    {
        // Obtener el menú desde la caché
        $menu = $this->user === null
            ? $this->getGuestMenu()
            : $this->getUserMenu();

        // Marcar la ruta actual como activa
        $currentRoute = Route::currentRouteName();

        return $this->markActive($menu, $currentRoute);
    }

    /**
     * Menú para usuarios no autenticados.
     */
    private function getGuestMenu()
    {
        return Cache::remember('vuexy_menu_guest', now()->addDays(7), function () {
            return $this->getMenuArray();
        });
    }

    /**
     * Menú para usuarios autenticados.
     */
    private function getUserMenu()
    {
        //Cache::forget("vuexy_menu_user_{$this->user->id}"); // Borrar la caché anterior para actualizarla

        return Cache::remember("vuexy_menu_user_{$this->user->id}", now()->addHours(24), function () {
            return $this->getMenuArray();
        });
    }

    private function processMenu($menu)
    {
        foreach ($menu as &$item) {
            // Determinar visibilidad actual (si no está definida, es true por defecto)
            $item['visible'] = $item['visible'] ?? true;

            // Procesar submenús de manera recursiva
            if (isset($item['submenu']) && is_array($item['submenu'])) {
                $item['submenu'] = $this->processMenu($item['submenu']);

                // Un submenú es visible si al menos uno de sus hijos es visible
                $item['visible'] = collect($item['submenu'])->contains('visible', true);
            }

            // Generar URL para los elementos del menú que tengan una ruta definida
            if (isset($item['route']))
                $item['url'] = Route::has($item['route']) ? route($item['route']) : '#';
        }

        // Filtrar los elementos del menú que no sean visibles
        return array_filter($menu, fn($item) => $item['visible']);
    }

    private function markActive($menu, $currentRoute)
    {
        foreach ($menu as &$item) {
            $item['active'] = false;

            // Check if the route matches
            if (isset($item['route']) && $item['route'] === $currentRoute)
                $item['active'] = true;

            // Process submenus recursively
            if (isset($item['submenu']) && !empty($item['submenu'])) {
                $item['submenu'] = $this->markActive($item['submenu'], $currentRoute);

                // If any submenu is active, mark the parent as active
                if (collect($item['submenu'])->contains('active', true))
                    $item['active'] = true;
            }
        }

        return $menu;
    }

    /**
     * Invalida el cache del menú de un usuario.
     */
    public static function clearUserMenuCache()
    {
        $user = Auth::user();

        if ($user !== null)
            Cache::forget("vuexy_menu_user_{$user->id}");
    }

    /**
     * Invalida el cache del menú de invitados.
     */
    public static function clearGuestMenuCache()
    {
        Cache::forget('vuexy_menu_guest');
    }



    public function getSearch()
    {
        return $this->vuexySearch;
    }

    public function getVuexySearchData()
    {
        if ($this->user === null)
            return null;

        $pages = Cache::remember("vuexy_search_user_{$this->user->id}", now()->addDays(7), function () {
            return $this->cacheVuexySearchData();
        });

        // Formatear como JSON esperado
        return [
            'pages' => $pages,
        ];
    }

    private function cacheVuexySearchData()
    {
        $originalMenu = $this->getUserMenu();

        return  $this->getPagesSearchMenu($originalMenu);
    }

    private function getPagesSearchMenu(array $menu, string $parentPath = '')
    {
        $formattedMenu = [];

        foreach ($menu as $name => $item) {
            // Verificar si el elemento es visible
            if (isset($item['visible']) && !$item['visible']) {
                continue;
            }

            // Construir la ruta jerárquica (menu / submenu / submenu)
            $currentPath = $parentPath ? $parentPath . ' / ' . $name : $name;

            // Verificar si el elemento tiene una URL o una ruta
            $url = $item['url'] ?? (isset($item['route']) ? route($item['route']) : null);

            // Agregar el elemento al menú formateado
            if ($url) {
                $formattedMenu[] = [
                    'name' => $currentPath, // Usar la ruta completa
                    'icon' => $item['icon'] ?? 'ti ti-point',
                    'url' => $url,
                ];
            }

            // Si hay un submenú, procesarlo recursivamente
            if (isset($item['submenu']) && is_array($item['submenu'])) {
                $formattedMenu = array_merge(
                    $formattedMenu,
                    $this->getPagesSearchMenu($item['submenu'], $currentPath) // Pasar el path acumulado
                );
            }
        }

        return $formattedMenu;
    }

    public static function clearSearchMenuCache()
    {
        $user = Auth::user();

        if ($user !== null)
            Cache::forget("vuexy_search_user_{$user->id}");
    }



    public function getQuickLinks()
    {
        if ($this->user === null)
            return null;

        // Recuperar enlaces desde la caché
        $quickLinks = Cache::remember("vuexy_quick_links_user_{$this->user->id}", now()->addDays(7), function () {
            return $this->cacheQuickLinks();
        });

        // Verificar si la ruta actual está en la lista
        $currentRoute = Route::currentRouteName();
        $currentPageInList = $this->isCurrentPageInList($quickLinks, $currentRoute);

        // Agregar la verificación al resultado
        $quickLinks['current_page_in_list'] = $currentPageInList;

        return $quickLinks;
    }

    private function cacheQuickLinks()
    {
        $originalMenu = $this->getUserMenu();

        $quickLinks = [];

        $quicklinks = Setting::where('user_id', Auth::user()->id)
            ->where('key', 'quicklinks')
            ->first();

        $this->quicklinksRouteNames = $quicklinks ? json_decode($quicklinks->value, true) : [];

        // Ordenar y generar los quickLinks según el orden del menú
        $this->collectQuickLinksFromMenu($originalMenu, $quickLinks);

        $quickLinksData = [
            'totalLinks' => count($quickLinks),
            'rows' => array_chunk($quickLinks, 2), // Agrupar los atajos en filas de dos
        ];

        return $quickLinksData;
    }

    private function collectQuickLinksFromMenu(array $menu, array &$quickLinks, string $parentTitle = null)
    {
        foreach ($menu as $title => $item) {
            // Verificar si el elemento está en la lista de quicklinksRouteNames
            if (isset($item['route']) && in_array($item['route'], $this->quicklinksRouteNames)) {
                $quickLinks[] = [
                    'title' => $title,
                    'subtitle' => $parentTitle ?? env('APP_NAME'),
                    'icon' => $item['icon'] ?? 'ti ti-point',
                    'url' => isset($item['route']) ? route($item['route']) : ($item['url'] ?? '#'),
                    'route' => $item['route'],
                ];
            }

            // Si tiene submenú, procesarlo recursivamente
            if (isset($item['submenu']) && is_array($item['submenu'])) {
                $this->collectQuickLinksFromMenu(
                    $item['submenu'],
                    $quickLinks,
                    $title // Pasar el título actual como subtítulo
                );
            }
        }
    }

    /**
     * Verifica si la ruta actual existe en la lista de enlaces.
     */
    private function isCurrentPageInList(array $quickLinks, string $currentRoute): bool
    {
        foreach ($quickLinks['rows'] as $row) {
            foreach ($row as $link) {
                if (isset($link['route']) && $link['route'] === $currentRoute) {
                    return true;
                }
            }
        }
        return false;
    }

    public static function clearQuickLinksCache()
    {
        $user = Auth::user();

        if ($user !== null)
            Cache::forget("vuexy_quick_links_user_{$user->id}");
    }



    public function getNotifications()
    {
        if ($this->user === null)
            return null;

        return Cache::remember("vuexy_notifications_user_{$this->user->id}", now()->addHours(4), function () {
            return $this->cacheNotifications();
        });
    }

    private function cacheNotifications()
    {
        return "<li class='nav-item dropdown-notifications navbar-dropdown dropdown me-3 me-xl-2'>
                <a class='nav-link btn btn-text-secondary btn-icon rounded-pill dropdown-toggle hide-arrow' href='javascript:void(0);' data-bs-toggle='dropdown' data-bs-auto-close='outside' aria-expanded='false'>
                    <span class='position-relative'>
                        <i class='ti ti-bell ti-md'></i>
                        <span class='badge rounded-pill bg-danger badge-dot badge-notifications border'></span>
                    </span>
                </a>
                <ul class='dropdown-menu dropdown-menu-end p-0'>
                    <li class='dropdown-menu-header border-bottom'>
                        <div class='dropdown-header d-flex align-items-center py-3'>
                            <h6 class='mb-0 me-auto'>Notification</h6>
                            <div class='d-flex align-items-center h6 mb-0'>
                                <span class='badge bg-label-primary me-2'>8 New</span>
                                <a href='javascript:void(0)' class='btn btn-text-secondary rounded-pill btn-icon dropdown-notifications-all' data-bs-toggle='tooltip' data-bs-placement='top' title='Mark all as read'><i class='ti ti-mail-opened text-heading'></i></a>
                            </div>
                        </div>
                    </li>
                    <li class='dropdown-notifications-list scrollable-container'>
                        <ul class='list-group list-group-flush'>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <img src='' . asset('assets/admin/img/avatars/1.png') . '' alt class='rounded-circle'>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='small mb-1'>Congratulation Lettie 🎉</h6>
                                        <small class='mb-1 d-block text-body'>Won the monthly best seller gold badge</small>
                                        <small class='text-muted'>1h ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <span class='avatar-initial rounded-circle bg-label-danger'>CF</span>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>Charles Franklin</h6>
                                        <small class='mb-1 d-block text-body'>Accepted your connection</small>
                                        <small class='text-muted'>12hr ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item marked-as-read'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <img src='' . asset('assets/admin/img/avatars/2.png') . '' alt class='rounded-circle'>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>New Message ✉️</h6>
                                        <small class='mb-1 d-block text-body'>You have new message from Natalie</small>
                                        <small class='text-muted'>1h ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <span class='avatar-initial rounded-circle bg-label-success'><i class='ti ti-shopping-cart'></i></span>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>Whoo! You have new order 🛒 </h6>
                                        <small class='mb-1 d-block text-body'>ACME Inc. made new order $1,154</small>
                                        <small class='text-muted'>1 day ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item marked-as-read'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <img src='' . asset('assets/admin/img/avatars/9.png') . '' alt class='rounded-circle'>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>Application has been approved 🚀 </h6>
                                        <small class='mb-1 d-block text-body'>Your ABC project application has been approved.</small>
                                        <small class='text-muted'>2 days ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item marked-as-read'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <span class='avatar-initial rounded-circle bg-label-success'><i class='ti ti-chart-pie'></i></span>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>Monthly report is generated</h6>
                                        <small class='mb-1 d-block text-body'>July monthly financial report is generated </small>
                                        <small class='text-muted'>3 days ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item marked-as-read'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <img src='' . asset('assets/admin/img/avatars/5.png') . '' alt class='rounded-circle'>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>Send connection request</h6>
                                        <small class='mb-1 d-block text-body'>Peter sent you connection request</small>
                                        <small class='text-muted'>4 days ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <img src='' . asset('assets/admin/img/avatars/6.png') . '' alt class='rounded-circle'>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>New message from Jane</h6>
                                        <small class='mb-1 d-block text-body'>Your have new message from Jane</small>
                                        <small class='text-muted'>5 days ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                            <li class='list-group-item list-group-item-action dropdown-notifications-item marked-as-read'>
                                <div class='d-flex'>
                                    <div class='flex-shrink-0 me-3'>
                                        <div class='avatar'>
                                            <span class='avatar-initial rounded-circle bg-label-warning'><i class='ti ti-alert-triangle'></i></span>
                                        </div>
                                    </div>
                                    <div class='flex-grow-1'>
                                        <h6 class='mb-1 small'>CPU is running high</h6>
                                        <small class='mb-1 d-block text-body'>CPU Utilization Percent is currently at 88.63%,</small>
                                        <small class='text-muted'>5 days ago</small>
                                    </div>
                                    <div class='flex-shrink-0 dropdown-notifications-actions'>
                                        <a href='javascript:void(0)' class='dropdown-notifications-read'><span class='badge badge-dot'></span></a>
                                        <a href='javascript:void(0)' class='dropdown-notifications-archive'><span class='ti ti-x'></span></a>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </li>
                    <li class='border-top'>
                        <div class='d-grid p-4'>
                            <a class='btn btn-primary btn-sm d-flex' href='javascript:void(0);'>
                                <small class='align-middle'>View all notifications</small>
                            </a>
                        </div>
                    </li>
                </ul>
            </li>";
    }

    public static function clearNotificationsCache()
    {
        $user = Auth::user();

        if ($user !== null)
            Cache::forget("vuexy_notifications_user_{$user->id}");
    }



    public function getBreadcrumbs()
    {
        $originalMenu = $this->user === null
            ? $this->getGuestMenu()
            : $this->getUserMenu();

        $routeName = Route::currentRouteName() ? Route::currentRouteName() : '';

        // Lógica para construir los breadcrumbs
        $breadcrumbs = $this->findBreadcrumbTrail($originalMenu, $routeName);

        // Asegurar que el primer elemento siempre sea "Inicio"
        array_unshift($breadcrumbs, $this->homeRoute);

        return $breadcrumbs;
    }

    private function findBreadcrumbTrail(array $menu, string $routeName, array $breadcrumbs = []): array
    {
        foreach ($menu as $title => $item) {
            $skipBreadcrumb = isset($item['breadcrumbs']) && $item['breadcrumbs'] === false;

            if (isset($item['route']) && $item['route'] === $routeName) {
                if (!$skipBreadcrumb) {
                    $breadcrumbs[] = [
                        'name' => $title,
                        'active' => true,
                    ];
                }

                return $breadcrumbs;
            }

            if (isset($item['submenu']) && is_array($item['submenu'])) {
                $newBreadcrumbs = $breadcrumbs;

                if (!$skipBreadcrumb)
                    $newBreadcrumbs[] = [
                        'name' => $title,
                        'route' => $item['route'] ?? null,
                    ];

                $found = $this->findBreadcrumbTrail($item['submenu'], $routeName, $newBreadcrumbs);

                if ($found)
                    return $found;
            }
        }

        return [];
    }



    private function getMenuArray()
    {
        if ($this->orientation === 'horizontal') {
            return $this->processMenu($this->getHorizontalMenu());
        } else {
            return $this->processMenu($this->getVerticalMenu());
        }
    }

    private function getVerticalMenu()
    {
        return $this->getHorizontalMenu();
    }

    private function getHorizontalMenu()
    {
        return [
            'Inicio' => [
                'breadcrumbs' => false,
                'icon' => 'menu-icon tf-icons ti ti-home',
                'submenu' => [
                    'Inicio' => [
                        'route' => 'admin.home.index',
                        'icon' => 'menu-icon tf-icons ti ti-home',
                    ],
                    'Ajustes' => [
                        'icon' => 'menu-icon tf-icons ti ti-settings-cog',
                        'submenu' => [
                            'Aplicación' => [
                                'submenu' => [
                                    'Ajustes generales' => [
                                        'route' => 'admin.webapp.general-settings.index',
                                        'icon' => 'menu-icon tf-icons ti ti-adjustments-alt',
                                        'visible' => $this->canUserAccess('webapp.general-settings.allow'),
                                    ],
                                    'Ajustes de caché' => [
                                        'route' => 'admin.webapp.cache-manager.index',
                                        'icon' => 'menu-icon tf-icons ti ti-cpu',
                                        'visible' => $this->canUserAccess('webapp.cache-manager.view'),
                                    ],
                                    'API BANXICO' => [
                                        'route' => 'admin.webapp.api-banxico.index',
                                        'icon' => 'menu-icon tf-icons ti ti-building-bank',
                                        'visible' => $this->canUserAccess('webapp.api-banxico.allow'),
                                    ],
                                    'Servidor de correo SMTP' => [
                                        'route' => 'admin.webapp.smtp-settings.index',
                                        'icon' => 'menu-icon tf-icons ti ti-mail-cog',
                                        'visible' => $this->canUserAccess('webapp.smtp-settings.allow'),
                                    ],
                                    'Catálogos' => [
                                        'route' => 'admin.webapp.catalogs.index',
                                        'icon' => 'menu-icon tf-icons ti ti-library',
                                        'visible' => $this->canUserAccess('webapp.catalogs.view'),
                                    ],
                                ],
                            ],
                            'Sitio Web' => [
                                'submenu' => [
                                    'Ajustes generales' => [
                                        'route' => 'admin.website.general-settings.index',
                                        'icon' => 'menu-icon tf-icons ti ti-tools',
                                        'visible' => $this->canUserAccess('website.general-settings.allow'),
                                    ],
                                    'Avisos legales' => [
                                        'route' => 'admin.website.legal.index',
                                        'icon' => 'menu-icon tf-icons ti ti-writing-sign',
                                        'visible' => $this->canUserAccess('website.legal.view'),
                                    ],
                                ],
                            ],
                            'Empresa' => [
                                'submenu' => [
                                    'Información general' => [
                                        'route' => 'admin.company.general-settings.index',
                                        'icon' => 'menu-icon tf-icons ti ti-adjustments-alt',
                                        'visible' => $this->canUserAccess('company.general-settings.allow'),
                                    ],
                                    'Sucursales' => [
                                        'route' => 'admin.company.stores.index',
                                        'icon' => 'menu-icon tf-icons ti ti-building',
                                        'visible' => $this->canUserAccess('company.stores.view'),
                                    ],
                                    'Centros de trabajo' => [
                                        'route' => 'admin.company.workcenters.index',
                                        'icon' => 'menu-icon tf-icons ti ti-map-pin-cog',
                                        'visible' => $this->canUserAccess('company.stores.view'),
                                    ],
                                    'Catálogos' => [
                                        'route' => 'admin.company.catalogs.index',
                                        'icon' => 'menu-icon tf-icons ti ti-library',
                                        'visible' => $this->canUserAccess('company.catalogs.view'),
                                    ],
                                ]
                            ],
                            'Punto de venta' => [
                                'submenu' => [
                                    'Listas de precios' => [
                                        'route' => 'admin.pos.pricelists-config.index',
                                        'icon' => 'menu-icon tf-icons ti ti-list-search',
                                        'visible' => $this->canUserAccess('pos.pricelists-config.allow'),
                                    ],
                                    'Ticket' => [
                                        'route' => 'admin.pos.ticket-config.index',
                                        'icon' => 'menu-icon tf-icons ti ti-receipt',
                                        'visible' => $this->canUserAccess('pos.ticket-config.allow'),
                                    ],
                                    'Catálogos' => [
                                        'route' => 'admin.pos.catalogs.index',
                                        'icon' => 'menu-icon tf-icons ti ti-library',
                                        'visible' => $this->canUserAccess('pos.catalogs.view'),
                                    ],
                                ]
                            ],
                            'Facturación' => [
                                'submenu' => [
                                    'Configuraciones' => [
                                        'route' => 'admin.billing.general-settings.index',
                                        'icon' => 'menu-icon tf-icons ti ti-tool',
                                        'visible' => $this->canUserAccess('billing.general-settings.allow'),
                                    ],
                                    'Certificados de Sello Digital' => [
                                        'route' => 'admin.billing.csds-settings.index',
                                        'icon' => 'menu-icon tf-icons ti ti-certificate-2',
                                        'visible' => $this->canUserAccess('billing.csds-settings.allow'),
                                    ],
                                    'Paquete de timbrado' => [
                                        'route' => 'admin.billing.stamping-package.index',
                                        'icon' => 'menu-icon tf-icons ti ti-bell-cog',
                                        'visible' => $this->canUserAccess('billing.stamping-package.allow'),
                                    ],
                                    'Servidor de correo SMTP' => [
                                        'route' => 'admin.billing.smtp-settings.index',
                                        'icon' => 'menu-icon tf-icons ti ti-mail-cog',
                                        'visible' => $this->canUserAccess('billing.smtp-settings.allow'),
                                    ],
                                ]
                            ],
                        ]
                    ],
                    'Sistema' => [
                        'icon' => 'menu-icon tf-icons ti ti-user-cog',
                        'submenu' => [
                            'Usuarios' => [
                                'route' => 'admin.system.users.index',
                                'icon' => 'menu-icon tf-icons ti ti-users',
                                'visible' => $this->canUserAccess('system.users.view'),
                            ],
                            'Roles y permisos' => [
                                'submenu' => [
                                    'Roles' => [
                                        'route' => 'admin.system.roles.index',
                                        'icon' => 'menu-icon tf-icons ti ti-user-shield',
                                        'visible' => $this->canUserAccess('system.roles.view'),
                                    ],
                                    'Permisos' => [
                                        'route' => 'admin.system.permissions.index',
                                        'icon' => 'menu-icon tf-icons ti ti-user-star',
                                        'visible' => $this->canUserAccess('system.permissions.view'),
                                    ]
                                ]
                            ],
                            'Importar' => [
                                'submenu' => [
                                    'Catálogos SAT' => [
                                        'route' => 'admin.import.catalogs-sat.index',
                                        'icon' => 'menu-icon tf-icons ti ti-library',
                                        'visible' => $this->canUserAccess('import.catalogs-sat.allow'),
                                    ],
                                ]
                            ],
                        ]
                    ],
                    env('APP_URL') => [
                        'url' => env('APP_URL'),
                        'icon' => 'menu-icon tf-icons ti ti-world-www',
                    ],
                    /*
                    'Exportar' => [
                        'icon' => 'menu-icon tf-icons ti ti-database-export',
                        'submenu' => [
                            'Catálogos SAT' => [
                                'route' => 'admin.export.customers.index',
                                'visible' => $this->canUserAccess('export.customers.allow'),
                            ],
                        ]
                    ],
                    */
                    'Acerca de' => [
                        'route' => 'admin.about.index',
                        'icon' => 'menu-icon tf-icons ti ti-cat',
                    ],
                ],
            ],

            'Recursos humanos' => [
                'icon' => 'menu-icon tf-icons ti ti-users-group',
                'submenu' => [
                    'Tablero' => [
                        'route' => 'admin.human-resources.dashboard.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-infographic',
                        'visible' => $this->canUserAccess('human-resources.dashboard.allow'),
                    ],
                    'Empleados' => [
                        'route' => 'admin.human-resources.employees.index',
                        'icon' => 'menu-icon tf-icons ti ti-id-badge-2',
                        'visible' => $this->canUserAccess('human-resources.employees.view'),
                    ],
                    'Puestos de trabajo' => [
                        'route' => 'admin.human-resources.jobs.index',
                        'icon' => 'menu-icon tf-icons ti ti-tie',
                        'visible' => $this->canUserAccess('human-resources.jobs.view'),
                    ],
                ]
            ],

            'Nómina' => [
                'icon' => 'menu-icon tf-icons ti ti-user-dollar',
                'submenu' => [
                    'Tablero' => [
                        'route' => 'admin.payrolls.dashboard.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-infographic',
                        'visible' => $this->canUserAccess('payrolls.dashboard.allow'),
                    ],
                    'Contratos' => [
                        'route' => 'admin.payrolls.contracts.index',
                        'icon' => 'menu-icon tf-icons ti ti-writing-sign',
                        'visible' => $this->canUserAccess('payrolls.contracts.view'),
                    ],
                    'Asistencias' => [
                        'route' => 'admin.payrolls.assistance.index',
                        'icon' => 'menu-icon tf-icons ti ti-calendar-exclamation',
                        'visible' => $this->canUserAccess('payrolls.assistance.view'),
                    ],
                    'CFDI Nómina' => [
                        'route' => 'admin.payrolls.billing.index',
                        'icon' => 'menu-icon tf-icons ti ti-file-certificate',
                        'visible' => $this->canUserAccess('billing.nomina.view'),
                    ],
                ]
            ],

            'Activos fijos' => [
                'icon' => 'menu-icon tf-icons ti ti-building',
                'submenu' => [
                    'Tablero' => [
                        'route' => 'admin.assets.dashboard.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-infographic',
                        'visible' => $this->canUserAccess('assets.dashboard.allow'),
                    ],
                    'Activos fijos' => [
                        'route' => 'admin.assets.assets.index',
                        'icon' => 'menu-icon tf-icons ti ti-building',
                        'visible' => $this->canUserAccess('assets.assets.view'),
                    ],
                    'Eventos relacionados' => [
                        'route' => 'admin.assets.events.index',
                        'icon' => 'menu-icon tf-icons ti ti-list-check',
                        'visible' => $this->canUserAccess('assets.events.view'),
                    ],
                ]
            ],

            'CRM' => [
                'icon' => 'menu-icon tf-icons ti ti-users',
                'submenu' => [
                    'Contactos' => [
                        'route' => 'admin.crm.contacts.index',
                        'icon' => 'menu-icon tf-icons ti ti-users',
                        'visible' => $this->canUserAccess('crm.contacts.view'),
                    ],
                    'Campañas de marketing' => [
                        'route' => 'admin.crm.marketing-campaigns.index',
                        'icon' => 'menu-icon tf-icons ti ti-ad-2',
                        'visible' => $this->canUserAccess('crm.marketing-campaigns.view'),
                    ],
                    'Oportunidades ' => [
                        'route' => 'admin.crm.leads.index',
                        'icon' => 'menu-icon tf-icons ti ti-target-arrow',
                        'visible' => $this->canUserAccess('crm.leads.view'),
                    ],
                    'Newsletter' => [
                        'route' => 'admin.crm.newsletter.index',
                        'icon' => 'menu-icon tf-icons ti ti-notebook',
                        'visible' => $this->canUserAccess('crm.newsletter.view'),
                    ],
                ]
            ],

            'Productos y servicios' => [
                'icon' => 'menu-icon tf-icons ti ti-package',
                'submenu' => [
                    'Categorias' => [
                        'route' => 'admin.products.categories.index',
                        'icon' => 'menu-icon tf-icons ti ti-category',
                        'visible' => $this->canUserAccess('products.categories.view'),
                    ],
                    'Catálogos' => [
                        'route' => 'admin.products.catalogs.index',
                        'icon' => 'menu-icon tf-icons ti ti-library',
                        'visible' => $this->canUserAccess('products.catalogs.view'),
                    ],
                    'Productos y servicios' => [
                        'route' => 'admin.products.products.index',
                        'icon' => 'menu-icon tf-icons ti ti-packages',
                        'visible' => $this->canUserAccess('products.products.view'),
                    ],
                    'Agregar producto o servicio' => [
                        'route' => 'admin.products.products.create',
                        'icon' => 'menu-icon tf-icons ti ti-package',
                        'visible' => $this->canUserAccess('products.products.create'),
                    ],
                ]
            ],

            'Compras y Gastos' => [
                'icon' => 'menu-icon tf-icons ti ti-receipt-2',
                'submenu' => [
                    'Tablero' => [
                        'route' => 'admin.purchases.dashboard.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-infographic',
                        'visible' => $this->canUserAccess('purchases.dashboard.allow'),
                    ],
                    'Proveedores' => [
                        'route' => 'admin.purchases.supplier.index',
                        'icon' => 'menu-icon tf-icons ti ti-truck',
                        'visible' => $this->canUserAccess('purchases.supplier.view'),
                    ],
                    'Ordenes de compra' => [
                        'icon' => 'menu-icon tf-icons ti ti-list-details',
                        'submenu' => [
                            'Nueva ordenes de compra' => [
                                'route' => 'admin.purchases.orders.create',
                                'icon' => 'menu-icon tf-icons ti ti-basket-check',
                                'visible' => $this->canUserAccess('purchases.orders.create'),
                            ],
                            'Ordenes de compra' => [
                                'route' => 'admin.purchases.orders.index',
                                'icon' => 'menu-icon tf-icons ti ti-basket-check',
                                'visible' => $this->canUserAccess('purchases.orders.view'),
                            ],
                            'Ordenes de compra por producto o servicio' => [
                                'route' => 'admin.purchases.orders-by-product.index',
                                'icon' => 'menu-icon tf-icons ti ti-basket-check',
                                'visible' => $this->canUserAccess('purchases.orders.view'),
                            ],
                        ]
                    ],
                    'Compras y gastos' => [
                        'icon' => 'menu-icon tf-icons ti ti-receipt-2',
                        'submenu' => [
                            'Nueva compras o gastos' => [
                                'route' => 'admin.purchases.purchases.create',
                                'icon' => 'menu-icon tf-icons ti ti-basket-dollar',
                                'visible' => $this->canUserAccess('purchases.purchases.create'),
                            ],
                            'Compras y gastos' => [
                                'route' => 'admin.purchases.purchases.index',
                                'icon' => 'menu-icon tf-icons ti ti-basket-dollar',
                                'visible' => $this->canUserAccess('purchases.purchases.view'),
                            ],
                            'Compras y gastos por producto o servicio' => [
                                'route' => 'admin.purchases.purchases-by-product.index',
                                'icon' => 'menu-icon tf-icons ti ti-basket-dollar',
                                'visible' => $this->canUserAccess('purchases.purchases.view'),
                            ],
                        ]
                    ],
                ]
            ],

            'Ventas' => [
                'icon' => 'menu-icon tf-icons ti ti-cash-register',
                'submenu' => [
                    'Tablero' => [
                        'route' => 'admin.pos.dashboard.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-infographic',
                        'visible' => $this->canUserAccess('pos.dashboard.allow'),
                    ],
                    'Clientes' => [
                        'route' => 'admin.pos.customers.index',
                        'icon' => 'menu-icon tf-icons ti ti-users-group',
                        'visible' => $this->canUserAccess('pos.customers.view'),
                    ],
                    'Lista de precios' => [
                        'route' => 'admin.pos.pricelist.index',
                        'icon' => 'menu-icon tf-icons ti ti-report-search',
                        'visible' => $this->canUserAccess('pos.sales.view'),
                    ],
                    'Cotizaciones' => [
                        'route' => 'admin.pos.quotes.index',
                        'icon' => 'menu-icon tf-icons ti ti-file-dollar',
                        'visible' => $this->canUserAccess('pos.quotes.view'),
                    ],
                    'Ventas' => [
                        'icon' => 'menu-icon tf-icons ti ti-cash-register',
                        'submenu' => [
                            'Crear venta' => [
                                'route' => 'admin.pos.sales.create',
                                'icon' => 'menu-icon tf-icons ti ti-cash-register',
                                'visible' => $this->canUserAccess('pos.sales.create'),
                            ],
                            'Ventas' => [
                                'route' => 'admin.pos.sales.index',
                                'icon' => 'menu-icon tf-icons ti ti-cash-register',
                                'visible' => $this->canUserAccess('pos.sales.view'),
                            ],
                            'Ventas por producto o servicio' => [
                                'route' => 'admin.pos.sales-by-product.index',
                                'icon' => 'menu-icon tf-icons ti ti-cash-register',
                                'visible' => $this->canUserAccess('pos.sales.view'),
                            ],
                        ]
                    ],
                    'Remisiones' => [
                        'icon' => 'menu-icon tf-icons ti ti-receipt',
                        'submenu' => [
                            'Crear remisión' => [
                                'route' => 'admin.pos.remissions.create',
                                'icon' => 'menu-icon tf-icons ti ti-receipt',
                                'visible' => $this->canUserAccess('pos.remissions.create'),
                            ],
                            'Remisiones' => [
                                'route' => 'admin.pos.remissions.index',
                                'icon' => 'menu-icon tf-icons ti ti-receipt',
                                'visible' => $this->canUserAccess('pos.remissions.view'),
                            ],
                            'Remisiones por producto o servicio' => [
                                'route' => 'admin.pos.remissions-by-product.index',
                                'icon' => 'menu-icon tf-icons ti ti-receipt',
                                'visible' => $this->canUserAccess('pos.remissions.view'),
                            ],
                        ]
                    ],
                    'Notas de crédito' => [
                        'icon' => 'menu-icon tf-icons ti ti-receipt-refund',
                        'submenu' => [
                            'Crear nota de crédito' => [
                                'route' => 'admin.pos.credit-notes.create',
                                'icon' => 'menu-icon tf-icons ti ti-receipt-refund',
                                'visible' => $this->canUserAccess('pos.credit-notes.create'),
                            ],
                            'Notas de créditos' => [
                                'route' => 'admin.pos.credit-notes.index',
                                'icon' => 'menu-icon tf-icons ti ti-receipt-refund',
                                'visible' => $this->canUserAccess('pos.credit-notes.view'),
                            ],
                            'Notas de crédito por producto o servicio' => [
                                'route' => 'admin.pos.credit-notes-by-product.index',
                                'icon' => 'menu-icon tf-icons ti ti-receipt-refund',
                                'visible' => $this->canUserAccess('pos.credit-notes.view'),
                            ],
                        ]
                    ],
                ]
            ],

            'Facturación' => [
                'icon' => 'menu-icon tf-icons ti ti-rubber-stamp',
                'submenu' => [
                    'Tablero' => [
                        'route' => 'admin.billing.dashboard.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-infographic',
                        'visible' => $this->canUserAccess('billing.dashboard.allow'),
                    ],
                    'Ingresos' => [
                        'icon' => 'menu-icon tf-icons ti ti-file-certificate',
                        'submenu' => [
                            'Facturar ventas' => [
                                'route' => 'admin.billing.ingresos-stamp.index',
                                'icon' => 'menu-icon tf-icons ti ti-rubber-stamp',
                                'visible' => $this->canUserAccess('billing.ingresos.create'),
                            ],
                            'CFDI Ingresos' => [
                                'route' => 'admin.billing.ingresos.index',
                                'icon' => 'menu-icon tf-icons ti ti-file-invoice',
                                'visible' => $this->canUserAccess('billing.ingresos.view'),
                            ],
                            'CFDI Ingresos por producto o servicio' => [
                                'route' => 'admin.billing.ingresos-by-product.index',
                                'icon' => 'menu-icon tf-icons ti ti-file-invoice',
                                'visible' => $this->canUserAccess('billing.ingresos.view'),
                            ],
                        ]
                    ],
                    'Egresos' => [
                        'icon' => 'menu-icon tf-icons ti ti-file-certificate',
                        'submenu' => [
                            'Facturar notas de crédito' => [
                                'route' => 'admin.billing.egresos-stamp.index',
                                'icon' => 'menu-icon tf-icons ti ti-rubber-stamp',
                                'visible' => $this->canUserAccess('billing.egresos.create'),
                            ],
                            'CFDI Engresos' => [
                                'route' => 'admin.billing.egresos.index',
                                'icon' => 'menu-icon tf-icons ti ti-file-invoice',
                                'visible' => $this->canUserAccess('billing.egresos.view'),
                            ],
                            'CFDI Engresos por producto o servicio' => [
                                'route' => 'admin.billing.egresos-by-product.index',
                                'icon' => 'menu-icon tf-icons ti ti-lisfile-invoicet',
                                'visible' => $this->canUserAccess('billing.egresos.view'),
                            ],
                        ]
                    ],
                    'Pagos' => [
                        'icon' => 'menu-icon tf-icons ti ti-file-certificate',
                        'submenu' => [
                            'Facturar pagos' => [
                                'route' => 'admin.billing.pagos-stamp.index',
                                'icon' => 'menu-icon tf-icons ti ti-rubber-stamp',
                                'visible' => $this->canUserAccess('billing.pagos.created'),
                            ],
                            'CFDI Pagos' => [
                                'route' => 'admin.billing.pagos.index',
                                'icon' => 'menu-icon tf-icons ti ti-file-invoice',
                                'visible' => $this->canUserAccess('billing.pagos.view'),
                            ],
                        ]
                    ],
                    'CFDI Nómina' => [
                        'route' => 'admin.billing.nomina.index',
                        'icon' => 'menu-icon tf-icons ti ti-file-certificate',
                        'visible' => $this->canUserAccess('billing.nomina.view'),
                    ],
                    'Verificador de CFDI 4.0' => [
                        'route' => 'admin.billing.verify-cfdi.index',
                        'icon' => 'menu-icon tf-icons ti ti-rosette-discount-check',
                        'visible' => $this->canUserAccess('billing.verify-cfdi.allow'),
                    ],
                ]
            ],

            'Finanzas' => [
                'icon' => 'menu-icon tf-icons ti ti-coins',
                'submenu' => [
                    'Tablero' => [
                        'route' => 'admin.finance.dashboard.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-infographic',
                        'visible' => $this->canUserAccess('finance.dashboard.allow'),
                    ],
                    'Catálogos de cuentas contables' => [
                        'route' => 'admin.finance.accounting-charts.index',
                        'icon' => 'menu-icon tf-icons ti ti-chart-histogram',
                        'visible' => $this->canUserAccess('finance.accounting-charts.view'),
                    ],
                    'Cuentas por pagar' => [
                        'route' => 'admin.finance.accounts-payable.index',
                        'icon' => 'menu-icon tf-icons ti ti-businessplan',
                        'visible' => $this->canUserAccess('finance.accounts-payable.view'),
                    ],
                    'Cuentas por cobrar' => [
                        'route' => 'admin.finance.accounts-receivable.index',
                        'icon' => 'menu-icon tf-icons ti ti-cash-register',
                        'visible' => $this->canUserAccess('finance.accounts-receivable.view'),
                    ],
                ]
            ],

            'Sitio Web' => [
                'icon' => 'menu-icon tf-icons ti ti-wand',
                'submenu' => [
                    'Slider' => [
                        'route' => 'admin.website.slider.index',
                        'icon' => 'menu-icon tf-icons ti ti-table-row',
                        'visible' => $this->canUserAccess('website.slider.view'),
                    ],
                    'Concierge Magazine' => [
                        'route' => 'admin.website.cmagazine.index',
                        'icon' => 'menu-icon tf-icons ti ti-book',
                        'visible' => $this->canUserAccess('website.cmagazine.view'),
                    ],
                    'Preguntas frecuentes' => [
                        'route' => 'admin.website.faq.index',
                        'icon' => 'menu-icon tf-icons ti ti-bubble-text',
                        'visible' => $this->canUserAccess('website.faq.view'),
                    ],
                ]
            ],

            'Blog' => [
                'icon' => 'menu-icon tf-icons ti ti-news',
                'submenu' => [
                    'Categorias' => [
                        'route' => 'admin.blog.categories.index',
                        'icon' => 'menu-icon tf-icons ti ti-category',
                        'visible' => $this->canUserAccess('blog.categories.view'),
                    ],
                    'Etiquetas' => [
                        'route' => 'admin.blog.tags.index',
                        'icon' => 'menu-icon tf-icons ti ti-tags',
                        'visible' => $this->canUserAccess('blog.tags.view'),
                    ],
                    'Articulos' => [
                        'route' => 'admin.blog.articles.index',
                        'icon' => 'menu-icon tf-icons ti ti-news',
                        'visible' => $this->canUserAccess('blog.articles.view'),
                    ],
                    'Comentarios' => [
                        'route' => 'admin.blog.comments.index',
                        'icon' => 'menu-icon tf-icons ti ti-message',
                        'visible' => $this->canUserAccess('blog.comments.view'),
                    ],
                ]
            ],

            'Iniciar sesión' => [
                'route' => 'login',
                'icon' => 'menu-icon tf-icons ti ti-login',
                'visible' => $this->user === null,
            ],

            'Recuperar contraseña' => [
                'route' => 'password.request',
                'icon' => 'menu-icon tf-icons ti ti-key',
                'visible' => !$this->user === null,
            ],
        ];
    }

    private function canUserAccess($permission)
    {
        return $this->user && $this->user->can($permission);
    }
}
