{{-- Imports --}}
@php
    use App\Helpers\Environment\FacturapiHelper;
    use App\Helpers\Environment\SystemModulesHelper;
    use App\Helpers\Environment\SystemEnvHelper;
    use \App\Helpers\Environment\SystemFeaturesHelper;
@endphp

{{-- Content --}}
@auth
    {{-- General Variables --}}
    @php
        //* Control Variables
            $role = Auth::user()->role;
            $modules = [
                'audits'            => SystemModulesHelper::getModuleStatus('audits'),
                'restaurant'        => SystemModulesHelper::getModuleStatus('restaurant'),
                'invoicing'         => SystemEnvHelper::areCurrentCountries(['MEX']) && SystemModulesHelper::isEstablishmentTaxDataComplete() && FacturapiHelper::isEnabled(),
                'otas_connection'   => SystemModulesHelper::getModuleStatus('otas_connection'),
            ];

            $has_only_invoicing_system = SystemFeaturesHelper::getFeatureStatus('only_invoicing_system');

        //* Data to Render
            $sidebar_items = [
                // Hotel Modules
                [
                    'title'   => __('modules')['dashboard']['hotel']['title'],
                    'roles'   => ['administrador','gerente','recepcionista'],
                    'display' => !$has_only_invoicing_system,
                    'children'=> [
                      // Admin
                        ['title'=>__('modules')['dashboard']['hotel']['seasons'], 'icon'=>'season_blue.svg', 'route'=>'seasons.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['hotel']['room_groups'], 'icon'=>'layers.svg', 'route'=>'room-groups.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['hotel']['room_types'], 'icon'=>'double_bed_blue.svg', 'route'=>'room-types.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['hotel']['rooms'], 'icon'=>'single_bed_blue.svg', 'route'=>'rooms.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['hotel']['agencies'], 'icon'=>'agency_blue.svg', 'route'=>'agencies.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['hotel']['reservation_sources'], 'icon'=>'source.svg', 'route'=>'sources.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['hotel']['regimens'], 'icon'=>'regiment.svg', 'route'=>'regimens.index', 'roles'=>['administrador']],

                      // Shared
                        ['title'=>__('modules')['dashboard']['hotel']['clients'], 'icon'=>'traveling_blue.svg', 'route'=>'clients.index'],
                        [
                            'title'   => __('modules')['dashboard']['hotel']['reservations'],
                            'icon'    => 'checkIn_blue.svg',
                            'children'=> [
                                ['title'=>__('modules')['dashboard']['hotel']['reservation_tickets'], 'icon'=>'file_blue.svg', 'route'=>'reservation.tickets.fullStays'],
                                ['title'=>__('modules')['dashboard']['hotel']['consumption_tickets'], 'icon'=>'ticket_blue.svg', 'route'=>'reservation.tickets.hotelConsumptions'],
                            ]
                        ],

                      // Admin-Manager
                        ['title'=>__('modules')['dashboard']['hotel']['reports'], 'icon'=>'paper_blue.svg', 'route'=>'hotel.reports', 'roles'=>['administrador','gerente']],
                    ]
                ],

                // Restaurant Modules
                [
                    'title'   => __('modules')['dashboard']['restaurant']['title'],
                    'roles'   => ['administrador','gerente','recepcionista'],
                    'module'  => 'restaurant', // Only shows if module is enabled
                    'display' => !$has_only_invoicing_system,
                    'children'=> [
                        ['title'=>__('modules')['dashboard']['restaurant']['tables'], 'icon'=>'table_blue.svg', 'route'=>'tables.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['restaurant']['categories'], 'icon'=>'category_blue.svg', 'route'=>'product-categories.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['restaurant']['products'], 'icon'=>'plate_blue.svg', 'route'=>'products.index', 'roles'=>['administrador']],
                        ['title'=>__('modules')['dashboard']['restaurant']['orders'], 'icon'=>'orden_blue.svg', 'route'=>'orders.index'],
                        ['title'=>__('modules')['dashboard']['restaurant']['reports'], 'icon'=>'paper_blue.svg', 'route'=>'restaurant.reports'],
                    ]
                ],

                // Invoicing Modules
                [
                    'title'   => __('modules')['dashboard']['invoicing']['title'],
                    'roles'   => ['administrador','gerente','recepcionista'],
                    'module'  => 'invoicing', // Only shows if module is available on configured country
                    'children'=> [
                      // Shared
                        ['title'=>__('modules')['dashboard']['invoicing']['invoices'], 'icon'=>'invoice_blue.svg', 'route'=>'invoices.index'],
                        ['title'=>__('modules')['dashboard']['invoicing']['branches'], 'icon'=>'small_hotel_blue.svg', 'route'=>'tax-branches.index', 'roles'=>['administrador', 'gerente']],
                        ['title'=>__('modules')['dashboard']['invoicing']['tax_clients'], 'icon'=>'traveling_blue.svg', 'route'=>'tax-clients.index'],
                        ['title'=>__('modules')['dashboard']['invoicing']['prod_servs'], 'icon'=>'cube_blue.svg', 'route'=>'tax-prod-servs.index', 'roles'=>['administrador', 'gerente']],
                        ['title'=>__('modules')['dashboard']['invoicing']['formats_descriptive'], 'icon'=>'file_stack_blue.svg', 'route'=>'tax-formats.index', 'roles'=>['administrador', 'gerente']],
                    ]
                ],

                // Settings Modules
                [
                    'title'   => __('modules')['dashboard']['settings']['title'],
                    'roles'   => ['administrador','gerente'],
                    'children'=> [
                        ['title'=>__('modules')['dashboard']['settings']['audits'], 'icon'=>'missing_payment_blue.svg', 'route'=>'audits.index', 'module'=>'audits', 'display' => !$has_only_invoicing_system],
                        ['title'=>__('modules')['dashboard']['settings']['otas_connection'], 'icon'=>'api_agency_blue.svg', 'route'=>'otas.index', 'module'=>'otas_connection', 'display' => !$has_only_invoicing_system],
                        ['title'=>__('modules')['dashboard']['settings']['users'], 'icon'=>'user.svg', 'route'=>'users.index'],
                        ['title'=>__('modules')['dashboard']['settings']['establishments'], 'icon'=>'hotel_blue.svg', 'route'=>'establishments.index', 'roles'=>['administrador']],
                    ]
                ],
            ];

        //* Render Helper
            $canShow = function(array $item, string $role, array $modules): bool {
                if (isset($item['roles']) && !in_array($role, $item['roles'])) return false;
                if (isset($item['module']) && empty($modules[$item['module']] ?? false)) return false;
                if (array_key_exists('display', $item) && !$item['display']) return false;

                return true;
            };
    @endphp

    {{-- Route Helper --}}
    @php
        // ¿Coincide la ruta actual?
        $isRoute = function ($route) {
            return isset($route) && request()->routeIs($route);
        };

        // Recursivo: ¿este item o alguno de sus hijos está activo?
        $isItemActive = null;
        $isItemActive = function (array $item) use (&$isItemActive, $isRoute): bool {
            if (isset($item['route']) && $isRoute($item['route'])) return true;

            if (!empty($item['children'])) {
                foreach ($item['children'] as $child) {
                    if ($isItemActive($child)) return true;
                }
            }
            return false;
        };
    @endphp

    {{-- Sidebar Structure --}}
    <div class="p-0 mb-5 col-lg-3 col-md-4 col-sm-3 d-flex flex-column align-items-center">
        <div class="harsi-sidebar navbar navbar-expand-md flex-column align-items-center">
            <div class="nav navbar-inverse" style="letter-spacing: 1px;">
                <div class="nav-item">

                    {{-- Logo --}}
                    <a class="mt-2 btn d-flex justify-content-center" href="{{ route('home.index') }}">
                        <img class="logo-menu" src="{{ asset('images/only_harsi.png') }}" alt="Menu Item">
                    </a>

                    {{-- Options --}}
                    <nav class="mt-3 menu">
                        <ul class="alinear">
                            @foreach($sidebar_items as $item)
                                @if($canShow($item, $role, $modules))

                                    <li class="{{ empty($item['children']) ? '' : 'opcion' }} {{ $isItemActive($item) ? 'is-open' : '' }}">

                                        {{-- Modules --}}
                                        <a
                                            href="{{ $item['route'] ?? '#' }}"
                                            class="{{ empty($item['children']) ? '' : 'principal' }} {{ (isset($item['route']) && request()->routeIs($item['route'])) ? 'is-active' : '' }}"
                                        >
                                            {{ $item['title'] ?? '' }}

                                            @if(!empty($item['children']))
                                                <i class="icono">
                                                    <img class="menu-icon" src="{{ asset('icons/arrow.svg') }}" alt="Menu Item">
                                                </i>
                                            @endif
                                        </a>

                                        {{-- Module Features --}}
                                        @if(!empty($item['children']))
                                            <ul class="submenu menu2 {{ $isItemActive($item) ? 'activo' : '' }}">
                                                @foreach($item['children'] as $child)

                                                    @if(!empty($child['children']))

                                                        {{-- Secondary Parent Link --}}
                                                        @php $childOpen = $isItemActive($child); @endphp
                                                        <li class="{{ $childOpen ? 'is-open' : '' }}">
                                                            <a href="#">
                                                                @isset($child['icon'])
                                                                    <img class="icon-opcion" src="{{ asset('icons/' . $child['icon']) }}" alt="Menu Item">&nbsp;
                                                                @endisset
                                                                {{ $child['title'] ?? '' }}

                                                                <i class="icono"><img class="menu-icon2" src="{{ asset('icons/arrow.svg') }}" alt="Menu Item"></i>
                                                            </a>

                                                            <ul class="submenu2 {{ $childOpen ? 'activo' : '' }}">
                                                                @foreach($child['children'] as $grand)

                                                                    @if($canShow($grand, $role, $modules))
                                                                        <li>
                                                                            <a
                                                                                href="{{ isset($grand['route']) ? route($grand['route']) : '#' }}"
                                                                                class="{{ (isset($grand['route']) && request()->routeIs($grand['route'])) ? 'is-active' : '' }}"
                                                                            >
                                                                                @isset($grand['icon'])
                                                                                    <img class="icon-opcion" src="{{ asset('icons/' . $grand['icon']) }}" alt="Menu Item">&nbsp;
                                                                                @endisset
                                                                                {{ $grand['title'] ?? '' }}
                                                                            </a>
                                                                        </li>
                                                                    @endif

                                                                @endforeach
                                                            </ul>
                                                        </li>

                                                    @else
                                                        {{-- Simple Link --}}
                                                        @if($canShow($child, $role, $modules))
                                                            <li>
                                                                <a
                                                                    href="{{ isset($child['route']) ? route($child['route']) : '#' }}"
                                                                    class="{{ (isset($child['route']) && request()->routeIs($child['route'])) ? 'is-active' : '' }}"
                                                                >
                                                                    @isset($child['icon'])
                                                                        <img class="icon-opcion" src="{{ asset('icons/' . $child['icon']) }}" alt="Menu Item">&nbsp;
                                                                    @endisset
                                                                    {{ $child['title'] ?? '' }}
                                                                </a>
                                                            </li>
                                                        @endif
                                                    @endif

                                                @endforeach
                                            </ul>
                                        @endif
                                    </li>

                                @endif
                            @endforeach
                        </ul>
                    </nav>

                </div>
            </div >
        </div>
    </div>
