<?php 
// /includes/sidebar.php — Sidebar + ACL + Diseño responsivo
if (session_status() === PHP_SESSION_NONE) session_start();

$currentPage = basename(parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '');
$rol_raw = strtolower(trim($_SESSION['rol'] ?? 'ventas'));
$role = str_replace('-', '_', $rol_raw);
if ($role === 'super_admin') $role = 'superadmin';

/**
 * ACL por módulo/acción:
 * estructura: modulo => [view, create, edit, delete, disable]
 * disable = "dar de baja" (cuando aplique)
 */
function buildACL(string $role): array {
    $ALL_FALSE = ['view'=>false,'create'=>false,'edit'=>false,'delete'=>false,'disable'=>false];

    $acl = [
        // Dashboards
        'dashboard'           => $ALL_FALSE,
        'dashboard_analytics' => $ALL_FALSE,
        'dashboard_users'     => $ALL_FALSE, // NUEVO: Dashboard Usuarios (solo superadmin)

        // Gestión principal
        'clientes'           => $ALL_FALSE,
        'plataformas'        => $ALL_FALSE,
        'cuentas_maestras'   => $ALL_FALSE,
        'perfiles_vendidos'  => $ALL_FALSE,
        'proveedores'        => $ALL_FALSE,

        // Administración
        'finanzas'           => $ALL_FALSE, // colapsable: ingresos/egresos/reporte
        'usuarios'           => $ALL_FALSE,
        'config'             => $ALL_FALSE,
    ];

    switch ($role) {
        case 'superadmin':
            foreach ($acl as $k => $_) {
                $acl[$k] = ['view'=>true,'create'=>true,'edit'=>true,'delete'=>true,'disable'=>true];
            }
            // explícito por legibilidad (ya están en true con el foreach)
            $acl['dashboard']['view'] = true;
            $acl['dashboard_analytics']['view'] = true;
            $acl['dashboard_users']['view'] = true; // NUEVO
            $acl['finanzas']['view'] = true;
            break;

        case 'admin':
            foreach (['clientes','plataformas','cuentas_maestras','perfiles_vendidos','proveedores','config'] as $m) {
                $acl[$m] = ['view'=>true,'create'=>true,'edit'=>true,'delete'=>true,'disable'=>true];
            }
            // Dashboards y finanzas ocultos para admin (ajustable)
            $acl['dashboard']           = $ALL_FALSE;
            $acl['dashboard_analytics'] = $ALL_FALSE;
            $acl['dashboard_users']     = $ALL_FALSE; // NUEVO: admin NO lo ve
            $acl['usuarios']            = $ALL_FALSE; // Admin no gestiona usuarios
            $acl['finanzas']            = $ALL_FALSE;
            break;

        case 'ventas': // vendedor
            $acl['clientes']          = ['view'=>true,'create'=>true,'edit'=>true,'delete'=>false,'disable'=>false];
            $acl['cuentas_maestras']  = ['view'=>true,'create'=>false,'edit'=>false,'delete'=>false,'disable'=>false];
            $acl['perfiles_vendidos'] = ['view'=>true,'create'=>true,'edit'=>true,'delete'=>false,'disable'=>false];
            break;

        case 'cortes':
            $acl['perfiles_vendidos'] = ['view'=>true,'create'=>false,'edit'=>false,'delete'=>true,'disable'=>true];
            $acl['cuentas_maestras'] = ['view'=>true,'create'=>false,'edit'=>true,'delete'=>false,'disable'=>false];
            break;

        default:
            // sin permisos
            break;
    }
    return $acl;
}

$ACL = buildACL($role);
$_SESSION['ACL'] = $ACL; // disponible para checks en backend

// Helpers de vista
function canView(string $module): bool {
    $acl = $_SESSION['ACL'] ?? [];
    return !empty($acl[$module]['view']);
}
function isActive(string $filename): bool {
    $cp = basename(parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '');
    return $cp === $filename;
}

$isFinanzasActive = in_array($currentPage, ['ingresos.php','egresos.php','reporte_ganancias.php'], true);

// Home según rol: superadmin → dashboard; resto → perfiles vendidos
$homeHref = ($role === 'superadmin')
  ? '/digitalpremium/pages/dashboard.php'
  : '/digitalpremium/pages/perfiles_vendidos.php';
