<?php
// ==========================================
// 1. CAPA DE BACKEND (Lógica, Sesiones y SQL)
// ==========================================
session_start();

// Verificacion de Seguridad
if (!isset($_SESSION['usuario'])) {
    header("Location: login.php");
    exit();
}

include('db.php');

// Variables de sesion
$rol = $_SESSION['rol'];
$nombre_usuario = $_SESSION['usuario'];

// Manejo de la navegacion (Routing)
$vista = isset($_GET['view']) ? $_GET['view'] : 'home';

// CONSULTA INTEGRADA PARA LA ALERTA DE SOFTWARE (Para que suene en cualquier vista)
$check_global = mysqli_query($conexion, "SELECT COUNT(*) as total FROM pedidos WHERE estado = 'Pendiente'");
$data_global = mysqli_fetch_assoc($check_global);
$alarma_activa = ($data_global['total'] > 0) ? true : false;

// ==========================================
// 2. CAPA DE FRONTEND (HTML / Vista Limpia)
// ==========================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>El Nodo - Sistema de Soporte Tecnico</title>
    <link rel="stylesheet" href="style.css">
    <style>
        /* --- RESET Y NUEVOS ESTILOS GENERALES RESPONSIVE CON MAS ESPACIO --- */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
        }
        body {
            background-color: #0d1117;
            color: #c9d1d9;
            padding-bottom: 40px;
        }

        /* --- CONTENEDORES CON MAS AIRE --- */
        .card {
            background: #161b22;
            border: 1px solid #30363d;
            padding: 35px;
            border-radius: 12px;
            margin-bottom: 30px;
            color: #c9d1d9;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            animation: fadeInUp 0.5s ease-out both;
        }
        
        /* --- HEADER ADAPTABLE --- */
        header {
            padding: 25px 30px; 
            border-bottom: 1px solid #30363d;
            background: #161b22;
        }

        /* --- MENU DE NAVEGACION FLUIDO (FLEXBOX) --- */
        nav {
            padding: 15px 30px;
            background: #0d1117;
            border-bottom: 1px solid #30363d;
            display: flex;
            align-items: center;
            justify-content: flex-start;
            flex-wrap: wrap;
            gap: 15px;
        }
        nav a {
            text-decoration: none;
            padding: 12px 18px;
            border: 1px solid #30363d;
            border-radius: 8px;
            color: #c9d1d9;
            font-size: 0.9rem;
            font-weight: 500;
            transition: all 0.2s ease;
            text-align: center;
            background: #21262d;
        }
        nav a:hover {
            background: #30363d;
            border-color: #8b949e;
            color: white;
        }
        
        /* Boton salir inteligente con color sutil */
        nav a.btn-salir {
            border-color: rgba(248, 81, 73, 0.4);
            color: #f85149;
            background: rgba(248, 81, 73, 0.05);
            margin-left: auto;
        }
        nav a.btn-salir:hover {
            background: #f85149;
            color: white;
        }

        /* --- CONTROLES DE FORMULARIOS REFORZADOS CON ESPACIADO --- */
        label {
            display: block;
            margin-top: 18px;
            margin-bottom: 8px;
            color: #8b949e;
            font-size: 0.85rem;
        }
        input, select, textarea {
            width: 100%;
            padding: 14px 16px;
            margin: 6px 0 20px 0;
            background: #0d1117;
            border: 1px solid #30363d;
            color: white;
            border-radius: 8px;
            font-size: 0.95rem;
            transition: border-color 0.2s;
        }
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #58a6ff;
            box-shadow: 0 0 0 3px rgba(88, 166, 255, 0.15);
        }
        button, .btn-submit {
            width: 100%;
            cursor: pointer;
            border: none;
            border-radius: 8px;
            font-weight: bold;
            padding: 14px 20px;
            margin-top: 10px;
            background: #238636;
            color: white;
            font-size: 0.95rem;
            transition: background 0.2s;
        }
        button:hover {
            background: #2ea043;
        }

        /* --- ESPACIADO GLOBAL PARA TABLAS Y SEPARACIÓN DE BOTONES --- */
        table th, tr th {
            padding: 18px 15px !important;
        }
        table td, tr td {
            padding: 22px 15px !important;
            vertical-align: middle !important;
            white-space: nowrap; /* Evita desarmes raros */
        }

        /* Fuerza separación horizontal entre elementos contiguos en las celdas */
        td > * + * {
            margin-left: 12px !important;
        }

        table td a, 
        table td span, 
        table td button, 
        .card td a, 
        .card td span {
            display: inline-block !important;
            margin-right: 10px !important;
            margin-top: 4px !important;
            margin-bottom: 4px !important;
        }

        /* --- ANIMACIONES Y ESTADOS VACIOS --- */
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* --- MEDIA QUERIES (Ajustes especificos para Celulares) --- */
        @media (max-width: 768px) {
            header {
                text-align: center;
            }
            nav {
                justify-content: center;
                padding: 12px;
            }
            nav a {
                flex: 1 1 calc(50% - 10px);
                font-size: 0.85rem;
                padding: 12px 6px;
            }
            nav a.btn-salir {
                margin-left: 0;
                flex: 1 1 100%;
            }
            .card {
                padding: 20px;
                border-radius: 8px;
            }
            h1 { font-size: 1.6rem; }
            h2 { font-size: 1.25rem; }
        }
    </style>
