<?php
// Iniciar buffer de salida para evitar errores de headers
ob_start();
session_start();
if(!isset($_SESSION['id'])){
    header("Location: index.php");
    exit();
}

// Detectar qué página mostrar
$page = isset($_GET['page']) ? $_GET['page'] : 'dashboard';
$allowed_pages = [
    'dashboard', 
    'usuarios_listar', 'usuarios_nuevo', 'usuarios_editar',
    'clientes_listar', 'clientes_nuevo', 'clientes_editar',
    'categoria_listar', 'categoria_nuevo', 'categoria_editar',
    'producto_listar', 'producto_nuevo', 'producto_editar',
    'venta_listar', 'venta_nuevo', 'venta_editar', 'venta_ver',
    'detalle_venta_listar', 'detalle_venta_nuevo', 'detalle_venta_editar'
];
$page = in_array($page, $allowed_pages) ? $page : 'dashboard';
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema Web - Panel Principal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>
    <style>
        :root { --sidebar-width: 260px; }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #FFF8F5; }
        .sidebar {
            position: fixed; left: 0; top: 0; height: 100vh; width: var(--sidebar-width);
            background: linear-gradient(180deg, #F06292, #EC407A); color: white;
            z-index: 1000; transition: all 0.3s ease; overflow-y: auto;
        }
        .sidebar .brand { padding: 25px 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar .brand h3 { font-weight: 700; font-size: 1.3rem; margin: 0; }
        .sidebar .brand small { opacity: 0.7; font-size: 0.8rem; }
        .sidebar .user-info { padding: 20px; text-align: center; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar .user-info .avatar {
            width: 60px; height: 60px; border-radius: 50%; background: rgba(255,255,255,0.2);
            display: flex; align-items: center; justify-content: center; margin: 0 auto 10px;
            font-size: 1.8rem; border: 3px solid rgba(255,255,255,0.3);
        }
        .sidebar .user-info .avatar img { width: 60px; height: 60px; border-radius: 50%; object-fit: cover; }
        .sidebar .user-info h6 { margin: 0; font-weight: 600; }
        .sidebar .user-info small { opacity: 0.7; }
        .sidebar .nav-menu { padding: 10px 0; }
        .sidebar .nav-menu .nav-item { padding: 0 15px; margin-bottom: 5px; }
        .sidebar .nav-menu .nav-link {
            color: rgba(255,255,255,0.8); padding: 12px 15px; border-radius: 10px;
            text-decoration: none; display: flex; align-items: center; transition: all 0.3s;
        }
        .sidebar .nav-menu .nav-link i { width: 25px; margin-right: 12px; font-size: 1.1rem; }
        .sidebar .nav-menu .nav-link:hover, .sidebar .nav-menu .nav-link.active {
            background: rgba(255,255,255,0.25); color: white; border-left: 4px solid #fff;
        }
        .sidebar .nav-menu .nav-link.logout {
            color: #ff6b6b; margin-top: 20px; border-top: 1px solid rgba(255,255,255,0.1); padding-top: 20px;
        }
        .sidebar .nav-menu .nav-link.logout:hover { background: rgba(255,0,0,0.15); }
        .main-content { margin-left: var(--sidebar-width); min-height: 100vh; padding: 0; }
        .top-bar {
            background: #FFF0F5; padding: 15px 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0;
            z-index: 999; border-bottom: 2px solid #F8BBD0;
        }
        .top-bar .page-title h4 { margin: 0; font-weight: 600; color: #333; }
        .top-bar .page-title small { color: #666; }
        .top-bar .user-actions { display: flex; align-items: center; gap: 20px; }
        .top-bar .user-actions .btn-logout {
            background: #D81B60; border: none; padding: 8px 20px; border-radius: 8px;
            text-decoration: none; color: white; font-weight: 500; transition: all 0.3s;
        }
        .top-bar .user-actions .btn-logout:hover { background: #C2185B; transform: translateY(-2px); color: white; }
        .content-area { padding: 30px; }
        .sidebar-toggle { display: none; background: none; border: none; color: #8D6E63; font-size: 1.5rem; margin-right: 15px; }
        .sidebar-backdrop { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; }
        .sidebar-backdrop.show { display: block; }
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); width: 280px; }
            .sidebar.open { transform: translateX(0); }
            .main-content { margin-left: 0; }
            .sidebar-toggle { display: block; }
            .content-area { padding: 20px 15px; }
        }
        .table-container { background: #fff; border-radius: 15px; padding: 20px; box-shadow: 0 2px 15px rgba(0,0,0,.05); }
        .table thead th { background: #002855; color: #fff; border: none; }
        .btn-pdf { background: #dc3545; color: #fff; border: none; transition: .3s; }
        .btn-pdf:hover { background: #c82333; color: #fff; }
        .search-box, .filter-select { border-radius: 10px; border: 2px solid #e0e0e0; padding: 10px 15px; transition: .3s; }
        .search-box:focus, .filter-select:focus { border-color: #002855; box-shadow: 0 0 0 .2rem rgba(0,40,85,.25); }
        .action-buttons .btn { padding: 5px 12px; border-radius: 8px; font-size: .85rem; }
        .btn-edit { background: #ffc107; color: #000; }
        .btn-delete { background: #dc3545; color: #fff; }
        .btn-view { background: #17a2b8; color: #fff; }
        .btn-view:hover { background: #138496; color: #fff; }
        .empty-state { text-align: center; padding: 60px 20px; }
        .empty-state i { font-size: 4rem; color: #ccc; margin-bottom: 20px; }
        .badge-filter { background: #e9ecef; padding: 8px 15px; border-radius: 20px; }
        #factura { background: white; padding: 30px; }
        @media print {
            .sidebar, .top-bar, .btn, .action-buttons, .d-flex .btn, .no-print { display: none !important; }
            .main-content { margin-left: 0 !important; padding: 0 !important; }
            .content-area { padding: 10px !important; }
            #factura { box-shadow: none !important; border: none !important; padding: 10px !important; }
            .table-container { box-shadow: none !important; border: none !important; }
            body { background: white !important; }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="brand">
            <h3><i class="fas fa-university me-2"></i>Bazar Paola</h3>
            <small>Panel Administrativo</small>
        </div>
        <div class="user-info">
            <div class="avatar">
                <img src="assets/foto.png" alt="Foto de Perfil">
            </div>
            <h6><?php echo htmlspecialchars($_SESSION['nombre']); ?></h6>
            <small><?php echo htmlspecialchars($_SESSION['email']); ?></small>
        </div>
        <nav class="nav-menu">
            <div class="nav-item">
                <a href="menu.php?page=dashboard" class="nav-link <?php echo $page == 'dashboard' ? 'active' : ''; ?>">
                    <i class="fas fa-tachometer-alt"></i> Panel de Control
                </a>
            </div>
            <div class="nav-item">
                <a href="menu.php?page=usuarios_listar" class="nav-link <?php echo $page == 'usuarios_listar' ? 'active' : ''; ?>">
                    <i class="fas fa-users"></i> Usuario
                </a>
            </div>
            <div class="nav-item">
                <a href="menu.php?page=clientes_listar" class="nav-link <?php echo $page == 'clientes_listar' ? 'active' : ''; ?>">
                    <i class="fas fa-users"></i> Clientes
                </a>
            </div>
            <div class="nav-item">
                <a href="menu.php?page=categoria_listar" class="nav-link <?php echo $page == 'categoria_listar' ? 'active' : ''; ?>">
                    <i class="fas fa-tags"></i> Categoria
                </a>
            </div>
            <div class="nav-item">
                <a href="menu.php?page=producto_listar" class="nav-link <?php echo $page == 'producto_listar' ? 'active' : ''; ?>">
                    <i class="fas fa-box"></i> Producto
                </a>
            </div>
            <div class="nav-item">
                <a href="menu.php?page=venta_listar" class="nav-link <?php echo $page == 'venta_listar' ? 'active' : ''; ?>">
                    <i class="fas fa-file-invoice"></i> Venta
                </a>
            </div>
         
            <div class="nav-item">
                <a href="logout.php" class="nav-link logout">
                    <i class="fas fa-sign-out-alt"></i> Cerrar Sesión
                </a>
            </div>
        </nav>
    </div>

    <div class="sidebar-backdrop" id="sidebarBackdrop"></div>

    <div class="main-content">
        <div class="top-bar">
            <div class="page-title">
                <button class="sidebar-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <h4>
                    <?php
                    $pageTitle = 'Panel de Control';
                    if($page == 'usuarios_listar') $pageTitle = 'Gestión de Usuarios';
                    elseif($page == 'usuarios_nuevo') $pageTitle = 'Nuevo Usuario';
                    elseif($page == 'usuarios_editar') $pageTitle = 'Editar Usuario';
                    elseif($page == 'clientes_listar') $pageTitle = 'Gestión de Clientes';
                    elseif($page == 'clientes_nuevo') $pageTitle = 'Nuevo Cliente';
                    elseif($page == 'clientes_editar') $pageTitle = 'Editar Cliente';
                    elseif($page == 'categoria_listar') $pageTitle = 'Gestión de Categorías';
                    elseif($page == 'categoria_nuevo') $pageTitle = 'Nueva Categoría';
                    elseif($page == 'categoria_editar') $pageTitle = 'Editar Categoría';
                    elseif($page == 'producto_listar') $pageTitle = 'Gestión de Productos';
                    elseif($page == 'producto_nuevo') $pageTitle = 'Nuevo Producto';
                    elseif($page == 'producto_editar') $pageTitle = 'Editar Producto';
                    elseif($page == 'venta_listar') $pageTitle = 'Lista de Ventas';
                    elseif($page == 'venta_nuevo') $pageTitle = 'Nueva Venta';
                    elseif($page == 'venta_editar') $pageTitle = 'Editar Venta';
                    elseif($page == 'venta_ver') $pageTitle = 'Factura / Detalle de Venta';
                    elseif($page == 'detalle_venta_listar') $pageTitle = 'Detalle de Ventas';
                    elseif($page == 'detalle_venta_nuevo') $pageTitle = 'Nuevo Detalle de Venta';
                    elseif($page == 'detalle_venta_editar') $pageTitle = 'Editar Detalle de Venta';
                    echo $pageTitle;
                    ?>
                    <small><i class="fas fa-chevron-right mx-2"></i> <?php echo date('d/m/Y H:i'); ?></small>
                </h4>
            </div>
            <div class="user-actions">
                <span class="badge bg-primary rounded-pill">
                    <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($_SESSION['nombre']); ?>
                </span>
                <a href="logout.php" class="btn-logout">
                    <i class="fas fa-sign-out-alt me-1"></i> Salir
                </a>
            </div>
        </div>
        <div class="content-area">
            <div id="pageContent">
                <?php
                switch($page) {
                    case 'dashboard':
                        ?>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="card text-white bg-primary mb-3">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="card-title">Usuarios</h6>
                                                <h2 class="mb-0"><?php
                                                    include('conexion.php');
                                                    $result = mysqli_query($conexion, "SELECT COUNT(*) as total FROM usuarios");
                                                    $row = mysqli_fetch_assoc($result);
                                                    echo $row['total'];
                                                ?></h2>
                                            </div>
                                            <i class="fas fa-users fa-3x opacity-50"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card text-white bg-success mb-3">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="card-title">Clientes</h6>
                                                <h2 class="mb-0"><?php
                                                    include('conexion.php');
                                                    $result = mysqli_query($conexion, "SELECT COUNT(*) as total FROM clientes");
                                                    $row = mysqli_fetch_assoc($result);
                                                    echo $row['total'];
                                                ?></h2>
                                            </div>
                                            <i class="fas fa-user-check fa-3x opacity-50"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card text-white bg-warning mb-3">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="card-title">Productos</h6>
                                                <h2 class="mb-0"><?php
                                                    include('conexion.php');
                                                    $result = mysqli_query($conexion, "SELECT COUNT(*) as total FROM producto");
                                                    $row = mysqli_fetch_assoc($result);
                                                    echo $row['total'];
                                                ?></h2>
                                            </div>
                                            <i class="fas fa-box fa-3x opacity-50"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="card text-white bg-info mb-3">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="card-title">Venta</h6>
                                                <h2 class="mb-0"><?php
                                                    include('conexion.php');
                                                    $result = mysqli_query($conexion, "SELECT COUNT(*) as total FROM venta");
                                                    $row = mysqli_fetch_assoc($result);
                                                    echo $row['total'];
                                                ?></h2>
                                            </div>
                                            <i class="fas fa-file-invoice fa-3x opacity-50"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card text-white bg-danger mb-3">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="card-title">Categorias</h6>
                                                <h2 class="mb-0"><?php
                                                    include('conexion.php');
                                                    $result = mysqli_query($conexion, "SELECT COUNT(*) as total FROM categoria");
                                                    $row = mysqli_fetch_assoc($result);
                                                    echo $row['total'];
                                                ?></h2>
                                            </div>
                                            <i class="fas fa-tags fa-3x opacity-50"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card text-white bg-secondary mb-3">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <h6 class="card-title">Bienvenido</h6>
                                                <h5 class="mb-0"><?php echo htmlspecialchars($_SESSION['nombre']); ?></h5>
                                            </div>
                                            <i class="fas fa-smile fa-3x opacity-50"></i>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header bg-white">
                                <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Información del Sistema</h5>
                            </div>
                            <div class="card-body">
                                <p>Bienvenido al panel administrativo del Sistema Web de Postres.</p>
                                <ul>
                                    <li>Gestiona usuarios, clientes, categorías, productos y ventas desde el menú lateral</li>
                                    <li>Filtra y exporta a PDF los registros</li>
                                    <li>Visualiza facturas con sus detalles</li>
                                    <li>Mantén tus datos actualizados</li>
                                </ul>
                            </div>
                        </div>
                        <?php
                        break;
                    case 'usuarios_listar':
                        include('usuarios/listar.php');
                        break;
                    case 'usuarios_nuevo':
                        include('usuarios/nuevo.php');
                        break;
                    case 'usuarios_editar':
                        include('usuarios/editar.php');
                        break;
                    case 'clientes_listar':
                        include('clientes/listar.php');
                        break;
                    case 'clientes_nuevo':
                        include('clientes/nuevo.php');
                        break;
                    case 'clientes_editar':
                        include('clientes/editar.php');
                        break;
                    case 'categoria_listar':
                        include('categoria/listar.php');
                        break;
                    case 'categoria_nuevo':
                        include('categoria/nuevo.php');
                        break;
                    case 'categoria_editar':
                        include('categoria/editar.php');
                        break;
                    case 'producto_listar':
                        include('producto/listar.php');
                        break;
                    case 'producto_nuevo':
                        include('producto/nuevo.php');
                        break;
                    case 'producto_editar':
                        include('producto/editar.php');
                        break;
                    case 'venta_listar':
                        include('venta/listar.php');
                        break;
                    case 'venta_nuevo':
                        include('venta/nuevo.php');
                        break;
                    case 'venta_editar':
                        include('venta/editar.php');
                        break;
                    case 'venta_ver':
                        include('venta/ver.php');
                        break;
                    case 'detalle_venta_listar':
                        include('detalle_venta/listar.php');
                        break;
                    case 'detalle_venta_nuevo':
                        include('detalle_venta/nuevo.php');
                        break;
                    case 'detalle_venta_editar':
                        include('detalle_venta/editar.php');
                        break;
                    default:
                        echo "<h2>Página en construcción</h2>";
                        echo "<p>El módulo solicitado está siendo desarrollado.</p>";
                }
                ?>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('sidebarToggle').addEventListener('click', function() {
            document.getElementById('sidebar').classList.toggle('open');
            document.getElementById('sidebarBackdrop').classList.toggle('show');
        });
        document.getElementById('sidebarBackdrop').addEventListener('click', function() {
            document.getElementById('sidebar').classList.remove('open');
            document.getElementById('sidebarBackdrop').classList.remove('show');
        });

        function imprimirFactura() {
            window.print();
        }
    </script>
</body>
</html>