<?php
// partials/menu.php — Menú lateral (Bootstrap 5 + Font Awesome 6)
// Requiere: bootstrap.min.css, bootstrap.bundle.min.js y Font Awesome 6.
if (session_status() === PHP_SESSION_NONE) { session_start(); }

$permiso     = isset($_SESSION['permiso']) ? (int)$_SESSION['permiso'] : 0;
$currentPage = basename(parse_url($_SERVER['REQUEST_URI'] ?? 'index.php', PHP_URL_PATH));

/* ===== Helpers ===== */
function isActive(string $file, string $current): bool { return $current === $file; }

function navClasses(string $file, string $current, string $mode = 'light'): string {
  $is = isActive($file, $current);
  $base = 'nav-link px-0 d-flex align-items-center gap-2 rounded-1';
  $active = $is ? ' fw-bold link-primary active-link' : '';
  if ($mode === 'dark') return $base . ($is ? ' text-warning fw-bold active-link-dark' : ' text-light');
  return $base . ($is ? ' text-primary' : ' text-dark');
}
function ariaCurrent(string $file, string $current): string {
  return isActive($file, $current) ? 'aria-current="page"' : '';
}
function navItem(string $href, string $label, string $icon, string $file, string $current, string $mode = 'light'): string {
  $classes = navClasses($file, $current, $mode);
  $ico = htmlspecialchars($icon, ENT_QUOTES, 'UTF-8');
  $lbl = htmlspecialchars($label, ENT_QUOTES, 'UTF-8');
  $hrf = htmlspecialchars($href, ENT_QUOTES, 'UTF-8');
  $aria = ariaCurrent($file, $current);
  return "<li class=\"nav-item\"><a class=\"{$classes}\" href=\"{$hrf}\" {$aria}><i class=\"fa-solid {$ico}\"></i><span>{$lbl}</span></a></li>";
}

/**
 * anyMatchDeep: encuentra coincidencias por 'file' en arreglos simples o anidados
 * Ej: anyMatchDeep($sections['inventario'], $currentPage) -> true/false
 */
function anyMatchDeep(array $items, string $current): bool {
  foreach ($items as $it) {
    if (is_array($it)) {
      if (isset($it['file']) && $it['file'] === $current) return true;
      // Soporta niveles anidados (por ejemplo: Bodegas -> Quito/Guayaquil/Manta)
      foreach ($it as $sub) {
        if (is_array($sub) && anyMatchDeep($sub, $current)) return true;
      }
    }
  }
  return false;
}

function filesOf(array $items): array { return array_column($items, 'file'); }

