<?php
// modules/direccion/historial_de_correos.php

require_once '../../includes/auth.php';
require_once '../../includes/header.php';
requireRole('direccion');

// Configurar título de página
$pageTitle = "Historial de Correos";
$nombreColegio = APP_NAME;
$usuarioNombre = $_SESSION['user_name'] ?? 'Director';
$usuarioRol = 'Director';
$usuarioId = $_SESSION['user_id']; // Obtener ID del usuario logueado

// Obtener notificaciones no leídas
global $db;
$notificaciones = $db->fetchAll("
    SELECT * 
    FROM notificaciones 
    WHERE usuario_id = ? AND leida = 0
    ORDER BY fecha_envio DESC
    LIMIT 5
", [$usuarioId]);
$notificacionesNoLeidas = count($notificaciones);

// Paginación
$pagina_actual = isset($_GET['pagina']) ? (int)$_GET['pagina'] : 1;
$registros_por_pagina = 15;
$offset = ($pagina_actual - 1) * $registros_por_pagina;

// Obtener historial de correos con paginación - SOLO LOS DEL USUARIO ACTUAL
$total_registros = $db->fetchOne("SELECT COUNT(*) AS total FROM correos_enviados WHERE enviado_por = ?", [$usuarioId])['total'];
$total_paginas = ceil($total_registros / $registros_por_pagina);

$correos = $db->fetchAll("
    SELECT * 
    FROM correos_enviados 
    WHERE enviado_por = ?
    ORDER BY fecha_envio DESC 
    LIMIT $registros_por_pagina OFFSET $offset
", [$usuarioId]);
?>
<!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>
    <link href="<?= APP_URL ?>/assets/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">
    <style>
        :root {
            --primary: #2c3e50;
            --secondary: #3498db;
            --dark: #34495e;
            --light: #ecf0f1;
            --sidebar-width: 280px;
            --header-height: 70px;
            --accent: #9b59b6;
            --success: #06d6a0;
            --warning: #ffd166;
            --danger: #ef476f;
            --director-color: #9b59b6;
        }

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

        .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: 1000;
        }

        .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(--director-color);
        }

        .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(--director-color);
        }

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

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

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

        .main-content {
            flex: 1;
            margin-left: var(--sidebar-width);
            padding-bottom: 30px;
            transition: margin-left 0.3s;
        }

        .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: 900;
        }

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

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

        .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(--director-color), #8e44ad);
            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;
        }

        .footer {
            padding: 20px 30px;
            text-align: center;
            color: #7f8c8d;
            font-size: 14px;
            border-top: 1px solid #eee;
            margin-top: 30px;
            background: white;
        }

        /* Sistema de notificaciones */
        .notification-container {
            position: relative;
        }

        .notification-trigger {
            position: relative;
            cursor: pointer;
        }

        .notification-trigger i {
            font-size: 20px;
            color: var(--dark);
        }

        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background-color: var(--danger);
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }

        .notification-dropdown {
            position: absolute;
            top: 40px;
            right: 0;
            width: 400px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            display: none;
            overflow: hidden;
            transform: translateY(10px);
            opacity: 0;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }

        .notification-container.active .notification-dropdown {
            display: block;
            transform: translateY(0);
            opacity: 1;
        }

        .notification-header {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .notification-header h4 {
            margin: 0;
            font-size: 16px;
        }

        .notification-header small {
            color: var(--director-color);
            cursor: pointer;
            font-weight: 500;
        }

        .notification-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .notification-item {
            padding: 15px 20px;
            border-bottom: 1px solid #f8f9fa;
            display: flex;
            gap: 15px;
            cursor: pointer;
            transition: background 0.2s;
        }

        .notification-item:hover {
            background-color: #f8f9fa;
        }

        .notification-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: rgba(155, 89, 182, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--director-color);
            flex-shrink: 0;
        }

        .notification-content {
            flex: 1;
        }

        .notification-title {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
        }

        .notification-title strong {
            font-weight: 600;
            color: var(--dark);
        }

        .notification-title small {
            color: #95a5a6;
            font-size: 12px;
        }

        .notification-message {
            color: #7f8c8d;
            font-size: 14px;
            line-height: 1.4;
            margin-bottom: 10px;
        }

        .notification-actions {
            display: flex;
            gap: 10px;
        }

        .notification-actions a {
            padding: 5px 12px;
            background: rgba(155, 89, 182, 0.1);
            border-radius: 20px;
            color: var(--director-color);
            font-size: 13px;
            font-weight: 500;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .notification-actions a:hover {
            background: rgba(155, 89, 182, 0.2);
        }

        .notification-empty {
            padding: 30px 20px;
            text-align: center;
            color: #95a5a6;
        }

        .notification-empty i {
            font-size: 36px;
            margin-bottom: 10px;
        }

        .notification-footer {
            padding: 12px 20px;
            text-align: center;
            border-top: 1px solid #eee;
            background: #f8f9fa;
        }

        .notification-footer a {
            color: var(--director-color);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
        }

        /* ============================= */
        /* ESTILOS MEJORADOS PARA HISTORIAL */
        /* ============================= */
        .content {
            padding: 30px;
        }
        
        .history-container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            overflow: hidden;
            padding: 30px;
        }
        
        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .section-title {
            color: var(--accent);
            font-weight: 700;
            font-size: 1.6rem;
            display: flex;
            align-items: center;
            gap: 15px;
            margin: 0;
        }
        
        .section-title i {
            color: var(--accent);
            font-size: 1.8rem;
        }
        
        .history-table {
            width: 100%;
            border-collapse: collapse;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-radius: 12px;
            overflow: hidden;
        }
        
        .history-table th {
            background: #f1f5f9;
            padding: 16px 15px;
            text-align: left;
            color: var(--accent);
            font-weight: 700;
            font-size: 15px;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .history-table td {
            padding: 14px 15px;
            border-bottom: 1px solid #e9ecef;
            font-size: 14px;
            color: #495057;
        }
        
        .history-table tr:last-child td {
            border-bottom: none;
        }
        
        .history-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .history-table tr:hover {
            background-color: #edf2ff;
        }
        
        .status-badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 13px;
            display: inline-block;
        }
        
        .status-sent {
            background-color: rgba(6, 214, 160, 0.15);
            color: #06d6a0;
        }
        
        .status-error {
            background-color: rgba(239, 71, 111, 0.15);
            color: #ef476f;
        }
        
        .no-history {
            text-align: center;
            padding: 40px 20px;
            color: #6c757d;
            border: 2px dashed #e9ecef;
            border-radius: 12px;
            margin: 20px 0;
        }
        
        .no-history i {
            font-size: 48px;
            color: #dee2e6;
            margin-bottom: 15px;
        }
        
        .pagination-container {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }
        
        .pagination {
            display: flex;
            list-style: none;
            padding: 0;
            gap: 8px;
            flex-wrap: wrap;
            justify-content: center;
        }
        
        .page-item {
            display: flex;
        }
        
        .page-link {
            padding: 8px 16px;
            border-radius: 8px;
            border: 1px solid #dee2e6;
            color: var(--accent);
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s;
            display: block;
            text-align: center;
            min-width: 40px;
        }
        
        .page-link:hover {
            background-color: #e9ecef;
        }
        
        .page-item.active .page-link {
            background-color: var(--accent);
            border-color: var(--accent);
            color: white;
        }
        
        .page-item.disabled .page-link {
            color: #6c757d;
            pointer-events: none;
        }
        
        .email-details {
            max-width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .recipient-count {
            background-color: #e8f4fe;
            border-radius: 20px;
            padding: 3px 10px;
            font-size: 13px;
            font-weight: 600;
            color: var(--accent);
            display: inline-block;
            margin-left: 5px;
        }
        
        .view-details {
            color: var(--accent);
            text-decoration: none;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            white-space: nowrap;
        }
        
        .view-details:hover {
            text-decoration: underline;
        }
        
        /* Agregar estilo para el botón de volver */
        .btn-volver {
            display: inline-flex;
            align-items: center;
            padding: 8px 16px;
            background-color: #f8f9fa;
            color: #495057;
            text-decoration: none;
            border-radius: 6px;
            border: 1px solid #dee2e6;
            transition: all 0.3s;
            font-weight: 500;
        }
        
        .btn-volver:hover {
            background-color: #e9ecef;
            color: #212529;
        }
        
        /* ============================= */
        /* VERSIÓN MÓVIL - TARJETAS */
        /* ============================= */
        .mobile-history-card {
            display: none;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.06);
            margin-bottom: 20px;
            padding: 20px;
            border: 1px solid #f0f4f8;
        }
        
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        
        .card-date {
            font-weight: 600;
            color: var(--accent);
            font-size: 16px;
        }
        
        .card-status {
            font-size: 14px;
            padding: 4px 12px;
            border-radius: 20px;
        }
        
        .card-body {
            margin-bottom: 15px;
        }
        
        .card-row {
            display: flex;
            margin-bottom: 10px;
        }
        
        .card-label {
            font-weight: 600;
            min-width: 100px;
            color: var(--dark);
        }
        
        .card-value {
            flex: 1;
            color: #495057;
            word-break: break-all;
        }
        
        .card-footer {
            display: flex;
            justify-content: flex-end;
            border-top: 1px solid #eee;
            padding-top: 15px;
        }
        
        /* ============================= */
        /* RESPONSIVE DESIGN */
        /* ============================= */
        @media (max-width: 992px) {
            .sidebar {
                transform: translateX(-100%);
            }

            .sidebar.active {
                transform: translateX(0);
                box-shadow: 0 0 20px rgba(0,0,0,0.3);
            }

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

            .toggle-menu {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .history-container {
                padding: 20px 15px;
            }
            
            .section-title {
                font-size: 1.4rem;
                gap: 10px;
            }
            
            .section-title i {
                font-size: 1.5rem;
            }
            
            .history-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
            
            .history-table {
                display: none;
            }
            
            .mobile-history-card {
                display: block;
            }
            
            .header {
                padding: 0 15px;
            }
            
            .user-details {
                display: none;
            }
            
            .content {
                padding: 20px 15px;
            }
            
            .page-link {
                padding: 6px 12px;
                font-size: 14px;
            }
            
            .notification-dropdown {
                width: 320px;
                right: -20px;
            }
        }
        
        @media (max-width: 480px) {
            .section-title {
                font-size: 1.3rem;
            }
            
            .card-row {
                flex-direction: column;
                margin-bottom: 15px;
            }
            
            .card-label {
                margin-bottom: 5px;
            }
            
            .pagination {
                gap: 5px;
            }
            
            .page-link {
                padding: 6px 10px;
                min-width: 35px;
            }
            
            .notification-dropdown {
                width: 280px;
            }
        }
    </style>
</head>
<body>
    <!-- Sidebar Menu -->
    <div class="sidebar">
        <div class="logo-container">
            <div class="logo">
                <i class="fas fa-user-tie"></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/direccion/dashboard.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-home"></i>
                        <span>Menú Principal</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/direccion/notificaciones.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-inbox"></i>
                        <span>Buzón de Mensajería</span>
                    </a>
                </li>
                <li class="menu-item active">
                    <a href="<?= APP_URL ?>/modules/direccion/historial_de_correos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-history"></i>
                        <span>Historial de Comunicados</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/direccion/lista_alumnos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-chart-bar"></i>
                        <span>Lista de Alumnos</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/direccion/lista_docentes.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-chalkboard-teacher"></i>
                        <span>Personal Académico</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/direccion/usuarios.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-user-graduate"></i>
                        <span>Añadir Estudiantes</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/direccion/agregar_docente.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-chalkboard-teacher"></i>
                        <span>Añadir Docente</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/direccion/anadir_auxiliar.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-user-graduate"></i>
                        <span>Añadir Auxiliar</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/direccion/correo_administrativo.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-users"></i>
                        <span>Correo Administrativo</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/direccion/reportes.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-chart-bar"></i>
                        <span>Reportes de Asistencia</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/direccion/cambiar_contrasena.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-cog"></i>
                        <span>Cambiar de 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">
                <!-- Sistema de notificaciones -->
                <div class="notification-container" id="notificationContainer">
                    <div class="notification-trigger" id="notificationTrigger">
                        <i class="fas fa-bell"></i>
                        <?php if ($notificacionesNoLeidas > 0): ?>
                            <div class="notification-badge"><?= $notificacionesNoLeidas ?></div>
                        <?php endif; ?>
                    </div>

                    <div class="notification-dropdown">
                        <div class="notification-header">
                            <h4>Notificaciones</h4>
                            <small id="markAllAsRead">Marcar todas como leídas</small>
                        </div>
                        <div class="notification-list">
                            <?php if ($notificacionesNoLeidas > 0): ?>
                                <?php foreach ($notificaciones as $notif): ?>
                                    <div class="notification-item" 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 H:i', strtotime($notif['fecha_envio'])) ?></small>
                                            </div>
                                            <div class="notification-message">
                                                <?= htmlspecialchars($notif['mensaje']) ?>
                                            </div>
                                            <div class="notification-actions">
                                                <a href="<?= APP_URL ?>/modules/direccion/ver_correo.php?id=<?= $notif['id'] ?>">
                                                    <i class="fas fa-eye"></i> Ver
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="notification-empty">
                                    <i class="fas fa-inbox"></i>
                                    <p>No tienes notificaciones nuevas</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="notification-footer">
                            <a href="notificaciones.php">Ver todas las notificaciones</a>
                        </div>
                    </div>
                </div>

                <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="history-container">
                
                <div class="history-header">
                    <h2 class="section-title"><i class="fas fa-history"></i> Historial de Comunicados Enviados</h2>
                    
                    <div class="history-info">
                        <span class="badge bg-primary">Total: <?= $total_registros ?></span>
                    </div>
                    <div class="content-header">
                        <a href="<?= APP_URL ?>/modules/direccion/dashboard.php" class="btn-volver">
                            <i class="fas fa-arrow-left me-2"></i> Volver al Menú
                        </a>
                    </div>
                </div>
                
                <?php if (!empty($correos)): ?>
                    <!-- Tabla para escritorio -->
                    <div class="table-responsive">
                        <table class="history-table">
                            <thead>
                                <tr>
                                    <th>Fecha</th>
                                    <th>Asunto</th>
                                    <th>Destinatarios</th>
                                    <th>Estado</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($correos as $correo): 
                                    $destinatarios = explode(',', $correo['destinatarios']);
                                    $total_destinatarios = count($destinatarios);
                                ?>
                                    <tr>
                                        <td><?= date('d/m/Y H:i', strtotime($correo['fecha_envio'])) ?></td>
                                        <td class="email-details"><?= htmlspecialchars($correo['asunto']) ?></td>
                                        <td>
                                            <div class="email-details">
                                                <?= htmlspecialchars($destinatarios[0]) ?>
                                                <?php if ($total_destinatarios > 1): ?>
                                                    <span class="recipient-count">+<?= $total_destinatarios - 1 ?> más</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="status-badge <?= $correo['estado'] === 'enviado' ? 'status-sent' : 'status-error' ?>">
                                                <?= ucfirst($correo['estado']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <!-- Enlace a detalles con ID del correo -->
                                            <a href="detalles_de_correo_enviado.php?id=<?= $correo['id'] ?>" class="view-details">
                                                <i class="fas fa-eye"></i> Detalles
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Tarjetas para móvil -->
                    <div class="mobile-history-list">
                        <?php foreach ($correos as $correo): 
                            $destinatarios = explode(',', $correo['destinatarios']);
                            $total_destinatarios = count($destinatarios);
                            $status_class = $correo['estado'] === 'enviado' ? 'status-sent' : 'status-error';
                        ?>
                            <div class="mobile-history-card">
                                <div class="card-header">
                                    <div class="card-date"><?= date('d/m/Y H:i', strtotime($correo['fecha_envio'])) ?></div>
                                    <div class="card-status <?= $status_class ?>"><?= ucfirst($correo['estado']) ?></div>
                                </div>
                                <div class="card-body">
                                    <div class="card-row">
                                        <div class="card-label">Asunto:</div>
                                        <div class="card-value"><?= htmlspecialchars($correo['asunto']) ?></div>
                                    </div>
                                    <div class="card-row">
                                        <div class="card-label">Destinatarios:</div>
                                        <div class="card-value">
                                            <?= htmlspecialchars($destinatarios[0]) ?>
                                            <?php if ($total_destinatarios > 1): ?>
                                                <span class="recipient-count">+<?= $total_destinatarios - 1 ?> más</span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-footer">
                                    <!-- Enlace a detalles con ID del correo -->
                                    <a href="detalles_de_correo_enviado.php?id=<?= $correo['id'] ?>" class="view-details">
                                        <i class="fas fa-eye"></i> Ver detalles
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <!-- Paginación -->
                    <?php if ($total_paginas > 1): ?>
                        <div class="pagination-container">
                            <ul class="pagination">
                                <?php if ($pagina_actual > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?pagina=<?= $pagina_actual - 1 ?>">
                                            <i class="fas fa-chevron-left"></i>
                                        </a>
                                    </li>
                                <?php endif; ?>
                                
                                <?php 
                                // Calcular rango de páginas a mostrar
                                $inicio = max(1, $pagina_actual - 2);
                                $fin = min($total_paginas, $pagina_actual + 2);
                                
                                // Mostrar primera página si no está en el rango
                                if ($inicio > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?pagina=1">1</a>
                                    </li>
                                    <?php if ($inicio > 2): ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">...</span>
                                        </li>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <?php for ($i = $inicio; $i <= $fin; $i++): ?>
                                    <li class="page-item <?= $i === $pagina_actual ? 'active' : '' ?>">
                                        <a class="page-link" href="?pagina=<?= $i ?>"><?= $i ?></a>
                                    </li>
                                <?php endfor; ?>
                                
                                <?php if ($fin < $total_paginas): ?>
                                    <?php if ($fin < $total_paginas - 1): ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">...</span>
                                        </li>
                                    <?php endif; ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?pagina=<?= $total_paginas ?>"><?= $total_paginas ?></a>
                                    </li>
                                <?php endif; ?>
                                
                                <?php if ($pagina_actual < $total_paginas): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?pagina=<?= $pagina_actual + 1 ?>">
                                            <i class="fas fa-chevron-right"></i>
                                        </a>
                                    </li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="no-history">
                        <i class="fas fa-inbox"></i>
                        <h4>No hay registros de comunicados enviados</h4>
                        <p>Los comunicados que envíes aparecerán en este historial</p>
                        <a href="<?= APP_URL ?>/modules/direccion/correo_administrativo.php" class="btn btn-primary mt-3">
                            <i class="fas fa-envelope me-2"></i> Enviar primer comunicado
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

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

    <!-- Bootstrap JS -->
    <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');
        });
        
        // Cerrar sidebar al hacer clic fuera
        document.addEventListener('click', function(event) {
            const sidebar = document.querySelector('.sidebar');
            const toggleMenu = document.querySelector('.toggle-menu');
            
            // Si el clic fue fuera del sidebar y el menú está abierto
            if (sidebar.classList.contains('active') && 
                !sidebar.contains(event.target) && 
                !toggleMenu.contains(event.target)) {
                sidebar.classList.remove('active');
            }
        });
        
        // Prevenir cierre al hacer clic dentro del sidebar
        document.querySelector('.sidebar').addEventListener('click', function(event) {
            event.stopPropagation();
        });

        // Sistema de notificaciones
        document.addEventListener('DOMContentLoaded', function() {
            const notificationContainer = document.getElementById('notificationContainer');
            const notificationTrigger = document.getElementById('notificationTrigger');
            const notificationDropdown = notificationContainer.querySelector('.notification-dropdown');

            // Abrir/cerrar menú de notificaciones
            notificationTrigger.addEventListener('click', function(e) {
                e.stopPropagation();
                notificationContainer.classList.toggle('active');
            });

            // Cerrar menú al hacer clic fuera
            document.addEventListener('click', function(e) {
                if (!notificationContainer.contains(e.target)) {
                    notificationContainer.classList.remove('active');
                }
            });

            // Prevenir cierre al hacer clic dentro del menú
            notificationDropdown.addEventListener('click', function(e) {
                e.stopPropagation();
            });

            // Marcar notificación como leída
            document.querySelectorAll('.notification-item').forEach(item => {
                item.addEventListener('click', function() {
                    const notifId = this.getAttribute('data-id');

                    // Enviar solicitud AJAX para marcar como leída
                    fetch('marcar_leida.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                id: notifId
                            })
                        }).then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                this.style.opacity = '0.7';
                                // Actualizar contador
                                const badge = document.querySelector('.notification-badge');
                                if (badge) {
                                    badge.textContent = parseInt(badge.textContent) - 1;
                                    if (parseInt(badge.textContent) === 0) {
                                        badge.style.display = 'none';
                                    }
                                }
                            }
                        });
                });
            });

            // Marcar todas como leídas
            const markAllAsRead = document.getElementById('markAllAsRead');
            if (markAllAsRead) {
                markAllAsRead.addEventListener('click', function(e) {
                    e.stopPropagation();

                    // Enviar solicitud AJAX para marcar todas como leídas
                    fetch('marcar_todas_leidas.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                usuario_id: <?= $usuarioId ?>
                            })
                        }).then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Actualizar la interfaz
                                document.querySelectorAll('.notification-item').forEach(item => {
                                    item.style.opacity = '0.7';
                                });

                                const badge = document.querySelector('.notification-badge');
                                if (badge) {
                                    badge.style.display = 'none';
                                }
                            }
                        });
                });
            }
        });
    </script>
</body>
</html>