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

// Asegurar CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$success = $_SESSION['success'] ?? null;
$error = $_SESSION['error'] ?? null;
unset($_SESSION['success'], $_SESSION['error']);

// Obtener email del auxiliar para usar como remitente
global $db;
$usuario_email = $_SESSION['user_email'] ?? '';
if (empty($usuario_email)) {
    $user_data = $db->fetchOne("SELECT email FROM usuarios WHERE id = ?", [$_SESSION['user_id']]);
    $usuario_email = $user_data['email'] ?? 'no-reply@micole.edu';
    $_SESSION['user_email'] = $usuario_email;
}

// Obtener grupos disponibles (niveles, grados, secciones) en una sola consulta
$grupos = $db->fetchAll("
    SELECT DISTINCT s.nivel, s.grado, s.id as seccion_id, s.seccion
    FROM secciones s
    JOIN estudiantes e ON s.nivel = e.nivel AND s.grado = e.grado AND s.seccion = e.seccion
    ORDER BY s.nivel, CAST(s.grado AS UNSIGNED), s.seccion
");

// Procesar para crear estructura optimizada
$niveles = [];
$gradosPorNivel = [];
$seccionesPorGrado = [];
foreach ($grupos as $grupo) {
    $nivel = $grupo['nivel'];
    $grado = $grupo['grado'];
    if (!in_array($nivel, $niveles)) {
        $niveles[] = $nivel;
    }
    if (!isset($gradosPorNivel[$nivel]) || !in_array($grado, $gradosPorNivel[$nivel])) {
        $gradosPorNivel[$nivel][] = $grado;
    }
    $seccionesPorGrado[$nivel][$grado][] = [
        'id' => $grupo['seccion_id'],
        'seccion' => $grupo['seccion']
    ];
}

// Variables para datos filtrados
$secciones = [];
$estudiantes = [];
$destinatarios = [];
$filtro_valido = false;

// Procesamiento de filtros
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['filtro'])) {
    $filtro = $_GET['filtro'];
    if (!empty($filtro['nivel']) && !empty($filtro['grado']) && !empty($filtro['seccion_id'])) {
        $filtro_valido = true;
        $nivel = $filtro['nivel'];
        $grado = $filtro['grado'];
        $seccion_id = $filtro['seccion_id'];

        $seccion_seleccionada = $db->fetchOne("
            SELECT nivel, grado, seccion 
            FROM secciones 
            WHERE id = ?
        ", [$seccion_id]);

        if ($seccion_seleccionada) {
            $estudiantes = $db->fetchAll("
                SELECT e.id, u.nombre AS nombres, u.apellido, u.email 
                FROM estudiantes e
                JOIN usuarios u ON e.usuario_id = u.id
                WHERE e.nivel = ? 
                AND e.grado = ? 
                AND e.seccion = ?
                ORDER BY u.apellido, u.nombre
            ", [
                $seccion_seleccionada['nivel'],
                $seccion_seleccionada['grado'],
                $seccion_seleccionada['seccion']
            ]);

            foreach ($estudiantes as $est) {
                $destinatarios[] = $est['email'];
            }
        }
    }
}

// Obtener historial de correos
$correos = $db->fetchAll("SELECT * FROM correos_enviados ORDER BY fecha_envio DESC LIMIT 10");

// Configurar título de página
$pageTitle = "Enviar Correo Electrónico";
$nombreColegio = APP_NAME;
$usuarioNombre = $_SESSION['user_name'] ?? 'Auxiliar';
$usuarioRol = 'Auxiliar';

// Determinar estado de los selects
$gradoDisabled = empty($_GET['filtro']['nivel']);
$seccionDisabled = empty($_GET['filtro']['grado']) || $gradoDisabled;
?>