?>
<style>
:root{
  --sb-bg-1:#0f1419;
  --sb-bg-2:#1a1f2e;
  --sb-accent:#6366f1;
  --sb-accent-2:#8b5cf6;
  --sb-text:#f8fafc;
  --sb-muted:#94a3b8;
  --sb-hover:rgba(255,255,255,.06);
  --sb-active:#3730a3;
  --sb-border:rgba(255,255,255,.08);
  --sb-shadow:rgba(0,0,0,.4);
  --sb-success:#059669;
  --sb-warning:#d97706;
  --sb-danger:#dc2626;
}

/* Botón de hamburguesa para móviles */
.sidebar-toggle-mobile {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 1041;
  background: var(--sb-accent);
  border: none;
  color: white;
  padding: 12px 15px;
  border-radius: 10px;
  font-size: 18px;
  box-shadow: 0 4px 20px rgba(99, 102, 241, 0.3);
  transition: all 0.3s ease;
  display: none;
}

.sidebar-toggle-mobile:hover {
  background: var(--sb-accent-2);
  transform: scale(1.05);
  box-shadow: 0 6px 25px rgba(139, 92, 246, 0.4);
}

/* Botón de cerrar para móviles */
.sidebar-close {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 1050;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border: none;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: none;
  align-items: center;
  justify-content: center;
  font-size: 1.1rem;
  cursor: pointer;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.sidebar-close:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.sidebar-close:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.3);
}

/* Overlay para móviles */
.sidebar-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1039;
  display: none;
}

/* Sidebar principal */
.sidebar{
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 1040;
  width: 320px; /* Aumentado a 320px para mejor estética */
  padding: 16px 14px 12px;
  background: linear-gradient(180deg,var(--sb-bg-1) 0%, var(--sb-bg-2) 100%);
  box-shadow: 2px 0 18px var(--sb-shadow);
  color: var(--sb-text);
  transition: all 0.3s ease;
  overflow-x: hidden;
  overflow-y: auto;
}

/* Ocultar sidebar en móviles por defecto */
@media (max-width: 991.98px) {
  .sidebar {
    transform: translateX(-100%) !important;
    width: 320px;
    height: calc(100vh - 60px);
    top: 60px;
  }
  
  .sidebar.expanded {
    transform: translateX(0) !important;
  }
}

/* Responsive para móviles - Solo mostrar botón de cerrar */
@media (max-width: 991.98px) {
  .sidebar-close {
    display: block !important;
  }
}

.sidebar::-webkit-scrollbar{ width:8px; }
.sidebar::-webkit-scrollbar-thumb{ background:var(--sb-border); border-radius:6px; }

.sidebar-header{
  display:flex; align-items:center; justify-content:center;
  padding:12px 10px 24px;
  border-bottom:1px solid var(--sb-border);
  margin-bottom:16px;
}

.logo-link{
  display:flex; align-items:center; gap:.75rem; text-decoration:none; color:var(--sb-text);
  transition:all .3s ease;
}

.logo-link:hover{
  transform:scale(1.05);
  color:var(--sb-accent-2);
}

        .logo-container{
          width:48px; height:48px; display:flex; align-items:center; justify-content:center;
          background: linear-gradient(135deg, rgba(99,102,241,0.2), rgba(139,92,246,0.2));
          border-radius:12px; 
          border:1px solid rgba(99,102,241,0.3);
          backdrop-filter:blur(10px);
          box-shadow:0 4px 20px rgba(99,102,241,0.2);
          overflow:hidden;
        }
        
        .logo-image{
          width:50px; height:50px; object-fit:contain;
          max-width:100%;
          max-height:100%;
          display:block;
          filter:brightness(1.1) contrast(1.1);
        }

        .logo-fallback{
          width:50px; height:50px; 
          background:linear-gradient(135deg, var(--sb-accent), var(--sb-accent-2));
          border-radius:12px;
          display:flex; align-items:center; justify-content:center;
          color:#fff;
          font-weight:700;
          font-size:1.2rem;
          box-shadow:0 4px 20px rgba(99,102,241,0.3);
        }

