<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php-error.log');

include_once '../../controllers/MateriaController.php';
include_once '../../controllers/CarreraController.php';
include_once '../../controllers/AsignarMateriaController.php';
include_once '../../controllers/EstudianteController.php';
include_once '../../controllers/DocenteController.php';

$carreraController = new CarreraController();
$materiaController = new MateriaController();
$asignarMateriaController = new AsignarMateriaController();
$estudianteController = new EstudianteController();
$docenteController = new DocenteController();

$carrera_id = isset($_GET['carrera_id']) ? $_GET['carrera_id'] : null;
if ($carrera_id) {
    $materias = $materiaController->listarMateriasPorCarrera($carrera_id);
} else {
    $materias = [];
}

$asignaciones = $asignarMateriaController->listarAsignaciones();

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['agregar'])) {
    if (isset($_POST['estudiantes']) && !empty($_POST['estudiantes'])) {
        // Los estudiantes ya deberían estar como cadena separada por comas
        $student_ids = explode(',', $_POST['estudiantes']);
        $docente_id = $_POST['docente_id'];
        $materia_id = $_POST['materia_id'];
        $fecha_asignacion = $_POST['fecha_asignacion'];
        $estado = $_POST['estado'];

        foreach ($student_ids as $student_id) {
            $resultado = $asignarMateriaController->agregarAsignacion(
                $student_id,
                $docente_id,
                $materia_id,
                $fecha_asignacion,
                $estado
            );
            if (!$resultado) {
                echo "<script>
                    document.addEventListener('DOMContentLoaded', function() {
                        Swal.fire({
                            title: 'Error',
                            text: 'Error al agregar asignación para el estudiante $student_id.',
                            icon: 'error',
                            confirmButtonColor: '#ef4444'
                        });
                    });
                </script>";
            }
        }

        echo "<script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    title: '¡Éxito!',
                    text: 'Asignaciones agregadas correctamente.',
                    icon: 'success',
                    timer: 2000,
                    showConfirmButton: false
                }).then(function() {
                    window.location.href = 'gestionar_asignaciones.php';
                });
            });
        </script>";
    } else {
        echo "<script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    title: 'Advertencia',
                    text: 'Por favor, seleccione al menos un estudiante.',
                    icon: 'warning',
                    confirmButtonColor: '#f59e0b'
                });
            });
        </script>";
    }
}
?>

