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

// Obtener ID del estudiante desde parámetro GET
$estudiante_id = $_GET['estudiante_id'] ?? null;

// Validar que se haya proporcionado un ID de estudiante
if (!$estudiante_id) {
    $_SESSION['error'] = 'No se ha especificado un estudiante';
    header("Location: lista_alumnos.php");
    exit;
}

// Obtener datos del estudiante
global $db;
$estudiante = $db->fetchOne("
    SELECT e.id, u.nombre, u.apellido, u.email 
    FROM estudiantes e
    JOIN usuarios u ON e.usuario_id = u.id
    WHERE e.id = ?
", [$estudiante_id]);

// Verificar que el estudiante existe
if (!$estudiante) {
    $_SESSION['error'] = 'Estudiante no encontrado';
    header("Location: lista_alumnos.php");
    exit;
}

// Obtener historial de correos para este estudiante
$correos = $db->fetchAll("
    SELECT * 
    FROM correos_enviados 
    WHERE destinatarios LIKE ? 
    ORDER BY fecha_envio DESC 
    LIMIT 5
", ["%{$estudiante['email']}%"]);

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

// Configuración para menú y header
$nombreColegio = APP_NAME;
$usuarioNombre = $_SESSION['user_name'] ?? 'Auxiliar';
$usuarioRol = 'Auxiliar';
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contactar a Padres - <?= 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 */
        .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;
            font-size: 14px;
        }

        .form-control, .form-select {
            border: 2px solid #e0e6ef;
            border-radius: 8px;
            padding: 12px 15px;
            transition: all 0.3s;
            font-size: 14px;
        }

        .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;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-send:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.4);
            color: white;
        }

        .recipient-card {
            background: #f0f5ff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 15px;
            border-left: 4px solid var(--accent);
        }

        .recipient-icon {
            width: 60px;
            height: 60px;
            background: rgba(67, 97, 238, 0.1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: var(--accent);
        }

        .recipient-info h3 {
            margin: 0;
            font-size: 18px;
            color: var(--dark);
        }

        .recipient-info p {
            margin: 5px 0 0;
            color: #6c757d;
        }

        .history-card {
            background: #f8fafc;
            border-radius: 10px;
            padding: 20px;
            margin-top: 30px;
            border: 1px solid #e9ecef;
        }

        .history-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .history-header h3 {
            margin: 0;
            color: var(--dark);
            font-size: 18px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .history-table {
            width: 100%;
            border-collapse: collapse;
        }

        .history-table th {
            background-color: #f1f5f9;
            padding: 12px 15px;
            text-align: left;
            color: var(--dark);
            font-weight: 600;
            border-bottom: 2px solid #dee2e6;
        }

        .history-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #e9ecef;
        }

        .history-table tr:last-child td {
            border-bottom: none;
        }

        .badge-success {
            background-color: rgba(6, 214, 160, 0.15);
            color: var(--success);
            padding: 5px 12px;
            border-radius: 50px;
            font-weight: 500;
        }

        .badge-danger {
            background-color: rgba(239, 71, 111, 0.15);
            color: var(--danger);
            padding: 5px 12px;
            border-radius: 50px;
            font-weight: 500;
        }

        .no-history {
            text-align: center;
            padding: 30px;
            color: #6c757d;
        }

        .no-history i {
            font-size: 48px;
            color: #dee2e6;
            margin-bottom: 15px;
        }

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

        /* FORMULARIO MEJORADO */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #343a40;
        }

        .form-control {
            width: 100%;
            font-size: 14px;
            line-height: 1.5;
        }

        textarea.form-control {
            min-height: 150px;
            resize: vertical;
        }

        .info-text {
            font-size: 14px;
            color: #495057;
            margin-top: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .info-text i {
            font-size: 12px;
            color: #007bff;
        }

        .submit-wrapper {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            gap: 12px;
            margin-top: 15px;
        }

        .submit-wrapper .btn {
            padding: 10px 20px;
            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;
            }

            .recipient-card {
                flex-direction: column;
                text-align: center;
            }

            .form-control {
                font-size: 14px;
            }

            .btn-send {
                width: 100%;
            }
        }

        @media (max-width: 480px) {
            .header {
                padding: 0 15px;
            }

            .recipient-icon {
                width: 50px;
                height: 50px;
                font-size: 20px;
            }

            .btn-send {
                width: 100%;
            }
        }
    </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 Comunicados</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/historial_de_correos.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-history"></i>
                        <span>Historial de Comunicados</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/auxiliar/correo_administrativo.php" style="color: inherit; text-decoration: none;">
                        <i class="fas fa-users"></i>
                        <span>Correo Administrativo</span>
                    </a>
                </li>
            </ul>
        </div>

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

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

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

        <!-- Contenido de contacto -->
        <div class="content">
            <div class="email-container">
                <div class="email-header">
                    <h1><i class="fas fa-user-graduate"></i> Contactar a Padres</h1>
                    <p>Comunícate con los padres o apoderados del estudiante</p>
                    <a href="lista_alumnos.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; ?>

                    <!-- Tarjeta de destinatario -->
                    <div class="recipient-card">
                        <div class="recipient-icon">
                            <i class="fas fa-user"></i>
                        </div>
                        <div class="recipient-info">
                            <h3><?= htmlspecialchars($estudiante['nombre'] . ' ' . $estudiante['apellido']) ?></h3>
                            <p><?= htmlspecialchars($estudiante['email']) ?></p>
                        </div>
                    </div>

                    <!-- Formulario de envío de correo -->
                    <form method="POST" action="send_email_single_handler.php" id="emailForm">
                        <input type="hidden" name="to" value="<?= htmlspecialchars($estudiante['email']) ?>">
                        <input type="hidden" name="estudiante_id" value="<?= $estudiante_id ?>">

                        <!-- Campo Asunto -->
                        <div class="form-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 sobre <?= htmlspecialchars($estudiante['nombre']) ?>">
                        </div>

                        <!-- Campo Mensaje -->
                        <div class="form-group">
                            <label for="message" class="form-label">Mensaje</label>
                            <textarea class="form-control" id="message" name="message" rows="6" required
                                      placeholder="Escribe tu mensaje aquí..."><?= htmlspecialchars("Estimados padres de " . $estudiante['nombre'] . ",\n\nLe escribo para informar sobre...") ?></textarea>
                            <div class="info-text">
                                <i class="fas fa-info-circle"></i>
                                Tu nombre (<strong><?= htmlspecialchars($_SESSION['user_name'] ?? 'Auxiliar') ?></strong>) se agregará automáticamente al final del mensaje
                            </div>
                        </div>

                        <!-- Botón de enviar y info adicional -->
                        <div class="submit-wrapper">
                            <button type="submit" class="btn btn-send">
                                <i class="fas fa-paper-plane"></i> Enviar Comunicado
                            </button>
                            <div class="info-text">
                                <i class="fas fa-info-circle"></i>
                                Se enviará una copia a tu correo
                            </div>
                        </div>
                    </form>

                    <!-- Historial de comunicaciones -->
                    <div class="history-card">
                        <div class="history-header">
                            <h3><i class="fas fa-history"></i> Comunicados anteriores</h3>
                        </div>

                        <?php if (!empty($correos)): ?>
                            <div class="table-responsive">
                                <table class="history-table">
                                    <thead>
                                        <tr>
                                            <th>Fecha</th>
                                            <th>Asunto</th>
                                            <th>Estado</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($correos as $correo): ?>
                                            <tr>
                                                <td><?= date('d/m/Y H:i', strtotime($correo['fecha_envio'])) ?></td>
                                                <td><?= htmlspecialchars($correo['asunto']) ?></td>
                                                <td>
                                                    <span class="<?= $correo['estado'] === 'enviado' ? 'badge-success' : 'badge-danger' ?>">
                                                        <?= ucfirst($correo['estado']) ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="no-history">
                                <i class="fas fa-inbox"></i>
                                <h4>No hay comunicaciones anteriores</h4>
                                <p class="text-muted">Los mensajes que envíes aparecerán en este historial</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </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');

            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();
        });
    </script>
</body>
</html>