.logo-text{ 
  font-weight:700; font-size:1.2rem; letter-spacing:.3px; 
  background:linear-gradient(135deg, var(--sb-accent), var(--sb-accent-2));
  -webkit-background-clip:text;
  -webkit-text-fill-color:transparent;
  background-clip:text;
}

.group-title{
  text-transform:uppercase; font-size:.75rem; letter-spacing:.1em; color:var(--sb-muted);
  padding:16px 10px 8px; margin:8px 0 6px; 
  border-top:1px solid var(--sb-border);
  font-weight:600;
  position:relative;
}

.group-title::before{
  content:'';
  position:absolute; left:10px; top:50%; transform:translateY(-50%);
  width:4px; height:4px; background:var(--sb-accent-2); border-radius:50%;
}

.nav-list{ list-style:none; margin:0; padding:6px 4px; }
.nav-link{
  display:flex; align-items:center; gap:.75rem; padding:12px 14px;
  border-radius:12px; color:var(--sb-text); text-decoration:none;
  transition:all .2s ease; position:relative; margin-bottom:4px;
  border:1px solid transparent;
}

.nav-link:hover{ 
  background:var(--sb-hover); 
  transform:translateX(4px); 
  border-color:rgba(99,102,241,0.3);
}

.nav-link.active, .nav-link.active-parent{
  background:linear-gradient(135deg,rgba(99,102,241,0.15),rgba(139,92,246,0.1));
  border:1px solid rgba(99,102,241,0.4);
  box-shadow:0 4px 20px rgba(99,102,241,0.2);
  transform:translateX(4px);
}

.nav-link .icon{
  width:24px; text-align:center; font-size:1.1rem; color:var(--sb-accent);
  transition:all .2s ease;
}

.nav-link:hover .icon{
  transform:scale(1.1);
  color:var(--sb-accent-2);
}

.label{ 
  white-space:nowrap; 
  font-weight:500;
  font-size:0.9rem;
}

.caret{ 
  margin-left:auto; font-size:.9rem; color:var(--sb-muted); 
  transition:transform .2s ease; 
}

.nav-link.collapsed .caret{ transform:rotate(0deg); }
.nav-link:not(.collapsed) .caret{ transform:rotate(180deg); }

.submenu{ 
  padding:4px 0 8px 40px; 
  margin-top:4px;
  border-left:2px solid rgba(124,77,255,0.2);
  margin-left:12px;
}

.submenu .nav-link{ 
  padding:10px 12px; border-radius:10px; 
  margin-bottom:2px;
  font-size:0.85rem;
}

.submenu .nav-link.active{
  background:rgba(124,77,255,0.15); 
  border-left:3px solid var(--sb-accent-2); 
  margin-left:-14px; 
  padding-left:26px;
  border:1px solid rgba(124,77,255,0.3);
}

.sidebar-footer{ 
  margin-top:20px; padding:16px 8px; 
  border-top:1px solid var(--sb-border);
}

.footer-sep{ border-color:var(--sb-border); }

.role-chip{
  display:inline-flex; align-items:center; gap:.4rem;
  background:linear-gradient(135deg, rgba(99,102,241,0.15), rgba(139,92,246,0.1));
  color:var(--sb-text); 
  border:1px solid rgba(99,102,241,0.4);
  padding:.4rem .8rem; border-radius:999px; 
  font-size:.75rem; font-weight:600;
  box-shadow:0 2px 12px rgba(99,102,241,0.2);
}

.footer-actions{ margin-top:12px; }

.logout-link{
  display:flex; align-items:center; gap:.6rem; 
  color:var(--sb-muted); text-decoration:none; 
  padding:10px 12px; border-radius:10px;
  transition:all .2s ease;
  border:1px solid transparent;
}

.logout-link:hover{ 
  color:var(--sb-danger); 
  background:rgba(239,68,68,0.1); 
  border-color:rgba(239,68,68,0.3);
  transform:translateX(4px);
}

.badge{
  padding:0.25rem 0.5rem;
  font-size:0.7rem;
  font-weight:600;
  border-radius:6px;
}

.badge.bg-warning{
  background:var(--sb-warning) !important;
  color:#000 !important;
}

.badge.bg-success{
  background:var(--sb-success) !important;
  color:#fff !important;
}

