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

// Verificar y definir constantes si no existen
if (!defined('APP_NAME')) define('APP_NAME', 'MI COLE');
if (!defined('APP_URL')) define('APP_URL', '');

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

// Obtener información del estudiante
global $db;
$estudiante = $db->fetchOne("SELECT * FROM estudiantes WHERE usuario_id = ?", [$usuarioId]);

// Valores por defecto si no se encuentra el estudiante
$nivel = 'secundaria';
$grado = '5';
$seccion = 'A';
$estudianteId = 0;

if ($estudiante) {
    $nivel = $estudiante['nivel'] ?? $nivel;
    $grado = $estudiante['grado'] ?? $grado;
    $seccion = $estudiante['seccion'] ?? $seccion;
    $estudianteId = $estudiante['id'] ?? 0;
    $usuarioRol = "Estudiante - $grado $nivel";
} else {
    $usuarioRol = "Estudiante";
}

// Manejar navegación entre semanas
$weekOffset = isset($_GET['week_offset']) ? (int)$_GET['week_offset'] : 0;
$hoy = new DateTime();
$lunes = (clone $hoy)->modify('Monday this week')->modify("$weekOffset weeks");
$fechasSemana = [];

// Generar fechas de lunes a viernes
for ($i = 0; $i < 5; $i++) {
    $fecha = clone $lunes;
    $fecha->modify("+$i days");
    $fechasSemana[] = $fecha->format('Y-m-d');
}

