<?php
// modules/auxiliar/notificaciones.php
require_once '../../includes/auth.php';
require_once __DIR__ . '/../../includes/database.php';
require_once '../../includes/header.php';
requireRole('auxiliar');

// Obtener datos del usuario desde la sesión
$nombreColegio = APP_NAME;
$usuarioNombre = $_SESSION['user_name'] ?? 'Auxiliar';
$usuarioId = $_SESSION['user_id'] ?? 0;
$usuarioRol = 'Auxiliar';

// Obtener todas las notificaciones del usuario
global $db;
$notificaciones = $db->fetchAll("
    SELECT * 
    FROM notificaciones 
    WHERE usuario_id = ?
    ORDER BY fecha_envio DESC
", [$usuarioId]);

// Configurar título de página
$pageTitle = "Buzón de Mensajería";
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?> - <?= $nombreColegio ?></title>
    
    <!-- Cargar Font Awesome desde CDN -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Cargar Bootstrap CSS local -->
    <link href="<?= APP_URL ?>/assets/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Estilos personalizados -->
    <style>
        :root {
            --primary: #2c3e50;
            --secondary: #3498db;
            --accent: #e74c3c;
            --light: #ecf0f1;
            --dark: #34495e;
            --success: #2ecc71;
            --warning: #f39c12;
            --sidebar-width: 280px;
            --header-height: 70px;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            display: flex;
            min-height: 100vh;
            margin: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        /* Sidebar */
        .sidebar {
            width: var(--sidebar-width);
            background: linear-gradient(to bottom, var(--primary), var(--dark));
            color: white;
            height: 100vh;
            position: fixed;
            overflow-y: auto;
            transition: all 0.3s ease;
            box-shadow: 3px 0 15px rgba(0, 0, 0, 0.1);
            z-index: 100;
        }

        .logo-container {
            padding: 20px 25px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            background-color: rgba(0, 0, 0, 0.1);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .logo i {
            font-size: 28px;
            color: var(--secondary);
        }

        .logo h1 {
            font-size: 22px;
            font-weight: 600;
        }

        .menu-section {
            padding: 25px 0;
        }

        .menu-title {
            padding: 0 25px 10px;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: rgba(255, 255, 255, 0.6);
            font-weight: 500;
        }

        .menu-items {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .menu-item {
            padding: 12px 25px;
            display: flex;
            align-items: center;
            gap: 15px;
            cursor: pointer;
            transition: all 0.2s ease;
            border-left: 4px solid transparent;
            position: relative;
        }

        .menu-item:hover {
            background-color: rgba(255, 255, 255, 0.05);
            border-left-color: var(--secondary);
        }

        .menu-item.active {
            background-color: rgba(255, 255, 255, 0.1);
            border-left-color: var(--secondary);
        }

        .menu-item i {
            width: 24px;
            text-align: center;
            font-size: 18px;
            color: var(--secondary);
        }

        .menu-item span {
            font-size: 16px;
            font-weight: 500;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            padding-bottom: 30px;
        }

        /* Header */
        .header {
            height: var(--header-height);
            background-color: white;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            position: sticky;
            top: 0;
            z-index: 90;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .toggle-menu {
            display: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--dark);
        }

        .search-bar {
            position: relative;
        }

        .search-bar input {
            padding: 10px 15px 10px 40px;
            border-radius: 30px;
            border: 1px solid #ddd;
            width: 300px;
            transition: all 0.3s ease;
        }

        .search-bar input:focus {
            outline: none;
            border-color: var(--secondary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        .search-bar i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #95a5a6;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 25px;
        }

        .user-profile {
            position: relative;
            cursor: pointer;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--secondary), var(--primary));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 18px;
        }

        .user-details {
            display: flex;
            flex-direction: column;
        }

        .user-name {
            font-weight: 600;
            font-size: 15px;
        }

        .user-role {
            font-size: 13px;
            color: #7f8c8d;
        }

        /* Content Area */
        .content {
            padding: 30px;
        }

        /* ----------------------- */
        /* ESTILOS DE NOTIFICACIONES */
        /* ----------------------- */
        .notifications-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .notifications-header {
            padding: 25px 30px;
            background: linear-gradient(135deg, var(--primary), var(--dark));
            color: white;
        }
        
        .notifications-header h1 {
            font-size: 1.8rem;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .mark-all-btn {
            display: inline-block;
            margin-top: 15px;
            padding: 10px 20px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            border-radius: 30px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
        }
        
        .mark-all-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .notification-item {
            padding: 20px;
            border-bottom: 1px solid #f1f2f6;
            display: flex;
            gap: 20px;
            transition: all 0.3s;
        }
        
        .notification-item:hover {
            background-color: #f8f9fa;
        }
        
        .notification-item:last-child {
            border-bottom: none;
        }
        
        .notification-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: rgba(52, 152, 219, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--secondary);
            font-size: 20px;
            flex-shrink: 0;
        }
        
        .notification-content {
            flex: 1;
        }
        
        .notification-title {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        
        .notification-title strong {
            font-weight: 600;
            color: var(--dark);
            font-size: 1.1rem;
        }
        
        .notification-title small {
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        
        .notification-message {
            color: #555;
            margin-bottom: 15px;
            line-height: 1.6;
        }
        
        .notification-actions {
            display: flex;
            gap: 15px;
        }
        
        .notification-actions a {
            padding: 8px 16px;
            background: rgba(52, 152, 219, 0.1);
            border-radius: 30px;
            color: var(--secondary);
            text-decoration: none;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .notification-actions a:hover {
            background: rgba(52, 152, 219, 0.2);
        }
        
        .notification-item.unread {
            background-color: #f0f8ff;
            border-left: 4px solid var(--secondary);
        }
        
        .empty-notifications {
            text-align: center;
            padding: 50px 20px;
            color: #7f8c8d;
        }
        
        .empty-notifications i {
            font-size: 3.5rem;
            margin-bottom: 15px;
            color: #bdc3c7;
        }
        
        .empty-notifications h3 {
            font-size: 1.5rem;
            margin-bottom: 10px;
            color: var(--dark);
        }
        
        .empty-notifications p {
            max-width: 500px;
            margin: 0 auto;
        }
        
        /* Botón Volver */
        .btn-volver {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            padding: 12px 25px;
            background: linear-gradient(135deg, var(--primary), var(--dark));
            color: white;
            border: none;
            border-radius: 30px;
            font-weight: 600;
            font-size: 16px;
            text-decoration: none;
            box-shadow: 0 4px 15px rgba(44, 62, 80, 0.3);
            transition: all 0.3s ease;
            margin-top: 15px;
            cursor: pointer;
        }
        
        .btn-volver:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(44, 62, 80, 0.4);
            text-decoration: none;
            color: white;
        }
        
        .btn-volver i {
            font-size: 18px;
        }
        
        /* Footer */
        .footer {
            padding: 20px 30px;
            text-align: center;
            color: #7f8c8d;
            font-size: 14px;
            border-top: 1px solid #eee;
            margin-top: 30px;
        }

        /* Responsive Design */
        @media (max-width: 992px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .toggle-menu {
                display: block;
            }

            .search-bar input {
                width: 200px;
            }
        }

        @media (max-width: 768px) {
            .search-bar {
                display: none;
            }

            .notification-title {
                flex-direction: column;
                gap: 5px;
            }
            
            .notification-actions {
                flex-direction: column;
                gap: 10px;
            }
            
            .notification-actions a {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar Menu -->
    <div class="sidebar">
        <div class="logo-container">
            <div class="logo">
                <i class="fas fa-graduation-cap"></i>
                <h1><?= $nombreColegio ?></h1>
            </div>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Principal</h3>
            <ul class="menu-items">
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/dashboard.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-home"></i>
                        <span>Menu</span>
                    </a>
                </li>
                <li class="menu-item active">
                    <a href="<?= APP_URL ?>/modules/auxiliar/notificaciones.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-inbox"></i>
                        <span>Buzón de Mensajería</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Funciones</h3>
            <ul class="menu-items">
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/asistencia.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-clipboard-check"></i>
                        <span>Tomar Asistencia</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/lista_alumnos.php?action=new" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-newspaper"></i>
                        <span>Lista de Almunos</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/correos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-envelope"></i>
                        <span>Enviar Comunicados</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/historial_de_correos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-history"></i>
                        <span>Historial de Comunicados</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/correo_administrativo.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-users"></i>
                        <span>Correo Administrativo</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Administración</h3>
            <ul class="menu-items">
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/cambiar_contrasena.php" style="display: block; color: inherit; text-decoration: none;">
                        <i class="fas fa-key"></i>
                        <span>Cambiar Contraseña</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/auth/logout.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>Cerrar Sesión</span>
                    </a>
                </li>
            </ul>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <header class="header">
            <div class="header-left">
                <div class="toggle-menu">
                    <i class="fas fa-bars"></i>
                </div>
                
            </div>

            <div class="header-right">
                <div class="user-profile">
                    <div class="user-info">
                        <div class="user-avatar"><?= substr($usuarioNombre, 0, 1) . (strpos($usuarioNombre, ' ') !== false ? substr($usuarioNombre, strpos($usuarioNombre, ' ') + 1, 1) : '') ?></div>
                        <div class="user-details">
                            <div class="user-name"><?= $usuarioNombre ?></div>
                            <div class="user-role"><?= $usuarioRol ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Content Area -->
        <div class="content">
            <div class="notifications-container">
                <div class="notifications-header">
                    <h1>
                        <i class="fas fa-inbox"></i>
                        Buzón de Mensajería
                    </h1>
                    <?php if (!empty($notificaciones)): ?>
                        <button class="mark-all-btn" id="markAllAsReadPage">
                            <i class="fas fa-check-circle"></i> Marcar todas como leídas
                        </button>
                    <?php endif; ?>
                </div>
                
                <div class="notifications-content">
                    <?php if (!empty($notificaciones)): ?>
                        <?php foreach ($notificaciones as $notif): 
                            // Extraer parámetros y construir enlace correcto
                            $params = [];
                            $query_string = parse_url($notif['enlace'], PHP_URL_QUERY);
                            if ($query_string) {
                                parse_str($query_string, $params);
                            }
                            $correo_id = $params['correo_id'] ?? $params['id'] ?? 0;
                            
                            // Construir enlace para ver el mensaje
                            $ver_enlace = APP_URL . "/modules/auxiliar/ver_correo.php?id=" . $correo_id;
                        ?>
                            <div class="notification-item <?= $notif['leida'] ? '' : 'unread' ?>" data-id="<?= $notif['id'] ?>">
                                <div class="notification-icon">
                                    <i class="fas fa-envelope"></i>
                                </div>
                                <div class="notification-content">
                                    <div class="notification-title">
                                        <strong><?= htmlspecialchars($notif['titulo']) ?></strong>
                                        <small><?= date('d M Y H:i', strtotime($notif['fecha_envio'])) ?></small>
                                    </div>
                                    <div class="notification-message">
                                        <?= htmlspecialchars($notif['mensaje']) ?>
                                    </div>
                                    <div class="notification-actions">
                                        <?php if ($correo_id): ?>
                                            <a href="<?= $ver_enlace ?>">
                                                <i class="fas fa-eye"></i> Ver detalles
                                            </a>
                                        <?php endif; ?>
                                        <?php if (!$notif['leida']): ?>
                                            <a href="#" class="mark-as-read" data-id="<?= $notif['id'] ?>">
                                                <i class="fas fa-check"></i> Marcar como leída
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="empty-notifications">
                            <i class="fas fa-inbox"></i>
                            <h3>No tienes mensajes</h3>
                            <p>Tu bandeja de entrada está vacía.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div style="text-align: center;">
                <a href="<?= APP_URL ?>/modules/auxiliar/dashboard.php" class="btn-volver">
                    <i class="fas fa-arrow-left"></i> VOLVER AL MENÚ PRINCIPAL
                </a>
            </div>
        </div>

        <!-- Footer -->
        <footer class="footer">
            <p>Sistema Escolar Integrado v3.0 © <?= date('Y') ?> - Todos los derechos reservados</p>
        </footer>
    </div>

    <script src="<?= APP_URL ?>/assets/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle sidebar on mobile
        document.querySelector('.toggle-menu')?.addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('active');
        });

        // Marcar notificación como leída
        document.querySelectorAll('.mark-as-read').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const notifId = this.getAttribute('data-id');
                
                // Crear formulario para enviar la solicitud
                const formData = new FormData();
                formData.append('id', notifId);
                
                fetch('marcar_leida.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const item = this.closest('.notification-item');
                        item.classList.remove('unread');
                        this.remove();
                    }
                })
                .catch(error => console.error('Error:', error));
            });
        });
        
        // Marcar todas como leídas
        document.getElementById('markAllAsReadPage').addEventListener('click', function(e) {
            e.preventDefault();
            
            // Crear formulario para enviar la solicitud
            const formData = new FormData();
            formData.append('usuario_id', <?= $usuarioId ?>);
            
            fetch('marcar_todas_leidas.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.querySelectorAll('.notification-item').forEach(item => {
                        item.classList.remove('unread');
                    });
                    
                    document.querySelectorAll('.mark-as-read').forEach(btn => {
                        btn.remove();
                    });
                }
            })
            .catch(error => console.error('Error:', error));
        });
    </script>
</body>
</html>