.badge.bg-danger{
  background:var(--sb-danger) !important;
  color:#fff !important;
}

/* Animaciones */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.nav-link {
  animation: fadeInUp 0.3s ease forwards;
}

.nav-link:nth-child(1) { animation-delay: 0.1s; }
.nav-link:nth-child(2) { animation-delay: 0.2s; }
.nav-link:nth-child(3) { animation-delay: 0.3s; }
.nav-link:nth-child(4) { animation-delay: 0.4s; }
.nav-link:nth-child(5) { animation-delay: 0.5s; }
</style>

<div class="sidebar" id="mainSidebar">
  <!-- Botón de cerrar para móviles -->
  <button class="sidebar-close d-lg-none" id="sidebarCloseBtn" aria-label="Cerrar menú">
    <i class="fas fa-times"></i>
  </button>
  
  <!-- Header / Logo -->
  <div class="sidebar-header">
          <a href="<?= htmlspecialchars($homeHref) ?>" class="logo-link">
        <div class="logo-container">
          <img src="/digitalpremium/assets/logo/logo-blanco.png" alt="DigitalPremium Logo" class="logo-image" 
               onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
          <div class="logo-fallback" style="display:none;">DP</div>
        </div>
        <span class="logo-text">DigitalPremium</span>
      </a>
  </div>

  <nav>
    <ul class="nav-list">

      <!-- DASHBOARDS -->
      <?php if (canView('dashboard') || canView('dashboard_analytics') || canView('dashboard_users')): ?>
        <li class="group-title">📊 Análisis y Reportes</li>

        <?php if (canView('dashboard')): ?>
        <li>
          <a class="nav-link <?= isActive('dashboard.php') ? 'active' : '' ?>" href="/digitalpremium/pages/dashboard.php">
            <i class="icon fas fa-tachometer-alt"></i>
            <span class="label">Vista General</span>
          </a>
        </li>
        <?php endif; ?>

        <?php if (canView('dashboard_analytics')): ?>
        <li>
          <a class="nav-link <?= isActive('dashboard2.php') ? 'active' : '' ?>" href="/digitalpremium/pages/dashboard2.php">
            <i class="icon fas fa-chart-pie"></i>
            <span class="label">Métricas y Estadísticas</span>
          </a>
        </li>
        <?php endif; ?>

        <?php if (canView('dashboard_users')): ?>
        <li>
          <a class="nav-link <?= isActive('dashboardusers.php') ? 'active' : '' ?>" href="/digitalpremium/pages/dashboardusers.php">
            <i class="icon fas fa-users-gear"></i>
            <span class="label">Gestión de Usuarios</span>
          </a>
        </li>
        <?php endif; ?>
      <?php endif; ?>

      <!-- GESTIÓN PRINCIPAL -->
      <?php if (canView('clientes') || canView('plataformas') || canView('cuentas_maestras') || canView('perfiles_vendidos') || canView('proveedores')): ?>
        <li class="group-title">🏢 Operaciones Comerciales</li>

        <?php if (canView('clientes')): ?>
        <li>
          <a class="nav-link <?= isActive('clientes.php') ? 'active' : '' ?>" href="/digitalpremium/pages/clientes.php">
            <i class="icon fas fa-users"></i>
            <span class="label">Clientes</span>
          </a>
        </li>
        <?php endif; ?>

        <?php if (canView('plataformas')): ?>
        <li>
          <a class="nav-link <?= isActive('plataformas.php') ? 'active' : '' ?>" href="/digitalpremium/pages/plataformas.php">
            <i class="icon fas fa-tv"></i>
            <span class="label">Plataformas</span>
          </a>
        </li>
        <?php endif; ?>

        <?php if (canView('cuentas_maestras')): ?>
        <li>
          <a class="nav-link <?= isActive('cuentas_maestras.php') ? 'active' : '' ?>" href="/digitalpremium/pages/cuentas_maestras.php">
            <i class="icon fas fa-key"></i>
            <span class="label">Cuentas Maestras</span>
          </a>
        </li>
        <?php endif; ?>

        <?php if (canView('perfiles_vendidos')): ?>
        <li>
          <a class="nav-link <?= (in_array($currentPage, ['perfiles_vendidos.php','perfiles_vendidos_crear.php'], true) ? 'active' : '') ?>"
             href="/digitalpremium/pages/perfiles_vendidos.php">
            <i class="icon fas fa-user-check"></i>
            <span class="label">Perfiles Vendidos</span>
          </a>
        </li>
        <?php endif; ?>

       
        
      <?php endif; ?>

      <!-- ADMINISTRACIÓN Y REPORTES -->
      <?php if (canView('finanzas') || canView('usuarios') || canView('config')): ?>
        <li class="group-title">⚙️ Administración del Sistema</li>

        <?php if (canView('finanzas')): ?>
        <li>
          <a class="nav-link collapsed <?= $isFinanzasActive ? 'active active-parent' : '' ?>"
             href="#collapseFinanzas" data-bs-toggle="collapse" role="button"
             aria-expanded="<?= $isFinanzasActive ? 'true' : 'false' ?>">
            <i class="icon fas fa-wallet"></i>
            <span class="label">Finanzas</span>
            <i class="fas fa-angle-down caret"></i>
          </a>
          <div class="collapse <?= $isFinanzasActive ? 'show' : '' ?>" id="collapseFinanzas">
            <ul class="submenu">
              <li><a class="nav-link <?= isActive('ingresos.php') ? 'active' : '' ?>" href="/digitalpremium/pages/ingresos.php"><i class="icon fas fa-arrow-up"></i><span class="label">Ingresos</span></a></li>
              <li><a class="nav-link <?= isActive('egresos.php') ? 'active' : '' ?>" href="/digitalpremium/pages/egresos.php"><i class="icon fas fa-arrow-down"></i><span class="label">Egresos</span></a></li>
              <li><a class="nav-link <?= isActive('reporte_ganancias.php') ? 'active' : '' ?>" href="/digitalpremium/pages/reporte_ganancias.php"><i class="icon fas fa-chart-line"></i><span class="label">Reporte Ganancias</span></a></li>
            </ul>
          </div>
        </li>
        <?php endif; ?>

        <?php if (canView('usuarios')): ?>
        <li>
          <a class="nav-link <?= isActive('gestion_usuarios.php') ? 'active' : '' ?>" href="/digitalpremium/pages/gestion_usuarios.php">
            <i class="icon fas fa-users-cog"></i>
            <span class="label">Gestionar Usuarios</span>
          </a>
        </li>
        <?php endif; ?>

        <?php if (canView('config')): ?>
        <li>
          <a class="nav-link <?= isActive('configuracion.php') ? 'active' : '' ?>" href="/digitalpremium/pages/configuracion.php">
            <i class="icon fas fa-cog"></i>
            <span class="label">Configuración</span>
          </a>
        </li>
        <?php endif; ?>
      <?php endif; ?>

    </ul>
  </nav>

  <!-- Footer -->
  <div class="sidebar-footer">
    <div class="d-flex align-items-center justify-content-between">
      <span class="role-chip">
        <i class="fas fa-user-shield"></i>
        <?= htmlspecialchars(ucfirst($role)) ?>
      </span>
    </div>
    <div class="footer-actions mt-2">
      <a class="logout-link" href="/digitalpremium/auth/logout.php">
        <i class="fas fa-sign-out-alt"></i>
        <span class="label">Cerrar Sesión</span>
      </a>
    </div>
  </div>
</div>

<!-- Overlay para móviles -->
<div class="sidebar-overlay" id="sidebar-overlay"></div>

<script>
  // Exponer permisos al front para ocultar/mostrar botones según rol
  window.APP_PERMS = <?= json_encode($ACL, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
  window.APP_ROLE  = <?= json_encode($role) ?>;

  // Verificar carga del logo
  document.addEventListener('DOMContentLoaded', function() {
    const logoImg = document.querySelector('.logo-image');
    if (logoImg) {
      logoImg.addEventListener('load', function() {
        console.log('Logo cargado correctamente');
      });
      
      logoImg.addEventListener('error', function() {
        console.log('Error al cargar el logo, mostrando fallback');
        this.style.display = 'none';
        const fallback = this.nextElementSibling;
        if (fallback) {
          fallback.style.display = 'flex';
        }
      });
    }
  });
</script>