/* ===== Datos de navegación ===== */
$sections = [
  'bodegas' => [
    'Quito' => [
      ['href'=>'../../views/pages/dapPatioQuito.php','label'=>'DAP','icon'=>'fa-truck','file'=>'dapPatioQuito.php'],
      ['href'=>'../../views/pages/simplePatioQuito.php','label'=>'Simple','icon'=>'fa-car','file'=>'simplePatioQuito.php'],
      ['href'=>'../../views/pages/plano_q.php','label'=>'Croquis DAP','icon'=>'fa-map-location-dot','file'=>'plano_q.php'],
    ],
    'Guayaquil' => [
      ['href'=>'../../views/pages/dapPatioGuayaquil.php','label'=>'DAP','icon'=>'fa-truck','file'=>'dapPatioGuayaquil.php'],
      ['href'=>'../../views/pages/simplePatioGuayaquil.php','label'=>'Simple','icon'=>'fa-car','file'=>'simplePatioGuayaquil.php'],
      ['href'=>'../../views/pages/plano_g.php','label'=>'Croquis Simple','icon'=>'fa-map-location-dot','file'=>'plano_g.php'],
    ],
    'Manta' => [
      ['href'=>'../../views/pages/dapPatioManta.php','label'=>'DAP','icon'=>'fa-truck','file'=>'dapPatioManta.php'],
      ['href'=>'../../views/pages/simplePatioManta.php','label'=>'Simple','icon'=>'fa-car','file'=>'simplePatioManta.php'],
    ],
  ],
  'clientes' => [
    ['href'=>'empresa.php','label'=>'Empresa','icon'=>'fa-building','file'=>'empresa.php'],
  ],
  'registro_previo' => [
    ['href'=>'dai_simple.php','label'=>'Simple','icon'=>'fa-car-side','file'=>'dai_simple.php'],
    ['href'=>'solicitud_previa.php','label'=>'DAP','icon'=>'fa-circle-dot','file'=>'solicitud_previa.php'],
  ],
  'movilizacion' => [
    ['href'=>'asignar.php','label'=>'Asignar Unidades','icon'=>'fa-circle-dot','file'=>'asignar.php'],
    ['href'=>'programar.php','label'=>'Programar Unidades','icon'=>'fa-truck','file'=>'programar.php'],
  ],
  'dap' => [
    ['href'=>'dai70.php','label'=>'DAI 70 - Guía y Tarja','icon'=>'fa-file-lines','file'=>'dai70.php'],
    ['href'=>'facturainformativa.php','label'=>'Factura Informativa','icon'=>'fa-file-invoice','file'=>'facturainformativa.php'],
    ['href'=>'nacionalizacion.php','label'=>'Nacionalización','icon'=>'fa-passport','file'=>'nacionalizacion.php'],
    ['href'=>'directa.php','label'=>'Nacionalización Directa','icon'=>'fa-right-to-bracket','file'=>'directa.php'],
    ['href'=>'nacionalizados.php','label'=>'DAI 10 - Nacionalizados','icon'=>'fa-box-archive','file'=>'nacionalizados.php'],
  ],
  'operaciones' => [
    ['href'=>'inventario.php','label'=>'Inventario','icon'=>'fa-car','file'=>'inventario.php'],
    ['href'=>'bateria.php','label'=>'Mediciones de Batería','icon'=>'fa-car-battery','file'=>'bateria.php'],
    ['href'=>'impronta.php','label'=>'Impronta','icon'=>'fa-fingerprint','file'=>'impronta.php'],
    ['href'=>'mantenimiento.php','label'=>'Mantenimiento','icon'=>'fa-screwdriver-wrench','file'=>'mantenimiento.php'],
  ],
  'pdi' => [
    ['href'=>'alistamiento_pdi.php','label'=>'Alistamiento PDI','icon'=>'fa-clipboard-check','file'=>'alistamiento_pdi.php'],
    ['href'=>'generar_qr.php','label'=>'Generar QR','icon'=>'fa-note-sticky','file'=>'generar_qr.php'],
  ],
  'reparacion' => [
    ['href'=>'reparacion.php','label'=>'Solicitud','icon'=>'fa-clipboard-list','file'=>'reparacion.php'],
  ],
  'accesorizacion' => [
    // Si tu archivo real es accesorizacion.php, cámbialo aquí.
    ['href'=>'accerizacion.php','label'=>'Solicitud','icon'=>'fa-clipboard-list','file'=>'accerizacion.php'],
  ],
  'inventario' => [
    ['href'=>'accesorio_ingreso.php','label'=>'Ingreso','icon'=>'fa-clipboard-list','file'=>'accesorio_ingreso.php'],
    ['href'=>'inventario_egreso.php','label'=>'Egreso','icon'=>'fa-clipboard-list','file'=>'inventario_egreso.php'],
    ['href'=>'categorias.php','label'=>'Categoria','icon'=>'fa-clipboard-list','file'=>'categorias.php'],
    ['href'=>'marcas.php','label'=>'Marcas','icon'=>'fa-clipboard-list','file'=>'marcas.php'],
    ['href'=>'modelos.php','label'=>'Modelo','icon'=>'fa-clipboard-list','file'=>'modelos.php'],
    ['href'=>'bodegas.php','label'=>'Almacen','icon'=>'fa-clipboard-list','file'=>'bodegas.php'],
    ['href'=>'accesorios.php','label'=>'Accesorios','icon'=>'fa-clipboard-list','file'=>'accesorios.php'],
    ['href'=>'partes.php','label'=>'Partes','icon'=>'fa-clipboard-list','file'=>'partes.php'],
    ['href'=>'movimientos.php','label'=>'Movimientos','icon'=>'fa-clipboard-list','file'=>'movimientos.php'],
  ],
  'recepcion' => [
    ['href'=>'recibe_conforme.php','label'=>'Recibe Conforme','icon'=>'fa-file-signature','file'=>'recibe_conforme.php'],
  ],
  'adicionales' => [
    ['href'=>'adicionales.php','label'=>'Solicitud','icon'=>'fa-clipboard-list','file'=>'adicionales.php'],
  ],
  'despacho' => [
    ['href'=>'despacho.php','label'=>'Registro','icon'=>'fa-pen-to-square','file'=>'despacho.php'],
  ],
  'reportes' => [
   
    ['href'=>'i_general.php','label'=>'Inventario','icon'=>'fa-warehouse','file'=>'i_general.php'],
    ['href'=>'trazabilidad.php','label'=>'Trazabilidad','icon'=>'fa-route','file'=>'trazabilidad.php'],
    ['href'=>'repor_novedad.php','label'=>'Reporte de Novedades','icon'=>'fa-note-sticky','file'=>'repor_novedad.php'],
    ['href'=>'finalizados.php','label'=>'Finalizados','icon'=>'fa-clipboard-check','file'=>'finalizados.php'],
  ],
  'admin' => [
    ['href'=>'usuario.php','label'=>'Usuarios','icon'=>'fa-users-gear','file'=>'usuario.php', 'mode'=>'dark'],
    ['href'=>'usuario_fi.php','label'=>'Factura Informativa','icon'=>'fa-file-pen','file'=>'usuario_fi.php', 'mode'=>'dark'],
    ['href'=>'usuario_guia.php','label'=>'Guía Entrada/Salida','icon'=>'fa-id-card','file'=>'usuario_guia.php', 'mode'=>'dark'],
  ],
];