// Obtener asistencia para la semana seleccionada
$asistencia = $db->fetchAll("
    SELECT fecha, estado 
    FROM asistencias_estudiantes 
    WHERE estudiante_id = ?
    AND fecha BETWEEN ? AND ?
", [$estudianteId, $fechasSemana[0], $fechasSemana[4]]);

// Organizar asistencia por fecha
$asistenciaSemanal = [];
foreach ($fechasSemana as $fecha) {
    $asistenciaSemanal[$fecha] = null; // Inicializar todos los días primero
}

foreach ($asistencia as $registro) {
    $asistenciaSemanal[$registro['fecha']] = $registro['estado'];
}

// Contadores para los totales
$totales = [
    'presente' => 0,
    'ausente' => 0,
    'tardanza' => 0,
    'justificado' => 0
];

foreach ($asistenciaSemanal as $estado) {
    if ($estado && isset($totales[$estado])) {
        $totales[$estado]++;
    }
}

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

$notificacionesNoLeidas = is_array($notificaciones) ? count($notificaciones) : 0;

function nombreDia($fecha) {
    $dias = ['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes'];
    $numeroDia = date('N', strtotime($fecha));
    return $dias[$numeroDia - 1];
}

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

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

        /* Sidebar para estudiantes */
        .sidebar {
            width: var(--sidebar-width);
            background: linear-gradient(to bottom, var(--primary), var(--secondary));
            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: white;
        }

        .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.7);
            font-weight: 500;
        }

        .menu-items {
            list-style: none;
            padding: 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.1);
            border-left-color: white;
        }

        .menu-item.active {
            background-color: rgba(255, 255, 255, 0.15);
            border-left-color: white;
        }

        .menu-item i {
            width: 24px;
            text-align: center;
            font-size: 18px;
        }

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

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

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

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

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

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

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

        .welcome-section {
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border-radius: 15px;
            padding: 25px 30px;
            color: white;
            margin-bottom: 25px;
            box-shadow: 0 10px 20px rgba(52, 152, 219, 0.2);
            position: relative;
            overflow: hidden;
        }

        .welcome-section::before {
            content: "";
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
            transform: rotate(30deg);
            z-index: 0;
        }

        .welcome-content {
            position: relative;
            z-index: 1;
        }

        .welcome-section h1 {
            font-size: 26px;
            margin-bottom: 10px;
            font-weight: 600;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .welcome-section p {
            font-size: 16px;
            max-width: 700px;
            opacity: 0.9;
            line-height: 1.6;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        
        /* Estilos específicos para la asistencia */
        .attendance-container {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
            margin-bottom: 30px;
        }
        
        .section-title {
            font-size: 22px;
            margin: 0 0 25px;
            color: var(--dark);
            display: flex;
            align-items: center;
            gap: 12px;
            position: relative;
            padding-bottom: 15px;
        }
        
        .section-title::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            width: 60px;
            height: 4px;
            background: var(--primary);
            border-radius: 2px;
        }
        
        .section-title i {
            color: var(--primary);
        }
        
        .info-section {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        
        .info-badge {
            background: #f0f7ff;
            border-radius: 30px;
            padding: 10px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 500;
            border: 1px solid #e1f0ff;
        }
        
        .info-badge i {
            color: var(--primary);
            font-size: 18px;
        }
        
        .week-range {
            text-align: center;
            margin-bottom: 25px;
            font-size: 18px;
            font-weight: 600;
            color: var(--primary);
            padding: 15px;
            background: rgba(52, 152, 219, 0.1);
            border-radius: 12px;
        }
        
        .summary-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .summary-card {
            background: white;
            border-radius: 12px;
            padding: 25px 20px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            border-left: 4px solid var(--primary);
        }
        
        .summary-card h3 {
            font-size: 32px;
            margin: 0 0 10px;
            font-weight: 700;
            color: var(--dark);
        }
        
        .summary-card p {
            font-size: 16px;
            margin: 0;
            color: #6c757d;
        }
        
        .card-presente { border-left-color: var(--success); }
        .card-ausente { border-left-color: var(--accent); }
        .card-tardanza { border-left-color: var(--warning); }
        .card-justificado { border-left-color: var(--info); }
        
        .attendance-table-container {
            overflow-x: auto;
            border-radius: 12px;
            border: 1px solid #e9ecef;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        }
        
        .attendance-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }
        
        .attendance-table th {
            background: var(--primary);
            color: white;
            font-weight: 600;
            padding: 14px 12px;
            text-align: center;
        }
        
        .attendance-table th:first-child {
            border-top-left-radius: 12px;
        }
        
        .attendance-table th:last-child {
            border-top-right-radius: 12px;
        }
        
        .attendance-table td {
            padding: 12px 10px;
            text-align: center;
            border-bottom: 1px solid #e9ecef;
        }
        
        .attendance-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .status-cell {
            font-weight: 600;
            border-radius: 8px;
            padding: 8px 12px;
            display: inline-block;
            min-width: 100px;
        }
        
        .status-presente {
            background-color: rgba(46, 204, 113, 0.15);
            color: var(--success);
        }
        
        .status-ausente {
            background-color: rgba(231, 76, 60, 0.15);
            color: var(--accent);
        }
        
        .status-tardanza {
            background-color: rgba(241, 196, 15, 0.2);
            color: var(--warning);
        }
        
        .status-justificado {
            background-color: rgba(52, 152, 219, 0.15);
            color: var(--primary);
        }
        
        .status-empty {
            color: #95a5a6;
            font-style: italic;
        }
        
        .future-day {
            background-color: #f8f9fa;
            color: #95a5a6;
        }
        
        /* Responsive Design */
        @media (max-width: 992px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .toggle-menu {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .summary-cards {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .welcome-section h1 {
                font-size: 22px;
            }
            
            /* Nuevos estilos para tabla en móviles */
            .attendance-table-container {
                border: none;
                box-shadow: none;
                padding: 0;
            }
            
            .attendance-table {
                min-width: 0;
                display: block;
            }
            
            .attendance-table thead {
                display: none;
            }
            
            .attendance-table tr {
                display: flex;
                flex-wrap: wrap;
                margin-bottom: 15px;
                border-radius: 12px;
                border: 1px solid #e9ecef;
                box-shadow: 0 3px 8px rgba(0, 0, 0, 0.05);
                padding: 15px;
                background: white;
            }
            
            .attendance-table td {
                flex: 1 0 100%;
                padding: 8px 0;
                text-align: left;
                display: flex;
                border: none;
            }
            
            .attendance-table td::before {
                content: attr(data-label);
                font-weight: 600;
                min-width: 80px;
                color: var(--dark);
                margin-right: 10px;
            }
            
            .status-cell {
                min-width: auto;
                padding: 6px 10px;
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
        }

        @media (max-width: 576px) {
            .summary-cards {
                grid-template-columns: 1fr;
            }
            
            .info-section {
                flex-direction: column;
                gap: 8px;
            }
            
            .attendance-table tr {
                padding: 12px;
            }
            
            .content {
                padding: 20px 15px;
            }
            
            .user-name {
                font-size: 14px;
            }
            
            .user-role {
                font-size: 12px;
            }
        }
        
        /* Notificaciones */
        .notification-container {
            position: relative;
        }
        
        .notification-dropdown {
            position: absolute;
            top: 40px;
            right: 0;
            width: 400px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            display: none;
            overflow: hidden;
            transform: translateY(10px);
            opacity: 0;
            transition: transform 0.3s ease, opacity 0.3s ease;
        }
        
        .notification-container.active .notification-dropdown {
            display: block;
            transform: translateY(0);
            opacity: 1;
        }

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

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

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

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

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

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

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

        .notification-content {
            flex: 1;
        }

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

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

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

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

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

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

        .notification-actions a:hover {
            background: rgba(52, 152, 219, 0.2);
        }

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

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

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

        .notification-footer a {
            color: var(--primary);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
        }
        
        /* Navegación entre semanas - Mejoras responsive */
        .week-navigation {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }
        
        .nav-arrow {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            font-size: 20px;
            text-decoration: none;
            box-shadow: 0 4px 10px rgba(52, 152, 219, 0.3);
            transition: all 0.3s ease;
        }
        
        .nav-arrow:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 15px rgba(52, 152, 219, 0.4);
        }
        
        .week-range {
            text-align: center;
            font-size: 18px;
            font-weight: 600;
            color: var(--primary);
            padding: 15px 20px;
            background: rgba(52, 152, 219, 0.1);
            border-radius: 30px;
            min-width: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
            flex-wrap: wrap;
        }
        
        .current-week-indicator {
            display: inline-block;
            padding: 4px 12px;
            background: rgba(46, 204, 113, 0.2);
            color: var(--success);
            border-radius: 20px;
            font-size: 14px;
            margin-left: 10px;
            font-weight: 500;
        }
        
        .week-selector {
            display: flex;
            justify-content: center;
            margin-top: 15px;
            width: 100%;
        }
        
        .week-selector select {
            padding: 8px 15px;
            border-radius: 30px;
            border: 1px solid #3498db;
            background: white;
            color: var(--dark);
            font-weight: 500;
            cursor: pointer;
            outline: none;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            width: 100%;
            max-width: 300px;
        }
        
        /* Mejoras para móviles pequeños */
        @media (max-width: 768px) {
            .week-navigation {
                flex-direction: column;
                gap: 15px;
            }
            
            .week-range {
                min-width: auto;
                width: 100%;
                font-size: 16px;
                padding: 10px 15px;
                flex-direction: column;
            }
            
            .current-week-indicator {
                margin-top: 8px;
                margin-left: 0;
            }
            
            .nav-arrow {
                width: 40px;
                height: 40px;
                font-size: 18px;
            }
            
            .week-selector select {
                max-width: 100%;
            }
        }
        
        @media (max-width: 480px) {
            .week-range {
                font-size: 14px;
            }
            
            .section-title {
                font-size: 20px;
                flex-direction: column;
                align-items: flex-start;
            }
            
            .section-title i {
                margin-bottom: 10px;
            }
            
            .info-badge {
                width: 100%;
                justify-content: center;
            }
            
            .summary-card h3 {
                font-size: 28px;
            }
        }
        /* Nuevos estilos para el botón VOLVER AL MENÚ */
        .btn-volver-menu {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            padding: 12px 25px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            color: white;
            border: none;
            border-radius: 30px;
            font-weight: 600;
            font-size: 16px;
            text-decoration: none;
            box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
            transition: all 0.3s ease;
            margin: 25px auto 0;
            cursor: pointer;
        }
        
        .btn-volver-menu:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
        }
        
        .btn-volver-menu i {
            font-size: 18px;
        }
        
        .btn-container {
            text-align: center;
            width: 100%;
            padding: 15px 0;
        }
        
        /* Responsive para el botón */
        @media (max-width: 768px) {
            .btn-volver-menu {
                padding: 10px 20px;
                font-size: 15px;
            }
        }
    </style>
</head>
<body>
   <!-- Sidebar para estudiantes -->
    <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/estudiante/dashboard.php" style="display: block; color: inherit; text-decoration: none;">
                        <i class="fas fa-home"></i>
                        <span>Menu</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Académico</h3>
            <ul class="menu-items">
                <li class="menu-item active">
                    <a href="<?= APP_URL ?>/modules/estudiante/ver_asistencia.php" style="display: block; color: inherit; text-decoration: none;">
                        <i class="fas fa-calendar-alt"></i>
                        <span>Ver Asistencia</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/estudiante/notificaciones.php" style="display: block; color: inherit; text-decoration: none;">
                        <i class="fas fa-inbox"></i>
                        <span>Ver Mensajería</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/estudiante/enviar_correo.php" style="display: block; 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/estudiante/historial_de_correos_enviados.php" style="display: block; color: inherit; text-decoration: none;">
                        <i class="fas fa-history"></i>
                        <span>Historial de Comunicados</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="menu-section">
            <h3 class="menu-title">Cuenta</h3>
            <ul class="menu-items">
                <li class="menu-item">
                    <a href="<?= APP_URL ?>/modules/estudiante/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="display: block; 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 class="user-info">
                    <div class="user-avatar">
                        <?= 
                            substr($usuarioNombre, 0, 1) . 
                            (strpos($usuarioNombre, ' ') !== false ? 
                                substr($usuarioNombre, strpos($usuarioNombre, ' ') + 1, 1) : 
                                substr($usuarioNombre, 1, 1))
                        ?>
                    </div>
                    <div class="user-details">
                        <div class="user-name"><?= $usuarioNombre ?></div>
                        <div class="user-role"><?= $usuarioRol ?></div>
                    </div>
                </div>
            </div>
            
            <div class="header-right">
                <div class="notification-container" id="notificationContainer">
                    <div class="notification-trigger" id="notificationTrigger">
                        <i class="fas fa-bell"></i>
                        <?php if ($notificacionesNoLeidas > 0): ?>
                            <div class="notification-badge"><?= $notificacionesNoLeidas ?></div>
                        <?php endif; ?>
                    </div>

                    <div class="notification-dropdown">
                        
                        <div class="notification-list">
                            <?php if ($notificacionesNoLeidas > 0): ?>
                                <?php foreach ($notificaciones as $notif): 
                                    // Extraer el ID del correo del enlace
                                    $correo_id = explode('=', $notif['enlace'])[1] ?? 0;
                                ?>
                                    <div class="notification-item" data-id="<?= $notif['id'] ?>">
                                        <div class="notification-icon">
                                            <i class="fas fa-envelope"></i>
                                        </div>
                                        <div class="notification-content">
                                            <div class="notification-title">
                                                <strong><?= htmlspecialchars($notif['titulo']) ?></strong>
                                                <small><?= date('d M H:i', strtotime($notif['fecha_envio'])) ?></small>
                                            </div>
                                            <div class="notification-message">
                                                <?= htmlspecialchars($notif['mensaje']) ?>
                                            </div>
                                            <div class="notification-actions">
                                                <a href="<?= APP_URL ?>/modules/estudiante/ver_correo.php?correo_id=<?= $correo_id ?>" class="btn-view">
                                                    <i class="fas fa-eye"></i> Ver comunicado
                                                </a>
                                                
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="notification-empty">
                                    <i class="fas fa-inbox"></i>
                                    <p>No tienes notificaciones nuevas</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="notification-footer">
                            <a href="notificaciones.php">Ver todas las notificaciones</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>
        
        <!-- Content Area -->
        <div class="content">
            <div class="attendance-container">
                <h2 class="section-title"><i class="fas fa-user-graduate"></i> Información del Estudiante</h2>
                
                <div class="info-section">
                    <div class="info-badge">
                        <i class="fas fa-user"></i>
                        <div class="user-details">
                            <div class="user-name"><?= $usuarioNombre ?></div>
                        </div>
                    </div>
                    <div class="info-badge">
                        <i class="fas fa-graduation-cap"></i>
                        <span>Nivel: <?= htmlspecialchars($nivel) ?></span>
                    </div>
                    <div class="info-badge">
                        <i class="fas fa-sort-numeric-up"></i>
                        <span>Grado: <?= htmlspecialchars($grado) ?>°</span>
                    </div>
                    <div class="info-badge">
                        <i class="fas fa-users"></i>
                        <span>Sección: <?= htmlspecialchars($seccion) ?></span>
                    </div>
                </div>

                <h2 class="section-title"><i class="fas fa-chart-pie"></i> Resumen de Asistencia</h2>
                
                <div class="summary-cards">
                    <div class="summary-card card-presente">
                        <h3><?= $totales['presente'] ?></h3>
                        <p>Días Presente</p>
                    </div>
                    <div class="summary-card card-ausente">
                        <h3><?= $totales['ausente'] ?></h3>
                        <p>Días Ausente</p>
                    </div>
                    <div class="summary-card card-tardanza">
                        <h3><?= $totales['tardanza'] ?></h3>
                        <p>Tardanzas</p>
                    </div>
                    <div class="summary-card card-justificado">
                        <h3><?= $totales['justificado'] ?></h3>
                        <p>Justificados</p>
                    </div>
                </div>
                
                <!-- Navegación entre semanas - Versión mejorada para responsive -->
                <div class="week-navigation">
                    <a href="?week_offset=<?= $weekOffset - 1 ?>" class="nav-arrow">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                    
                    <div class="week-range">
                        <i class="fas fa-calendar-week"></i>
                        Semana del <?= date('d/m/Y', strtotime($fechasSemana[0])) ?> al <?= date('d/m/Y', strtotime($fechasSemana[4])) ?>
                        <?php if ($weekOffset == 0): ?>
                            <span class="current-week-indicator">Semana Actual</span>
                        <?php endif; ?>
                    </div>
                    
                    <a href="?week_offset=<?= $weekOffset + 1 ?>" class="nav-arrow">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                    
                </div>
                <h2 class="section-title"><i class="fas fa-calendar-day"></i> Detalle Diario</h2>
                
                <div class="attendance-table-container">
                    <table class="attendance-table">
                        <thead>
                            <tr>
                                <th>Día</th>
                                <th>Fecha</th>
                                <th>Estado</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($fechasSemana as $fecha): ?>
                                <?php 
                                $hoyObj = new DateTime();
                                $fechaObj = new DateTime($fecha);
                                $isFuture = $fechaObj > $hoyObj;
                                $estado = $asistenciaSemanal[$fecha] ?? null;
                                ?>
                                <tr>
                                    <td data-label="Día"><?= nombreDia($fecha) ?></td>
                                    <td data-label="Fecha"><?= date('d/m/Y', strtotime($fecha)) ?></td>
                                    <td data-label="Estado">
                                        <?php if ($isFuture): ?>
                                            <span class="status-empty">--</span>
                                        <?php elseif ($estado): ?>
                                            <span class="status-cell status-<?= $estado ?>">
                                                <i class="fas 
                                                    <?= $estado === 'presente' ? 'fa-check-circle' : '' ?>
                                                    <?= $estado === 'ausente' ? 'fa-times-circle' : '' ?>
                                                    <?= $estado === 'tardanza' ? 'fa-clock' : '' ?>
                                                    <?= $estado === 'justificado' ? 'fa-file-alt' : '' ?>
                                                "></i>
                                                <?= ucfirst($estado) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="status-empty">Sin registro</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="btn-container">
                <a href="<?= APP_URL ?>/modules/estudiante/dashboard.php" class="btn-volver-menu">
                    <i class="fas fa-arrow-left"></i> VOLVER AL MENÚ
                </a>
            </div>
            </div>
        </div>
        
        <!-- Footer -->
        <footer class="footer">
            <p>Sistema Escolar Integrado v3.0 © <?= date('Y') ?> - Todos los derechos reservados</p>
        </footer>
    </div>

    <script src="<?= APP_URL ?>/assets/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle sidebar on mobile
        document.querySelector('.toggle-menu').addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('active');
        });
        
        // Set active menu item
        const menuItems = document.querySelectorAll('.menu-item');
        menuItems.forEach(item => {
            item.addEventListener('click', function() {
                menuItems.forEach(i => i.classList.remove('active'));
                this.classList.add('active');
            });
        });
        
        // Notificaciones
        document.addEventListener('DOMContentLoaded', function() {
            const notificationContainer = document.getElementById('notificationContainer');
            const notificationTrigger = document.getElementById('notificationTrigger');
            const notificationDropdown = notificationContainer.querySelector('.notification-dropdown');
            
            // Abrir/cerrar menú de notificaciones
            notificationTrigger.addEventListener('click', function(e) {
                e.stopPropagation();
                notificationContainer.classList.toggle('active');
            });
            
            // Cerrar menú al hacer clic fuera
            document.addEventListener('click', function(e) {
                if (!notificationContainer.contains(e.target)) {
                    notificationContainer.classList.remove('active');
                }
            });
            
            // Prevenir cierre al hacer clic dentro del menú
            notificationDropdown.addEventListener('click', function(e) {
                e.stopPropagation();
            });
            
            // Marcar notificación como leída
            document.querySelectorAll('.notification-item').forEach(item => {
                item.addEventListener('click', function() {
                    const notifId = this.getAttribute('data-id');
                    fetch('marcar_leida.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: notifId })
                    }).then(response => response.json())
                      .then(data => {
                          if (data.success) {
                              this.style.opacity = '0.7';
                          }
                      });
                });
            });
            
            // Marcar todas como leídas
            document.getElementById('markAllAsRead').addEventListener('click', function(e) {
                e.stopPropagation();
                fetch('marcar_todas_leidas.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ usuario_id: <?= $usuarioId ?> })
                }).then(response => response.json())
                  .then(data => {
                      if (data.success) {
                          // Actualizar la interfaz
                          document.querySelectorAll('.notification-item').forEach(item => {
                              item.style.opacity = '0.7';
                          });
                          if (document.querySelector('.notification-badge')) {
                              document.querySelector('.notification-badge').style.display = 'none';
                          }
                      }
                  });
            });
        });
    </script>
</body>
</html>