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

// Obtener datos del usuario
$nombreColegio = APP_NAME;
$usuarioNombre = $_SESSION['user_name'] ?? 'Auxiliar';
$usuarioId = $_SESSION['user_id'] ?? 0;

// Obtener lista de directores y auxiliares
global $db;
$destinatarios = $db->fetchAll("
    SELECT u.id, u.nombre, u.apellido, u.email, u.tipo 
    FROM usuarios u
    WHERE u.tipo IN ('direccion', 'auxiliar')
");

// Manejar envío de correo
$success = $_SESSION['success'] ?? null;
$error = $_SESSION['error'] ?? null;
unset($_SESSION['success'], $_SESSION['error']);

// Organizar destinatarios por tipo
$directores = array_filter($destinatarios, function($d) { return $d['tipo'] == 'direccion'; });
$auxiliares = array_filter($destinatarios, function($d) { return $d['tipo'] == 'auxiliar'; });
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Correo Administrativo - <?= APP_NAME ?></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 {
            display: flex;
            min-height: 100vh;
            margin: 0;
            background-color: #f5f7fa;
            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(--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 {
            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(--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 {
            padding: 20px 30px;
            text-align: center;
            color: #7f8c8d;
            font-size: 14px;
            border-top: 1px solid #eee;
            margin-top: 30px;
            background: white;
        }

        .content {
            padding: 30px;
        }
        
        /* ESTILOS ESPECÍFICOS DE CONTACTO ADMINISTRATIVO */
        .email-container {
            max-width: 800px;
            margin: 30px auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        
        .email-header {
            background: linear-gradient(135deg, var(--accent), #3a56d4);
            color: white;
            padding: 25px 30px;
            position: relative;
        }
        
        .email-header h1 {
            font-size: 24px;
            font-weight: 600;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .email-header p {
            opacity: 0.9;
            margin: 10px 0 0;
            font-size: 16px;
        }
        
        .email-content {
            padding: 30px;
        }
        
        .form-label {
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 8px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e0e6ef;
            border-radius: 8px;
            padding: 12px 15px;
            transition: all 0.3s;
            width: 100%;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
        }
        
        .btn-send {
            background: linear-gradient(135deg, var(--accent), #3a56d4);
            border: none;
            padding: 12px 25px;
            font-weight: 600;
            font-size: 16px;
            border-radius: 8px;
            transition: all 0.3s;
            color: white;
        }
        
        .btn-send:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.4);
            color: white;
        }
        
        .btn-back {
            position: absolute;
            top: 20px;
            right: 20px;
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 15px;
            border-radius: 6px;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-back:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-2px);
            color: white;
        }
        
        .alert {
            border-radius: 8px;
        }
        
        /* NUEVO ESTILO PARA DESTINATARIOS (ESTILO IMAGEN) */
        .recipient-selector {
            position: relative;
            margin-bottom: 20px;
        }
        
        .selector-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px;
            background: #f8fafc;
            border: 2px solid #e0e6ef;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .selector-header:hover {
            border-color: var(--accent);
        }
        
        .selector-header span {
            font-weight: 500;
            color: var(--dark);
        }
        
        .selector-header i {
            transition: transform 0.3s;
        }
        
        .selector-header.active i {
            transform: rotate(180deg);
        }
        
        .selector-dropdown {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 2px solid #e0e6ef;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            z-index: 100;
            max-height: 300px;
            overflow-y: auto;
            margin-top: 5px;
        }
        
        .selector-dropdown.active {
            display: block;
        }
        
        .recipient-group {
            border-bottom: 1px solid #eee;
        }
        
        .recipient-group:last-child {
            border-bottom: none;
        }
        
        .group-header {
            padding: 12px 15px;
            background: #f0f5ff;
            font-weight: 600;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .recipient-list {
            padding: 10px 15px;
        }
        
        .recipient-option {
            padding: 12px 0;
            display: flex;
            align-items: center;
            gap: 12px;
            cursor: pointer;
            transition: all 0.2s;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .recipient-option:last-child {
            border-bottom: none;
        }
        
        .recipient-option:hover {
            background-color: #f8f9fa;
        }
        
        .recipient-option input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        
        .recipient-name {
            font-weight: 500;
            color: var(--dark);
        }
        
        .recipient-email {
            font-size: 13px;
            color: #6c757d;
            margin-top: 3px;
        }
        
        .selected-recipients {
            background: #e8f4fe;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            border: 1px solid #d0e8ff;
            display: none;
        }
        
        .selected-recipients.active {
            display: block;
        }
        
        .selected-header {
            font-size: 15px;
            font-weight: 600;
            margin-bottom: 10px;
            color: var(--dark);
        }
        
        .selected-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .selected-item {
            background: var(--accent);
            color: white;
            padding: 6px 12px;
            border-radius: 50px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .remove-btn {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            padding: 0;
            font-size: 14px;
        }
        
        /* RESPONSIVE */
        @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) {
            .content {
                padding: 20px 15px;
            }
            
            .user-details {
                display: none;
            }
            
            .email-header h1 {
                font-size: 20px;
            }
            
            .selector-dropdown {
                position: relative;
                top: auto;
                left: auto;
                right: auto;
            }
        }
        
        @media (max-width: 480px) {
            .header {
                padding: 0 15px;
            }
            
            .email-container {
                margin: 15px;
            }
            
            .email-content {
                padding: 20px;
            }
            
            .recipient-option {
                padding: 10px 0;
            }
        }
    </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">
                    <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 active">
                    <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">Auxiliar</div>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Contenido de correo administrativo -->
        <div class="content">
            <div class="email-container">
                <div class="email-header">
                    <h1><i class="fas fa-users"></i> Correo Administrativo</h1>
                    <p>Envía un comunicado a directores y auxiliares del colegio</p>
                    
                    <a href="dashboard.php" class="btn-back">
                        <i class="fas fa-arrow-left"></i> Volver
                    </a>
                </div>
                
                <div class="email-content">
                    <?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; ?>
                    
                    <!-- Formulario de envío de correo -->
                    <form method="POST" action="send_email_administrativo_handler.php" id="emailForm">
                        <input type="hidden" name="tipo" value="administrativo">
                        <div class="mb-4">
                            <label class="form-label">Destinatarios</label>
                            
                            <!-- Nuevo selector de destinatarios estilo imagen -->
                            <div class="recipient-selector">
                                <div class="selector-header" id="recipientSelectorHeader">
                                    <span>Seleccionar destinatarios</span>
                                    <i class="fas fa-chevron-down"></i>
                                </div>
                                
                                <div class="selector-dropdown" id="recipientSelectorDropdown">
                                    <!-- Grupo de Directores -->
                                    <div class="recipient-group">
                                        <div class="group-header">
                                            <i class="fas fa-user-tie"></i>
                                            <span>Directores</span>
                                        </div>
                                        <div class="recipient-list">
                                            <?php if (!empty($directores)): ?>
                                                <?php foreach ($directores as $dir): ?>
                                                    <div class="recipient-option" data-id="<?= $dir['id'] ?>">
                                                        <input type="checkbox" name="destinatarios[]" 
                                                               value="<?= htmlspecialchars($dir['email']) ?>" 
                                                               id="dir-<?= $dir['id'] ?>">
                                                        <div>
                                                            <div class="recipient-name"><?= htmlspecialchars($dir['nombre'] . ' ' . $dir['apellido']) ?></div>
                                                            <div class="recipient-email"><?= htmlspecialchars($dir['email']) ?></div>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <div class="text-center py-2">
                                                    <i class="fas fa-user-slash text-muted"></i>
                                                    <p class="text-muted">No hay directores registrados</p>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <!-- Grupo de Auxiliares -->
                                    <div class="recipient-group">
                                        <div class="group-header">
                                            <i class="fas fa-user-shield"></i>
                                            <span>Auxiliares</span>
                                        </div>
                                        <div class="recipient-list">
                                            <?php if (!empty($auxiliares)): ?>
                                                <?php foreach ($auxiliares as $aux): ?>
                                                    <div class="recipient-option" data-id="<?= $aux['id'] ?>">
                                                        <input type="checkbox" name="destinatarios[]" 
                                                               value="<?= htmlspecialchars($aux['email']) ?>" 
                                                               id="aux-<?= $aux['id'] ?>">
                                                        <div>
                                                            <div class="recipient-name"><?= htmlspecialchars($aux['nombre'] . ' ' . $aux['apellido']) ?></div>
                                                            <div class="recipient-email"><?= htmlspecialchars($aux['email']) ?></div>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <div class="text-center py-2">
                                                    <i class="fas fa-user-slash text-muted"></i>
                                                    <p class="text-muted">No hay auxiliares registrados</p>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Área de destinatarios seleccionados -->
                            <div class="selected-recipients" id="selectedRecipients">
                                <div class="selected-header">Destinatarios seleccionados:</div>
                                <div class="selected-list" id="selectedList">
                                    <!-- Los destinatarios seleccionados aparecerán aquí -->
                                </div>
                            </div>
                        </div>
                        <div class="mb-4">
                            <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 administrativo">
                        </div>
                        
                        <div class="mb-4">
                            <label for="message" class="form-label">Mensaje</label>
                            <textarea class="form-control" id="message" name="message" rows="8" required
                                      placeholder="Escribe tu mensaje aquí...">Estimado equipo administrativo,</textarea>
                        </div>
                        
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <button type="submit" class="btn btn-send">
                                    <i class="fas fa-paper-plane me-2"></i>Enviar Comunicado
                                </button>
                            </div>
                            <div class="text-muted">
                                <i class="fas fa-info-circle me-2"></i>Se enviará una copia a tu correo
                            </div>
                        </div>
                    </form>
                </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');
        });
        
        // 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();
        });
        
        // Toggle selector de destinatarios
        const selectorHeader = document.getElementById('recipientSelectorHeader');
        const selectorDropdown = document.getElementById('recipientSelectorDropdown');
        const selectedRecipients = document.getElementById('selectedRecipients');
        const selectedList = document.getElementById('selectedList');
        
        selectorHeader.addEventListener('click', function() {
            this.classList.toggle('active');
            selectorDropdown.classList.toggle('active');
        });
        
        // Cerrar selector al hacer clic fuera
        document.addEventListener('click', function(e) {
            if (!selectorHeader.contains(e.target)) {
                selectorHeader.classList.remove('active');
                selectorDropdown.classList.remove('active');
            }
        });
        
        // Manejar selección de destinatarios
        const selectedItems = {};
        
        document.querySelectorAll('.recipient-option input[type="checkbox"]').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const option = this.closest('.recipient-option');
                const id = option.getAttribute('data-id');
                const name = option.querySelector('.recipient-name').textContent;
                
                if (this.checked) {
                    selectedItems[id] = name;
                } else {
                    delete selectedItems[id];
                }
                
                updateSelectedList();
            });
        });
        
        // Actualizar lista de seleccionados
        function updateSelectedList() {
            selectedList.innerHTML = '';
            
            if (Object.keys(selectedItems).length === 0) {
                selectedRecipients.classList.remove('active');
                return;
            }
            
            selectedRecipients.classList.add('active');
            
            for (const id in selectedItems) {
                const name = selectedItems[id];
                const item = document.createElement('div');
                item.className = 'selected-item';
                item.innerHTML = `
                    ${name}
                    <button class="remove-btn" data-id="${id}">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                selectedList.appendChild(item);
            }
            
            // Añadir event listeners a los botones de eliminar
            document.querySelectorAll('.remove-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const id = this.getAttribute('data-id');
                    const checkbox = document.querySelector(`.recipient-option[data-id="${id}"] input`);
                    if (checkbox) {
                        checkbox.checked = false;
                        delete selectedItems[id];
                        updateSelectedList();
                    }
                });
            });
        }
        
        // Validación del formulario
        document.getElementById('emailForm').addEventListener('submit', function(e) {
            if (Object.keys(selectedItems).length === 0) {
                e.preventDefault();
                alert('Por favor selecciona al menos un destinatario');
            }
        });
    </script>
</body>
</html>