/* ===== Flags de apertura automática ===== */
$inQuito = in_array($currentPage, filesOf($sections['bodegas']['Quito']), true);
$inGye   = in_array($currentPage, filesOf($sections['bodegas']['Guayaquil']), true);
$inManta = in_array($currentPage, filesOf($sections['bodegas']['Manta']), true);
$showBod = $inQuito || $inGye || $inManta;

$showClientes = anyMatchDeep($sections['clientes'], $currentPage);
$showRegPrev  = anyMatchDeep($sections['registro_previo'], $currentPage);
$showMovil    = anyMatchDeep($sections['movilizacion'], $currentPage);
$showDAP      = anyMatchDeep($sections['dap'], $currentPage);
$showOps      = anyMatchDeep($sections['operaciones'], $currentPage);
$showPDI      = anyMatchDeep($sections['pdi'], $currentPage);
$showRep      = anyMatchDeep($sections['reparacion'], $currentPage);
$showAcce     = anyMatchDeep($sections['accesorizacion'], $currentPage);
$showInv      = anyMatchDeep($sections['inventario'], $currentPage);
$showRecep    = anyMatchDeep($sections['recepcion'], $currentPage);
$showAdic     = anyMatchDeep($sections['adicionales'], $currentPage);
$showDesp     = anyMatchDeep($sections['despacho'], $currentPage);
$showReport   = anyMatchDeep($sections['reportes'], $currentPage);
$showAdmin    = anyMatchDeep($sections['admin'], $currentPage);
?>

<style>
  /* Mejoras visuales para el link activo */
  #sidebarMenu .active-link { position: relative; }
  #sidebarMenu .active-link::before{
    content:"";
    position:absolute; left:-8px; top:6px; bottom:6px;
    width:3px; border-radius:3px; background: currentColor;
  }
  #sidebarMenu .active-link-dark::before{ background:#ffc107; } /* warning */
</style>