<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestionar Asignaciones</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        :root {
            --primary: #6366f1;
            --primary-hover: #4f46e5;
            --secondary: #06b6d4;
            --secondary-hover: #0891b2;
            --accent: #f43f5e;
            --accent-hover: #e11d48;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --info: #3b82f6;
            --background: #f8fafc;
            --foreground: #0f172a;
            --card: rgba(255, 255, 255, 0.8);
            --card-foreground: #1e293b;
            --border: #e2e8f0;
            --input: #e2e8f0;
            --ring: #6366f1;
            --muted: #94a3b8;
        }

        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--background);
            color: var(--foreground);
            background-image: 
                radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.1) 0px, transparent 50%),
                radial-gradient(at 100% 0%, rgba(6, 182, 212, 0.1) 0px, transparent 50%),
                radial-gradient(at 100% 100%, rgba(244, 63, 94, 0.1) 0px, transparent 50%),
                radial-gradient(at 0% 100%, rgba(16, 185, 129, 0.1) 0px, transparent 50%);
            background-attachment: fixed;
            background-size: cover;
        }

        .glass {
            background: var(--card);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.3);
            box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.07);
        }

        .card {
            border-radius: 1.5rem;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.05), 0 10px 10px -5px rgba(0, 0, 0, 0.02);
        }

        .btn {
            position: relative;
            overflow: hidden;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 0.75rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .btn::after {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            pointer-events: none;
            background-image: radial-gradient(circle, #fff 10%, transparent 10.01%);
            background-repeat: no-repeat;
            background-position: 50%;
            transform: scale(10, 10);
            opacity: 0;
            transition: transform 0.5s, opacity 1s;
        }

        .btn:active::after {
            transform: scale(0, 0);
            opacity: 0.3;
            transition: 0s;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: var(--primary-hover);
            transform: translateY(-2px);
        }

        .btn-secondary {
            background-color: var(--secondary);
            color: white;
        }

        .btn-secondary:hover {
            background-color: var(--secondary-hover);
            transform: translateY(-2px);
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-success:hover {
            background-color: #0d9488;
            transform: translateY(-2px);
        }

        .btn-warning {
            background-color: var(--warning);
            color: white;
        }

        .btn-warning:hover {
            background-color: #d97706;
            transform: translateY(-2px);
        }

        .btn-danger {
            background-color: var(--danger);
            color: white;
        }

        .btn-danger:hover {
            background-color: #b91c1c;
            transform: translateY(-2px);
        }

        .form-input {
            border: 1px solid var(--input);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-size: 0.875rem;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            background-color: white;
            width: 100%;
        }

        .form-input:focus {
            outline: none;
            border-color: var(--ring);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
        }

        .form-select {
            border: 1px solid var(--input);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem 0.75rem 2.5rem;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-size: 0.875rem;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            background-color: white;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
            background-position: right 0.75rem center;
            background-repeat: no-repeat;
            background-size: 1.25em 1.25em;
            padding-right: 2.5rem;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            width: 100%;
        }

        .form-select:focus {
            outline: none;
            border-color: var(--ring);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2);
        }

        .input-container {
            position: relative;
            margin-bottom: 1.5rem;
        }

        .input-container svg {
            position: absolute;
            left: 0.75rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--muted);
            width: 1.25rem;
            height: 1.25rem;
            z-index: 1;
        }

        .input-container label {
            position: absolute;
            left: 2.5rem;
            top: 0;
            padding: 0 0.25rem;
            color: var(--muted);
            font-size: 0.75rem;
            font-weight: 500;
            transform: translateY(-50%);
            background-color: white;
            z-index: 1;
        }

        .fade-in {
            animation: fadeIn 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .slide-in {
            animation: slideIn 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .scale-in {
            animation: scaleIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        @keyframes scaleIn {
            from {
                opacity: 0;
                transform: scale(0.95);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }

        /* Animated background */
        .animated-bg {
            position: relative;
            overflow: hidden;
        }

        .animated-bg::before {
            content: "";
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: conic-gradient(
                transparent, 
                rgba(99, 102, 241, 0.1), 
                transparent 30%
            );
            animation: rotate 4s linear infinite;
        }

        .animated-bg::after {
            content: "";
            position: absolute;
            inset: 2px;
            background: white;
            border-radius: inherit;
            z-index: 0;
        }

        .animated-bg > * {
            position: relative;
            z-index: 1;
        }

        @keyframes rotate {
            100% {
                transform: rotate(1turn);
            }
        }

        /* Icon pulse animation */
        .icon-container {
            position: relative;
            width: 40px;
            height: 40px;
        }

        .icon-pulse {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background-color: currentColor;
            opacity: 0.2;
            animation: iconPulse 2s infinite;
        }

        @keyframes iconPulse {
            0% {
                transform: scale(1);
                opacity: 0.2;
            }
            50% {
                transform: scale(1.3);
                opacity: 0;
            }
            100% {
                transform: scale(1);
                opacity: 0.2;
            }
        }

        /* Table styles */
        .table-container {
            overflow-x: auto;
            border-radius: 1rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }

        .table th {
            background-color: rgba(243, 244, 246, 0.8);
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 0.05em;
            color: var(--foreground);
            border-bottom: 1px solid var(--border);
        }

        .table td {
            padding: 1rem;
            border-bottom: 1px solid var(--border);
            background-color: rgba(255, 255, 255, 0.6);
            transition: all 0.2s;
        }

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

        .table tr:hover td {
            background-color: rgba(243, 244, 246, 0.8);
        }

        /* Badge styles */
        .badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0.35rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            letter-spacing: 0.025em;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        }

        .badge-success {
            background-color: rgba(16, 185, 129, 0.1);
            color: var(--success);
        }

        .badge-danger {
            background-color: rgba(239, 68, 68, 0.1);
            color: var(--danger);
        }

        /* Student selection styles */
        .student-chip {
            display: inline-flex;
            align-items: center;
            background-color: rgba(99, 102, 241, 0.1);
            color: var(--primary);
            padding: 0.5rem 0.75rem;
            border-radius: 9999px;
            margin: 0.25rem;
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s;
        }

        .student-chip:hover {
            background-color: rgba(99, 102, 241, 0.2);
        }

        .student-chip button {
            background-color: transparent;
            border: none;
            color: var(--danger);
            margin-left: 0.5rem;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.2s;
        }

        .student-chip button:hover {
            transform: scale(1.2);
        }

        /* Multi-select styles */
        .multi-select {
            border: 1px solid var(--input);
            border-radius: 0.75rem;
            max-height: 200px;
            overflow-y: auto;
            background-color: white;
        }

        .multi-select option {
            padding: 0.75rem 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .multi-select option:hover {
            background-color: rgba(99, 102, 241, 0.1);
        }

        .multi-select option:checked {
            background-color: rgba(99, 102, 241, 0.2);
            color: var(--primary);
        }

        /* Scrollbar styles */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: rgba(243, 244, 246, 0.5);
            border-radius: 9999px;
        }

        ::-webkit-scrollbar-thumb {
            background: rgba(99, 102, 241, 0.5);
            border-radius: 9999px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: rgba(99, 102, 241, 0.7);
        }
    </style>
</head>

<body>
    <div class="max-w-7xl mx-auto p-6">
        <!-- Header con animación -->
        <div class="text-center mb-8 animate__animated animate__fadeInDown">
            <div class="flex justify-center items-center mb-4">
                <div class="relative">
                    <img src="../../public/images/logo.png" alt="Logo de la Institución" class="w-32 z-10 relative">
                    <div class="absolute inset-0 bg-indigo-500 filter blur-xl opacity-20 rounded-full"></div>
                </div>
            </div>
            <h2 class="text-4xl font-bold text-gray-800 mt-4 relative inline-block">
                Gestionar Asignaciones
                <span class="absolute bottom-0 left-0 w-full h-1.5 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 rounded-full"></span>
            </h2>
        </div>

        <!-- Botón de volver con animación -->
        <a href="../superadmin/dashboard.php" class="inline-flex items-center btn btn-primary px-6 py-2.5 rounded-full mb-6 animate__animated animate__fadeInLeft">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
            </svg>
            Volver al Menú Principal
        </a>

        <!-- Formulario para agregar asignaciones -->
        <form action="gestionar_asignaciones.php" method="post" class="card glass p-8 mb-8 fade-in">
            <div class="flex items-center mb-6">
                <div class="icon-container mr-4">
                    <div class="icon-pulse bg-indigo-500"></div>
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-indigo-500 relative z-10" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                </div>
                <h3 class="text-2xl font-bold text-gray-800">Nueva Asignación</h3>
            </div>

            <!-- Selección de Carrera -->
            <div class="mb-8">
                <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-indigo-500" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M10.394 2.08a1 1 0 00-.788 0l-7 3a1 1 0 000 1.84L5.25 8.051a.999.999 0 01.356-.257l4-1.714a1 1 0 11.788 1.838L7.667 9.088l1.94.831a1 1 0 00.787 0l7-3a1 1 0 000-1.838l-7-3zM3.31 9.397L5 10.12v4.102a8.969 8.969 0 00-1.05-.174 1 1 0 01-.89-.89 11.115 11.115 0 01.25-3.762zM9.3 16.573A9.026 9.026 0 007 14.935v-3.957l1.818.78a3 3 0 002.364 0l5.508-2.361a11.026 11.026 0 01.25 3.762 1 1 0 01-.89.89 8.968 8.968 0 00-5.35 2.524 1 1 0 01-1.4 0zM6 18a1 1 0 001-1v-2.065a8.935 8.935 0 00-2-.712V17a1 1 0 001 1z" />
                    </svg>
                    Seleccionar Carrera
                </h4>
                <div class="input-container">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path>
                    </svg>
                    <label for="carrera">Carrera</label>
                    <select id="carrera" name="carrera" required class="form-select">
                        <option value="" disabled selected></option>
                        <?php
                        $carreras = $carreraController->listarCarreras();
                        foreach ($carreras as $carrera) {
                            echo "<option value='{$carrera['id']}'>{$carrera['carrera']}</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="mt-4">
                    <button type="button" onclick="mostrarMaterias()" class="btn btn-secondary px-5 py-2.5 rounded-full">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
                        </svg>
                        Mostrar Materias
                    </button>
                </div>
            </div>

            <!-- Contenedor para mostrar las materias -->
            <div id="materias-container" style="display:none;" class="mb-8 scale-in">
                <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-indigo-500" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M9 4.804A7.968 7.968 0 005.5 4c-1.255 0-2.443.29-3.5.804v10A7.969 7.969 0 015.5 14c1.669 0 3.218.51 4.5 1.385A7.962 7.962 0 0114.5 14c1.255 0 2.443.29 3.5.804v-10A7.968 7.968 0 0014.5 4c-1.255 0-2.443.29-3.5.804V12a1 1 0 11-2 0V4.804z" />
                    </svg>
                    Seleccionar Materia
                </h4>
                <div class="input-container">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path>
                        <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path>
                    </svg>
                    <label for="materia_id">Materia</label>
                    <select id="materia_id" name="materia_id" required class="form-select"></select>
                </div>
            </div>

            <!-- Selección de Docente -->
            <div class="mb-8">
                <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-indigo-500" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z" />
                    </svg>
                    Seleccionar Docente
                </h4>
                <div class="input-container">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                        <circle cx="9" cy="7" r="4"></circle>
                        <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                        <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                    </svg>
                    <label for="docente_id">Docente</label>
                    <select id="docente_id" name="docente_id" required class="form-select">
                        <option value="" disabled selected></option>
                        <?php
                        $docentes = $docenteController->listarDocentes();
                        foreach ($docentes as $docente) {
                            echo "<option value='{$docente['cod_docente_int']}'>{$docente['nombres_varchar']}</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>

            <!-- Botón para mostrar estudiantes -->
            <div class="mb-8">
                <h4 class="text-lg font-semibold text-gray-700 mb-4 flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 text-indigo-500" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M10.394 2.08a1 1 0 00-.788 0l-7 3a1 1 0 000 1.84L5.25 8.051a.999.999 0 01.356-.257l4-1.714a1 1 0 11.788 1.838L7.667 9.088l1.94.831a1 1 0 00.787 0l7-3a1 1 0 000-1.838l-7-3zM3.31 9.397L5 10.12v4.102a8.969 8.969 0 00-1.05-.174 1 1 0 01-.89-.89 11.115 11.115 0 01.25-3.762zM9.3 16.573A9.026 9.026 0 007 14.935v-3.957l1.818.78a3 3 0 002.364 0l5.508-2.361a11.026 11.026 0 01.25 3.762 1 1 0 01-.89.89 8.968 8.968 0 00-5.35 2.524 1 1 0 01-1.4 0zM6 18a1 1 0 001-1v-2.065a8.935 8.935 0 00-2-.712V17a1 1 0 001 1z" />
                    </svg>
                    Seleccionar Estudiantes
                </h4>
                <div class="mt-4">
                    <button type="button" onclick="mostrarEstudiantes()" class="btn btn-secondary px-5 py-2.5 rounded-full">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                            <path d="M9 6a3 3 0 11-6 0 3 3 0 016 0zM17 6a3 3 0 11-6 0 3 3 0 016 0zM12.93 17c.046-.327.07-.66.07-1a6.97 6.97 0 00-1.5-4.33A5 5 0 0119 16v1h-6.07zM6 11a5 5 0 015 5v1H1v-1a5 5 0 015-5z" />
                        </svg>
                        Mostrar Estudiantes
                    </button>
                </div>
            </div>

            <!-- Contenedor para mostrar los estudiantes -->
            <div id="estudiantes-container" style="display:none;" class="mb-8 scale-in">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h5 class="text-md font-medium text-gray-700 mb-2">Estudiantes Disponibles:</h5>
                        <select id="estudiantes" class="multi-select w-full" size="10"></select>
                        <div class="mt-4 flex space-x-2">
                            <button type="button" onclick="seleccionarEstudiante()" class="btn btn-success px-4 py-2 rounded-full">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                                </svg>
                                Seleccionar
                            </button>
                            <button type="button" onclick="deseleccionarEstudiante()" class="btn btn-danger px-4 py-2 rounded-full">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                                    <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
                                </svg>
                                Deseleccionar
                            </button>
                        </div>
                    </div>
                    <div>
                        <h5 class="text-md font-medium text-gray-700 mb-2">Estudiantes Seleccionados:</h5>
                        <div id="estudiantes-seleccionados" class="border border-gray-200 rounded-lg p-4 min-h-[200px] bg-white overflow-y-auto">
                            <!-- Aquí se mostrarán los estudiantes seleccionados -->
                        </div>
                    </div>
                </div>
                <!-- Campo oculto para almacenar estudiantes seleccionados -->
                <input type="hidden" id="selected_estudiantes" name="estudiantes">
            </div>

            <!-- Fecha de Asignación y Estado -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                <div class="input-container">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                        <line x1="16" y1="2" x2="16" y2="6"></line>
                        <line x1="8" y1="2" x2="8" y2="6"></line>
                        <line x1="3" y1="10" x2="21" y2="10"></line>
                    </svg>
                    <label for="fecha_asignacion">Fecha de Asignación</label>
                    <input type="datetime-local" id="fecha_asignacion" name="fecha_asignacion" required class="form-input">
                </div>
                <div class="input-container">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                        <polyline points="22 4 12 14.01 9 11.01"></polyline>
                    </svg>
                    <label for="estado">Estado</label>
                    <select id="estado" name="estado" required class="form-select">
                        <option value="0">Activo</option>
                        <option value="1">Inactivo</option>
                    </select>
                </div>
            </div>

            <!-- Botón de envío -->
            <div class="text-center">
                <button type="submit" name="agregar" class="btn btn-primary px-8 py-3 rounded-full">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
                    </svg>
                    Agregar Asignación
                </button>
            </div>
        </form>

        <!-- Lista de Asignaciones -->
        <div class="card glass p-8 mb-8 fade-in">
            <div class="flex items-center mb-6">
                <div class="icon-container mr-4">
                    <div class="icon-pulse bg-blue-500"></div>
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-blue-500 relative z-10" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                </div>
                <h3 class="text-2xl font-bold text-gray-800">Lista de Asignaciones</h3>
            </div>

            <?php if (!empty($asignaciones)): ?>
                <div class="table-container glass">
                    <table class="table">
                        <thead>
                            <tr>
                                <th class="rounded-tl-lg">ID</th>
                                <th>Estudiante</th>
                                <th>Docente</th>
                                <th>Materia</th>
                                <th>Fecha de Asignación</th>
                                <th>Estado</th>
                                <th class="rounded-tr-lg">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($asignaciones as $index => $asignacion): ?>
                                <tr class="hover:bg-gray-50 transition-colors duration-150 ease-in-out" style="animation-delay: <?php echo $index * 0.05; ?>s">
                                    <td><?php echo $asignacion['id']; ?></td>
                                    <td class="font-medium"><?php echo $asignacion['estudiante_nombre']; ?></td>
                                    <td><?php echo $asignacion['docente_nombre']; ?></td>
                                    <td><?php echo $asignacion['materia_nombre']; ?></td>
                                    <td><?php echo $asignacion['fecha_asignacion']; ?></td>
                                    <td>
                                        <span class="badge <?php echo $asignacion['estado'] == 0 ? 'badge-success' : 'badge-danger'; ?>">
                                            <?php echo $asignacion['estado'] == 0 ? 'Activo' : 'Inactivo'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <a href="editar_asignacion.php?id=<?php echo $asignacion['id']; ?>" class="btn btn-warning text-white px-4 py-2 rounded-full inline-flex items-center">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
                                                <path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
                                            </svg>
                                            Editar
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="text-center py-8 text-gray-500">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-gray-400 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <p class="text-lg font-medium">No se encontraron asignaciones</p>
                    <p class="text-sm mt-2">Comienza agregando una nueva asignación usando el formulario de arriba</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
    // Variables para almacenar los estudiantes seleccionados
    let estudiantesSeleccionados = [];

    // Mostrar materias según la carrera seleccionada
    function mostrarMaterias() {
        const carreraId = document.getElementById('carrera').value;
        const materiasContainer = document.getElementById('materias-container');
        const materiaSelect = document.getElementById('materia_id');

        // Mostrar animación de carga
        Swal.fire({
            title: 'Cargando materias...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch(`get_materias.php?carrera_id=${carreraId}`)
            .then(response => response.json())
            .then(data => {
                Swal.close();
                
                if (data.error) {
                    console.error(data.error);
                    Swal.fire({
                        title: 'Error',
                        text: 'No se pudieron cargar las materias',
                        icon: 'error',
                        confirmButtonColor: '#ef4444'
                    });
                    return;
                }

                // Limpiar opciones anteriores
                materiaSelect.innerHTML = '<option value="" disabled selected></option>';

                data.materias.forEach(materia => {
                    const option = document.createElement('option');
                    option.value = materia.materia_id;
                    option.textContent = `${materia.nombre} (Semestre: ${materia.semestre})`;
                    materiaSelect.appendChild(option);
                });

                materiasContainer.style.display = 'block';
                
                // Animar la aparición
                materiasContainer.classList.add('scale-in');
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    title: 'Error',
                    text: 'Ocurrió un error al cargar las materias',
                    icon: 'error',
                    confirmButtonColor: '#ef4444'
                });
            });
    }

    // Mostrar estudiantes según la carrera seleccionada
    function mostrarEstudiantes() {
        const carreraId = document.getElementById('carrera').value;
        const estudiantesContainer = document.getElementById('estudiantes-container');

        // Mostrar animación de carga
        Swal.fire({
            title: 'Cargando estudiantes...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch(`get_estudiantes.php?carrera_id=${carreraId}`)
            .then(response => response.json())
            .then(data => {
                Swal.close();
                
                const estudiantesSelect = document.getElementById('estudiantes');
                estudiantesSelect.innerHTML = '';

                data.estudiantes.forEach(estudiante => {
                    const option = document.createElement('option');
                    option.value = estudiante.idRegistro;
                    option.textContent = estudiante.sname;
                    estudiantesSelect.appendChild(option);
                });

                estudiantesContainer.style.display = 'block';
                
                // Animar la aparición
                estudiantesContainer.classList.add('scale-in');
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    title: 'Error',
                    text: 'Ocurrió un error al cargar los estudiantes',
                    icon: 'error',
                    confirmButtonColor: '#ef4444'
                });
            });
    }

    // Seleccionar estudiante
    function seleccionarEstudiante() {
        const estudiantesSelect = document.getElementById('estudiantes');
        const estudiantesSeleccionadosDiv = document.getElementById('estudiantes-seleccionados');

        // Verificar si hay un estudiante seleccionado
        if (estudiantesSelect.selectedIndex === -1) {
            Swal.fire({
                title: 'Advertencia',
                text: 'Por favor, seleccione un estudiante primero',
                icon: 'warning',
                confirmButtonColor: '#f59e0b'
            });
            return;
        }

        // Obtener estudiante seleccionado
        const selectedOption = estudiantesSelect.options[estudiantesSelect.selectedIndex];

        // Verificar si el estudiante ya está seleccionado
        if (estudiantesSeleccionados.includes(selectedOption.value)) {
            Swal.fire({
                title: 'Información',
                text: 'El estudiante ya está seleccionado',
                icon: 'info',
                confirmButtonColor: '#3b82f6'
            });
            return;
        }

        // Añadir estudiante a la lista de seleccionados
        estudiantesSeleccionados.push(selectedOption.value);

        // Actualizar el campo oculto con los estudiantes seleccionados
        document.getElementById('selected_estudiantes').value = estudiantesSeleccionados.join(',');

        // Mostrar el estudiante en la lista de seleccionados
        const estudianteDiv = document.createElement('div');
        estudianteDiv.id = `estudiante-${selectedOption.value}`;
        estudianteDiv.className = 'student-chip';
        
        // Crear el contenido del chip
        estudianteDiv.innerHTML = `
            ${selectedOption.textContent}
            <button type="button" onclick="deseleccionarEstudiante('${selectedOption.value}')">×</button>
        `;
        
        estudiantesSeleccionadosDiv.appendChild(estudianteDiv);
        
        // Animar la aparición
        estudianteDiv.classList.add('scale-in');
    }

    // Deseleccionar estudiante
    function deseleccionarEstudiante(estudianteId) {
        // Si no se proporciona un ID, intentar obtenerlo del select
        if (!estudianteId) {
            const estudiantesSelect = document.getElementById('estudiantes');
            if (estudiantesSelect.selectedIndex === -1) {
                Swal.fire({
                    title: 'Advertencia',
                    text: 'Por favor, seleccione un estudiante para deseleccionar',
                    icon: 'warning',
                    confirmButtonColor: '#f59e0b'
                });
                return;
            }
            estudianteId = estudiantesSelect.options[estudiantesSelect.selectedIndex].value;
        }
        
        const index = estudiantesSeleccionados.indexOf(estudianteId);
        if (index > -1) {
            estudiantesSeleccionados.splice(index, 1);

            // Actualizar el campo oculto con los estudiantes seleccionados
            document.getElementById('selected_estudiantes').value = estudiantesSeleccionados.join(',');

            // Remover el estudiante de la visualización con animación
            const estudianteDiv = document.getElementById(`estudiante-${estudianteId}`);
            estudianteDiv.classList.add('animate__animated', 'animate__fadeOut');
            
            // Eliminar el elemento después de la animación
            setTimeout(() => {
                estudianteDiv.remove();
            }, 500);
        }
    }

    // Animación para las filas de la tabla
    document.addEventListener('DOMContentLoaded', function() {
        const rows = document.querySelectorAll('tbody tr');
        rows.forEach((row, index) => {
            row.style.animation = `fadeIn 0.3s cubic-bezier(0.4, 0, 0.2, 1) ${index * 0.1}s forwards`;
            row.style.opacity = '0';
        });
    });
    </script>
</body>

</html>