<!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: #4361ee;
            --success: #06d6a0;
            --warning: #ffd166;
            --danger: #ef476f;
        }
        body {
            background-color: #f5f7fa;
            color: #333;
            display: flex;
            min-height: 100vh;
            margin: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .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;
        }
        /* Footer */
        .footer {
            padding: 20px 30px;
            text-align: center;
            color: #7f8c8d;
            font-size: 14px;
            border-top: 1px solid #eee;
            margin-top: 30px;
            background: white;
        }
        /* ============================= */
        /* ESTILOS MEJORADOS PARA CORREOS */
        /* ============================= */
        .content {
            padding: 30px;
        }
        .email-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;
        }
        .email-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }
        @media (max-width: 992px) {
            .email-content {
                grid-template-columns: 1fr;
            }
        }
        .form-section, .history-section {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.06);
            padding: 30px;
            border: 1px solid #f0f4f8;
        }
        .section-title {
            color: var(--accent);
            font-weight: 700;
            font-size: 1.6rem;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 15px;
            padding-bottom: 15px;
            border-bottom: 3px solid #f0f4f8;
        }
        .section-title i {
            color: var(--accent);
            font-size: 1.8rem;
        }
        .form-label {
            font-weight: 600;
            color: #212529;
            margin-bottom: 10px;
            font-size: 1.05rem;
            display: block;
        }
        .form-control, .form-select {
            border: 2px solid #e0e6ef;
            border-radius: 10px;
            padding: 14px 18px;
            transition: all 0.3s;
            font-size: 1.05rem;
            width: 100%;
            background: #f8fafc;
        }
        .form-control:focus, .form-select:focus {
            border-color: var(--accent);
            box-shadow: 0 0 0 4px rgba(67, 97, 238, 0.2);
            outline: none;
            background: white;
        }
        .btn-send {
            background: linear-gradient(135deg, var(--accent), #3a56d4);
            border: none;
            padding: 16px 32px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s;
            font-size: 1.1rem;
            color: white;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
            margin-top: 20px;
        }
        .btn-send:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(67, 97, 238, 0.4);
        }
        .filter-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin-bottom: 25px;
        }
        @media (max-width: 768px) {
            .filter-grid {
                grid-template-columns: 1fr;
            }
        }
        .filter-group {
            margin-bottom: 5px;
        }
        .filter-btn {
            grid-column: span 3;
            display: flex;
            justify-content: flex-end;
        }
        @media (max-width: 768px) {
            .filter-btn {
                grid-column: span 1;
            }
        }
        .btn-filter {
            background: linear-gradient(135deg, #06d6a0, #05b388);
            border: none;
            padding: 14px 25px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s;
            color: white;
            display: inline-flex;
            align-items: center;
            gap: 10px;
        }
        .btn-filter:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(6, 214, 160, 0.4);
        }
        .student-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 10px;
            padding: 15px;
            margin: 20px 0;
        }
        .student-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 10px;
        }
        .student-item:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        .student-info {
            flex: 1;
        }
        .student-name {
            font-weight: 600;
            color: #212529;
        }
        .student-email {
            font-size: 14px;
            color: #6c757d;
        }
        .recipients-box {
            background: #e8f4fe;
            border-radius: 10px;
            padding: 20px;
            margin: 25px 0;
            border-left: 4px solid var(--accent);
        }
        .recipients-box h5 {
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--accent);
            margin-bottom: 15px;
        }
        .recipients-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .recipient-tag {
            background: white;
            border-radius: 20px;
            padding: 8px 16px;
            display: inline-flex;
            align-items: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            font-size: 14px;
            font-weight: 500;
        }
        .subject-group {
            margin: 25px 0;
        }
        .message-group {
            margin-bottom: 25px;
        }
        .message-group textarea {
            min-height: 200px;
            resize: vertical;
        }
        .info-note {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-top: 15px;
            font-size: 15px;
            color: #6c757d;
            border: 1px solid #e9ecef;
        }
        .info-note strong {
            color: var(--accent);
        }
        .action-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 25px;
        }
        .copy-note {
            font-size: 14px;
            color: #6c757d;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .history-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-radius: 10px;
            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-top: 20px;
        }
        .no-history i {
            font-size: 48px;
            color: #dee2e6;
            margin-bottom: 15px;
        }
        .no-students {
            text-align: center;
            padding: 30px 20px;
            color: #6c757d;
            border: 2px dashed #e9ecef;
            border-radius: 12px;
            margin: 20px 0;
        }
        .no-students i {
            font-size: 36px;
            color: #dee2e6;
            margin-bottom: 10px;
        }
        .alert {
            border-radius: 12px;
            padding: 18px 22px;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            gap: 18px;
            font-size: 1.1rem;
        }
        .alert i {
            font-size: 1.8rem;
        }
        .alert-warning {
            background-color: #fff3cd;
            border-color: #ffeeba;
            color: #856404;
        }
        .alert-success {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        .alert-danger {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        /* 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;
            }
            .email-content {
                padding: 20px;
            }
            .form-section, .history-section {
                padding: 20px;
            }
            .section-title {
                font-size: 1.4rem;
            }
        }
        /* Nuevo estilo para botón Volver */
        .btn-volver {
            background: linear-gradient(135deg, #6c757d, #5a6268);
            border: none;
            padding: 12px 25px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s;
            color: white;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
            text-decoration: none;
        }
        .btn-volver:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(108, 117, 125, 0.4);
            color: white;
        }
        .content-header {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
        }
        /* Estilo para selects deshabilitados */
        .form-select:disabled {
            background-color: #f8f9fa;
            opacity: 0.7;
            cursor: not-allowed;
        }
    </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">
                    <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 Alumnos</span>
                    </a>
                </li>
                <li class="menu-item active">
                    <a href="<?= APP_URL ?>/modules/auxiliar/correos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-envelope"></i>
                        <span>Enviar Comunicado</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="email-container">
                <!-- Sección de formulario -->
                <div class="form-section">
                    <div class="content-header">
                        <a href="<?= APP_URL ?>/modules/auxiliar/dashboard.php" class="btn-volver">
                            <i class="fas fa-arrow-left me-2"></i> Volver al Menú
                        </a>
                    </div>
                    <h2 class="section-title"><i class="fas fa-paper-plane"></i> Enviar Comunicado</h2>
                    <?php if ($success): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i> <?= $success ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle me-2"></i> <?= $error ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    <form method="GET" id="filterForm">
                        <div class="filter-grid">
                            <div class="filter-group">
                                <label class="form-label">Nivel</label>
                                <select class="form-select" name="filtro[nivel]" id="nivel" required>
                                    <option value="">Seleccionar Nivel</option>
                                    <?php foreach ($niveles as $nivel): ?>
                                        <option value="<?= $nivel ?>" 
                                            <?= isset($_GET['filtro']['nivel']) && $_GET['filtro']['nivel'] == $nivel ? 'selected' : '' ?>>
                                            <?= htmlspecialchars(ucfirst($nivel)) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="filter-group">
                                <label class="form-label">Grado</label>
                                <select class="form-select" name="filtro[grado]" id="grado" <?= $gradoDisabled ? 'disabled' : '' ?> required>
                                    <option value="">Seleccionar Grado</option>
                                    <?php if (isset($_GET['filtro']['nivel']) && isset($gradosPorNivel[$_GET['filtro']['nivel']])): ?>
                                        <?php foreach ($gradosPorNivel[$_GET['filtro']['nivel']] as $grado): ?>
                                            <option value="<?= $grado ?>" 
                                                <?= isset($_GET['filtro']['grado']) && $_GET['filtro']['grado'] == $grado ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($grado) ?>° Grado
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="filter-group">
                                <label class="form-label">Sección</label>
                                <select class="form-select" name="filtro[seccion_id]" id="seccion" <?= $seccionDisabled ? 'disabled' : '' ?> required>
                                    <option value="">Seleccionar Sección</option>
                                    <?php if (isset($_GET['filtro']['nivel']) && isset($_GET['filtro']['grado']) && isset($seccionesPorGrado[$_GET['filtro']['nivel']][$_GET['filtro']['grado']])): ?>
                                        <?php foreach ($seccionesPorGrado[$_GET['filtro']['nivel']][$_GET['filtro']['grado']] as $seccion): ?>
                                            <option value="<?= $seccion['id'] ?>" 
                                                <?= isset($_GET['filtro']['seccion_id']) && $_GET['filtro']['seccion_id'] == $seccion['id'] ? 'selected' : '' ?>>
                                                Sección <?= htmlspecialchars($seccion['seccion']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                            </div>
                            <div class="filter-btn">
                                <button type="submit" class="btn btn-filter">
                                    <i class="fas fa-filter me-2"></i> Aplicar Filtros
                                </button>
                            </div>
                        </div>
                    </form>
                    <?php if ($filtro_valido && !empty($estudiantes)): ?>
                        <div class="student-list">
                            <h4 class="mb-3"><i class="fas fa-user-graduate me-2"></i> Estudiantes de la Sección</h4>
                            <?php foreach ($estudiantes as $estudiante): ?>
                                <div class="student-item">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" 
                                               name="estudiantes[]" value="<?= $estudiante['email'] ?>" 
                                               id="est<?= $estudiante['id'] ?>" checked>
                                        <label class="form-check-label w-100" for="est<?= $estudiante['id'] ?>">
                                            <div class="student-info">
                                                <div class="student-name"><?= htmlspecialchars($estudiante['nombres'] . ' ' . $estudiante['apellido']) ?></div>
                                                <div class="student-email"><?= htmlspecialchars($estudiante['email']) ?></div>
                                            </div>
                                        </label>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif ($filtro_valido && empty($estudiantes)): ?>
                        <div class="no-students">
                            <i class="fas fa-user-graduate"></i>
                            <h5>No se encontraron estudiantes</h5>
                            <p>No hay estudiantes registrados en esta sección</p>
                        </div>
                    <?php endif; ?>
                    <!-- Formulario de envío de correo -->
                    <?php if (!empty($estudiantes)): ?>
                    <form method="POST" action="send_email_handler.php" enctype="multipart/form-data" id="emailForm">
                        <!-- CSRF Token -->
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

                        <!-- Destinatarios seleccionados -->
                        <div class="recipients-box">
                            <h5><i class="fas fa-users me-2"></i> Destinatarios seleccionados</h5>
                            <div class="recipients-tags" id="recipientsTags">
                                <?php foreach ($estudiantes as $estudiante): ?>
                                    <span class="recipient-tag">
                                        <?= htmlspecialchars($estudiante['email']) ?>
                                    </span>
                                <?php endforeach; ?>
                            </div>
                            <input type="hidden" name="to" value="<?= implode(',', $destinatarios) ?>">
                            <!-- Campos adicionales requeridos por la BD -->
                            <input type="hidden" name="remitente" value="<?= $usuario_email ?>">
                            <input type="hidden" name="destinatario" value="<?= $destinatarios[0] ?? '' ?>">
                        </div>

                        <div class="subject-group">
                            <label for="subject" class="form-label">Asunto</label>
                            <input type="text" class="form-control" id="subject" name="subject" required
                                   placeholder="Asunto del correo" value="Comunicado de <?= htmlspecialchars($_SESSION['user_name'] ?? 'Auxiliar') ?>">
                        </div>
                        <div class="message-group">
                            <label for="message" class="form-label">Mensaje</label>
                            <textarea class="form-control" id="message" name="message" rows="8" required
                                      placeholder="Escribe tu mensaje aquí..."></textarea>
                        </div>
                        <div class="info-note">
                            <i class="fas fa-info-circle me-2"></i> 
                            Tu nombre (<strong><?= htmlspecialchars($_SESSION['user_name'] ?? 'Auxiliar') ?></strong>) 
                            se agregará automáticamente al final del mensaje
                        </div>
                        <button type="submit" class="btn-send">
                            <i class="fas fa-paper-plane me-2"></i> Enviar Comunicado
                        </button>
                        <div class="copy-note">
                            <i class="fas fa-info-circle me-2"></i> Se enviará una copia a tu correo
                        </div>
                    </form>
                    <?php endif; ?>
                </div>
            </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');
        });
        // Habilitar/deshabilitar selects según las selecciones
        document.getElementById('nivel').addEventListener('change', function() {
            const gradoSelect = document.getElementById('grado');
            const seccionSelect = document.getElementById('seccion');
            if (this.value) {
                gradoSelect.disabled = false;
                gradoSelect.innerHTML = '<option value="">Seleccionar Grado</option>';
                seccionSelect.disabled = true;
                seccionSelect.innerHTML = '<option value="">Seleccionar Sección</option>';
                document.getElementById('filterForm').submit();
            } else {
                gradoSelect.disabled = true;
                seccionSelect.disabled = true;
                gradoSelect.innerHTML = '<option value="">Seleccionar Grado</option>';
                seccionSelect.innerHTML = '<option value="">Seleccionar Sección</option>';
                document.getElementById('filterForm').submit();
            }
        });
        document.getElementById('grado').addEventListener('change', function() {
            const seccionSelect = document.getElementById('seccion');
            if (this.value) {
                seccionSelect.disabled = false;
                seccionSelect.innerHTML = '<option value="">Seleccionar Sección</option>';
                document.getElementById('filterForm').submit();
            } else {
                seccionSelect.disabled = true;
                seccionSelect.innerHTML = '<option value="">Seleccionar Sección</option>';
                document.getElementById('filterForm').submit();
            }
        });
        // Actualizar destinatarios
        const checkboxes = document.querySelectorAll('input[name="estudiantes[]"]');
        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', updateRecipients);
        });
        function updateRecipients() {
            const selectedEmails = [];
            const recipientTags = document.getElementById('recipientsTags');
            const hiddenInput = document.querySelector('input[name="to"]');
            document.querySelectorAll('input[name="estudiantes[]"]:checked').forEach(checkbox => {
                selectedEmails.push(checkbox.value);
            });
            if (recipientTags) {
                recipientTags.innerHTML = '';
                if (selectedEmails.length > 0) {
                    selectedEmails.forEach(email => {
                        const tag = document.createElement('span');
                        tag.className = 'recipient-tag';
                        tag.textContent = email;
                        recipientTags.appendChild(tag);
                    });
                } else {
                    recipientTags.innerHTML = '<span class="text-muted">Seleccione estudiantes para ver los destinatarios</span>';
                }
            }
            if (hiddenInput) {
                hiddenInput.value = selectedEmails.join(',');
            }
        }
        document.addEventListener('DOMContentLoaded', function() {
            const nivelSelect = document.getElementById('nivel');
            const gradoSelect = document.getElementById('grado');
            const seccionSelect = document.getElementById('seccion');
            if (!nivelSelect.value) {
                gradoSelect.disabled = true;
                seccionSelect.disabled = true;
            } else if (nivelSelect.value && !gradoSelect.value) {
                seccionSelect.disabled = true;
            }
        });
    </script>
</body>
</html>