<nav class="col-md-3 col-lg-2 d-md-block bg-secondary-subtle text-dark sidebar collapse offcanvas-md offcanvas-start"
     id="sidebarMenu" style="font-size:1rem;" aria-label="Menú lateral de navegación">
  <div class="position-sticky overflow-auto px-2 pt-2">
    <div class="accordion" id="menuAccordion" data-remember="menuAccordion">

      <!-- Principal -->
      <div class="mb-2">
        <ul class="nav flex-column gap-1 px-2">
          <?= navItem('index.php','Inicio','fa-house','index.php',$currentPage); ?>
        </ul>
      </div>

      <?php if (in_array($permiso, [2,777], true)): ?>

      <!-- BODEGAS -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-bodegas">
        <h2 class="accordion-header" id="hdrBodegas">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showBod ? '' : 'collapsed' ?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colBodegas"
                  aria-expanded="<?= $showBod ? 'true':'false' ?>" aria-controls="colBodegas">
            <i class="fa-solid fa-warehouse me-2"></i>Bodegas
          </button>
        </h2>
        <div id="colBodegas" class="accordion-collapse collapse <?= $showBod ? 'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colBodegas">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <div class="accordion accordion-flush" id="accBodegas" data-remember="accBodegas">

              <!-- Quito -->
              <div class="accordion-item" id="sec-bod-quito">
                <h2 class="accordion-header" id="hdrBodQuito">
                  <button class="accordion-button <?= $inQuito ? '' : 'collapsed' ?> py-2 bg-secondary-subtle text-dark" type="button"
                          data-bs-toggle="collapse" data-bs-target="#colBodQuito"
                          aria-expanded="<?= $inQuito ? 'true':'false' ?>" aria-controls="colBodQuito">
                    <i class="fa-solid fa-city me-2"></i>Quito
                  </button>
                </h2>
                <div id="colBodQuito" class="accordion-collapse collapse <?= $inQuito ? 'show':'' ?>"
                     data-bs-parent="#accBodegas" data-remember="colBodQuito">
                  <div class="accordion-body py-2 bg-secondary-subtle">
                    <ul class="nav flex-column gap-1">
                      <?php foreach ($sections['bodegas']['Quito'] as $it): ?>
                        <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
                      <?php endforeach; ?>
                    </ul>
                  </div>
                </div>
              </div>

              <!-- Guayaquil -->
              <div class="accordion-item" id="sec-bod-gye">
                <h2 class="accordion-header" id="hdrBodGye">
                  <button class="accordion-button <?= $inGye ? '' : 'collapsed' ?> py-2 bg-secondary-subtle text-dark" type="button"
                          data-bs-toggle="collapse" data-bs-target="#colBodGye"
                          aria-expanded="<?= $inGye ? 'true':'false' ?>" aria-controls="colBodGye">
                    <i class="fa-solid fa-city me-2"></i>Guayaquil
                  </button>
                </h2>
                <div id="colBodGye" class="accordion-collapse collapse <?= $inGye ? 'show':'' ?>"
                     data-bs-parent="#accBodegas" data-remember="colBodGye">
                  <div class="accordion-body py-2 bg-secondary-subtle">
                    <ul class="nav flex-column gap-1">
                      <?php foreach ($sections['bodegas']['Guayaquil'] as $it): ?>
                        <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
                      <?php endforeach; ?>
                    </ul>
                  </div>
                </div>
              </div>

              <!-- Manta -->
              <div class="accordion-item" id="sec-bod-manta">
                <h2 class="accordion-header" id="hdrBodManta">
                  <button class="accordion-button <?= $inManta ? '' : 'collapsed' ?> py-2 bg-secondary-subtle text-dark" type="button"
                          data-bs-toggle="collapse" data-bs-target="#colBodManta"
                          aria-expanded="<?= $inManta ? 'true':'false' ?>" aria-controls="colBodManta">
                    <i class="fa-solid fa-city me-2"></i>Manta
                  </button>
                </h2>
                <div id="colBodManta" class="accordion-collapse collapse <?= $inManta ? 'show':'' ?>"
                     data-bs-parent="#accBodegas" data-remember="colBodManta">
                  <div class="accordion-body py-2 bg-secondary-subtle">
                    <ul class="nav flex-column gap-1">
                      <?php foreach ($sections['bodegas']['Manta'] as $it): ?>
                        <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
                      <?php endforeach; ?>
                    </ul>
                  </div>
                </div>
              </div>

            </div><!-- /accBodegas -->
          </div>
        </div>
      </div>

      <!-- CLIENTES -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-clientes">
        <h2 class="accordion-header" id="hdrClientes">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showClientes ? '' : 'collapsed' ?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colClientes"
                  aria-expanded="<?= $showClientes ? 'true' : 'false' ?>" aria-controls="colClientes">
            <i class="fa-solid fa-users me-2"></i>Clientes
          </button>
        </h2>
        <div id="colClientes" class="accordion-collapse collapse <?= $showClientes ? 'show' : '' ?>"
             data-bs-parent="#menuAccordion" data-remember="colClientes">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['clientes'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- REGISTRO PREVIO -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-regprev">
        <h2 class="accordion-header" id="hdrRegPrev">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showRegPrev ? '' : 'collapsed' ?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colRegPrev"
                  aria-expanded="<?= $showRegPrev ? 'true' : 'false' ?>" aria-controls="colRegPrev">
            <i class="fa-solid fa-truck-fast me-2"></i>Registro previo
          </button>
        </h2>
        <div id="colRegPrev" class="accordion-collapse collapse <?= $showRegPrev ? 'show' : '' ?>"
             data-bs-parent="#menuAccordion" data-remember="colRegPrev">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['registro_previo'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- MOVILIZACIÓN -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-movil">
        <h2 class="accordion-header" id="hdrMovil">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showMovil ? '' : 'collapsed' ?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colMovil"
                  aria-expanded="<?= $showMovil ? 'true' : 'false' ?>" aria-controls="colMovil">
            <i class="fa-solid fa-car-side me-2"></i>Movilización
          </button>
        </h2>
        <div id="colMovil" class="accordion-collapse collapse <?= $showMovil ? 'show' : '' ?>"
             data-bs-parent="#menuAccordion" data-remember="colMovil">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['movilizacion'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- DAP -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-dap">
        <h2 class="accordion-header" id="hdrDAP">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showDAP?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colDAP"
                  aria-expanded="<?= $showDAP?'true':'false'?>" aria-controls="colDAP">
            <i class="fa-solid fa-list-check me-2"></i>DAP
          </button>
        </h2>
        <div id="colDAP" class="accordion-collapse collapse <?= $showDAP?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colDAP">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['dap'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- OPERACIONES LOGÍSTICAS -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-ops">
        <h2 class="accordion-header" id="hdrOps">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showOps?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colOps"
                  aria-expanded="<?= $showOps?'true':'false'?>" aria-controls="colOps">
            <i class="fa-solid fa-gears me-2"></i>Operaciones logísticas
          </button>
        </h2>
        <div id="colOps" class="accordion-collapse collapse <?= $showOps?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colOps">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['operaciones'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- PDI -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-pdi">
        <h2 class="accordion-header" id="hdrPDI">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showPDI?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colPDI"
                  aria-expanded="<?= $showPDI?'true':'false'?>" aria-controls="colPDI">
            <i class="fa-solid fa-clipboard-check me-2"></i>PDI
          </button>
        </h2>
        <div id="colPDI" class="accordion-collapse collapse <?= $showPDI?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colPDI">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['pdi'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- REPARACIÓN -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-rep">
        <h2 class="accordion-header" id="hdrRep">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showRep?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colRep"
                  aria-expanded="<?= $showRep?'true':'false'?>" aria-controls="colRep">
            <i class="fa-solid fa-screwdriver-wrench me-2"></i>Reparación
          </button>
        </h2>
        <div id="colRep" class="accordion-collapse collapse <?= $showRep?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colRep">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['reparacion'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- ACCESORIZACIÓN -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-acce">
        <h2 class="accordion-header" id="hdrAcce">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showAcce?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colAcce"
                  aria-expanded="<?= $showAcce?'true':'false'?>" aria-controls="colAcce">
            <i class="fa-solid fa-toolbox me-2"></i>Accesorización
          </button>
        </h2>
        <div id="colAcce" class="accordion-collapse collapse <?= $showAcce?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colAcce">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['accesorizacion'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- INVENTARIO (ALMACEN) -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-inv">
        <h2 class="accordion-header" id="hdrInv">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showInv?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colInv"
                  aria-expanded="<?= $showInv?'true':'false'?>" aria-controls="colInv">
            <i class="fa-solid fa-boxes-stacked me-2"></i>ALMACEN
          </button>
        </h2>
        <div id="colInv" class="accordion-collapse collapse <?= $showInv?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colInv">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['inventario'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- RECEPCIÓN -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-recep">
        <h2 class="accordion-header" id="hdrRecep">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showRecep?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colRecep"
                  aria-expanded="<?= $showRecep?'true':'false'?>" aria-controls="colRecep">
            <i class="fa-solid fa-inbox me-2"></i>Recepción
          </button>
        </h2>
        <div id="colRecep" class="accordion-collapse collapse <?= $showRecep?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colRecep">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['recepcion'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- ADICIONALES -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-adic">
        <h2 class="accordion-header" id="hdrAdic">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showAdic?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colAdic"
                  aria-expanded="<?= $showAdic?'true':'false'?>" aria-controls="colAdic">
            <i class="fa-solid fa-layer-group me-2"></i>Adicionales
          </button>
        </h2>
        <div id="colAdic" class="accordion-collapse collapse <?= $showAdic?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colAdic">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['adicionales'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- DESPACHO -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-desp">
        <h2 class="accordion-header" id="hdrDesp">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showDesp?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colDesp"
                  aria-expanded="<?= $showDesp?'true':'false'?>" aria-controls="colDesp">
            <i class="fa-solid fa-truck-ramp-box me-2"></i>Despacho
          </button>
        </h2>
        <div id="colDesp" class="accordion-collapse collapse <?= $showDesp?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colDesp">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['despacho'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <!-- REPORTES -->
      <div class="accordion-item bg-secondary-subtle border-0" id="sec-report">
        <h2 class="accordion-header" id="hdrReport">
          <button class="accordion-button bg-secondary-subtle text-dark <?= $showReport?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colReport"
                  aria-expanded="<?= $showReport?'true':'false'?>" aria-controls="colReport">
            <i class="fa-solid fa-chart-line me-2"></i>Reportes
          </button>
        </h2>
        <div id="colReport" class="accordion-collapse collapse <?= $showReport?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colReport">
          <div class="accordion-body py-2 bg-secondary-subtle">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['reportes'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>

      <?php if ($permiso === 777): ?>
      <!-- ADMINISTRACIÓN -->
      <div class="accordion-item bg-dark border-0 rounded-2 overflow-hidden" id="sec-admin">
        <h2 class="accordion-header" id="hdrAdmin">
          <button class="accordion-button bg-dark text-light <?= $showAdmin?'':'collapsed'?>"
                  type="button" data-bs-toggle="collapse" data-bs-target="#colAdmin"
                  aria-expanded="<?= $showAdmin?'true':'false'?>" aria-controls="colAdmin">
            <i class="fa-solid fa-user-gear me-2"></i>Administración
          </button>
        </h2>
        <div id="colAdmin" class="accordion-collapse collapse <?= $showAdmin?'show':'' ?>"
             data-bs-parent="#menuAccordion" data-remember="colAdmin">
          <div class="accordion-body py-2 bg-dark">
            <ul class="nav flex-column gap-1">
              <?php foreach ($sections['admin'] as $it): ?>
                <?= navItem($it['href'],$it['label'],$it['icon'],$it['file'],$currentPage, $it['mode'] ?? 'dark'); ?>
              <?php endforeach; ?>
            </ul>
          </div>
        </div>
      </div>
      <?php endif; ?>

      <?php endif; // permiso 2/777 ?>
    </div><!-- /menuAccordion -->
  </div>
</nav>

<script>
/**
 * Persistencia simple del estado de los acordeones en localStorage.
 * Cada .accordion-collapse con atributo data-remember guarda/restaura su estado.
 */
(function() {
  const storeKey = (id) => 'menu_collapse_' + id;
  const rememberNodes = document.querySelectorAll('.accordion-collapse[data-remember]');
  rememberNodes.forEach(node => {
    const id = node.getAttribute('id');
    if (!id) return;
    // Restaurar
    const val = localStorage.getItem(storeKey(id));
    if (val === 'show') {
      node.classList.add('show');
    } else if (val === 'hide') {
      node.classList.remove('show');
    }
    // Escuchar cambios
    node.addEventListener('shown.bs.collapse', () => localStorage.setItem(storeKey(id), 'show'));
    node.addEventListener('hidden.bs.collapse', () => localStorage.setItem(storeKey(id), 'hide'));
  });
})();
</script>