@endauth

{{--* Scripts *--}}
    {{-- Menus Control --}}
    <script>
        $(document).ready(function () {
            function toggleMenu($trigger, submenuSelector, iconSelector) {
                const $submenu = $trigger.siblings(submenuSelector);
                const $arrow = $trigger.find(iconSelector);

                if ($submenu.length) {
                    $submenu.toggleClass('activo');

                    const deg = $submenu.hasClass('activo') ? '90deg' : '0deg';
                    $arrow.css({ transform: `rotate(${deg})`, transition: '0.3s' });
                }
            }

            // Estado inicial: abrir los que vienen marcados por Blade
            $('.opcion.is-open').each(function () {
                $(this).children('.submenu, .menu2').addClass('activo');
                $(this).find('> a .menu-icon').css({ transform: 'rotate(90deg)' });
            });
            $('.submenu2.activo').each(function () {
                $(this).closest('li').find('> a .menu-icon2').css({ transform: 'rotate(90deg)' });
            });

            // Menú principal
            $('.opcion > a.principal').on('click', function (e) {
                e.preventDefault();
                toggleMenu($(this), '.submenu, .menu2', '.menu-icon');
            });

            // Submenús anidados
            $('.submenu > li > a, .menu2 > li > a').on('click', function (e) {
                if ($(this).siblings('.submenu2').length) {
                    e.preventDefault();
                    toggleMenu($(this), '.submenu2', '.menu-icon2');
                }
            });
        });
    </script>