</head>
<body>

    <header>
        <h1 style="color: #58a6ff; margin: 0;">EL NODO <small style="font-size: 0.5em; opacity: 0.6;">Soporte Tecnico</small></h1>
        <div style="margin-top: 12px; font-size: 0.85rem; opacity: 0.8;">
            Bienvenido, <strong><?php echo htmlspecialchars($nombre_usuario); ?></strong> 
            <span style="opacity: 0.5;">| Rol: <?php echo ucfirst($rol); ?></span>
        </div>
    </header>

    <nav>
        <?php if ($rol == 'profesor'): ?>
            <a href="index.php?view=registro">Cargar Pedido</a>
            <a href="index.php?view=estado" style="border-color: #2ea043;">Mis Pedidos</a>
        <?php endif; ?>

        <?php if ($rol == 'empleador'): ?>
            <a href="index.php?view=estado" style="border-color: #2ea043;">Monitor</a>
            <a href="index.php?view=panel">Panel Tecnico</a>
            <a href="index.php?view=inventario">Inventario</a>
            <a href="dashboard.php" style="border-color: #58a6ff; color: #58a6ff;">Estadisticas</a>
            <a href="index.php?view=usuarios" style="border-color: #30363d;">Usuarios</a>
        <?php endif; ?>

        <a href="logout.php" class="btn-salir">Salir</a>
    </nav>

    <main style="padding: 25px 15px; max-width: 1300px; margin: 0 auto;">
        <?php
        switch ($vista) {
            case 'registro':
                if ($rol == 'profesor') {
                    include('registrar.php');
                } else {
                    echo "<div class='card'><h2>Acceso restringido</h2><p>Solo profesores pueden reportar fallas.</p></div>";
                }
                break;

            case 'estado':
                include('estado_profesor.php');
                break;

            case 'panel':
                if ($rol == 'empleador') {
                    include('panel_tecnico.php');
                } else {
                    echo "<div class='card'><h2>Acceso Denegado</h2></div>";
                }
                break;

            case 'inventario':
                if ($rol == 'empleador') {
                    include('inventario_admin.php');
                } else {
                    echo "<div class='card'><h2>Acceso Denegado</h2><p>Area exclusiva para tecnicos.</p></div>";
                }
                break;

            case 'usuarios':
                if ($rol == 'empleador') {
                    include('usuarios.php');
                } else {
                    echo "<div class='card'><h2>Acceso Denegado</h2></div>";
                }
                break;

            case 'home':
            default:
                echo "
                <div class='card' style='text-align: center; padding: 60px 20px; border-color: #30363d;'>
                    <h2 style='color: #58a6ff; margin-bottom: 15px;'>Panel de Inicio</h2>
                    <p style='margin-top: 10px; font-size: 1.05rem;'>Hola $nombre_usuario, utiliza el menu superior para gestionar el sistema.</p>
                    <div style='margin-top: 40px; opacity: 0.4; font-size: 0.8rem;'>
                        <p>Sistema El Nodo v2.0 | Estado: Conectado</p>
                    </div>
                </div>";
                break;
        }
        ?>
    </main>

    <footer style="text-align: center; padding: 40px; opacity: 0.3; font-size: 0.8rem;">
        &copy; <?php echo date('Y'); ?> - El Nodo - Sistema de Gestion Tecnica
    </footer>

    <?php 
    // SE SEGURIZA EL AUDIO: Solo se genera el codigo de la alarma si el usuario logueado es 'empleador'
    if ($rol === 'empleador'): 
    ?>
    <script>
        // Inicializamos el objeto de sonido con el archivo de la raiz
        const sonidoAlarma = new Audio('alarma.mp3');
        sonidoAlarma.loop = true; // Bucle infinito mientras haya pendientes

        // Estado que viene desde la consulta PHP
        const alarmaActiva = <?php echo $alarma_activa ? 'true' : 'false'; ?>;

        function gestionarSirena() {
            if (alarmaActiva) {
                sonidoAlarma.play().then(() => {
                    console.log("Alarma reproduciendose en segundo plano.");
                }).catch(err => {
                    console.log("El navegador requiere un click en la interfaz para activar el audio.");
                });
            } else {
                sonidoAlarma.pause();
                sonidoAlarma.currentTime = 0;
            }
        }

        // Intenta arrancar automaticamente al cargar la pagina
        window.addEventListener('DOMContentLoaded', gestionarSirena);

        // Forzar arranque si el navegador lo bloqueo, apenas el usuario interactue con el sitio
        window.addEventListener('click', () => {
            if (alarmaActiva && sonidoAlarma.paused) {
                sonidoAlarma.play().catch(e => console.log("Error de interaccion:", e));
            }
        }, { once: true });
    </script>
    <?php 
    endif; // Fin del bloqueo de sonido para profesores 
    ?>
</body>
</html>