<?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/AsignarMateriaController.php';
$asignarMateriaController = new AsignarMateriaController();

include_once '../../controllers/EstudianteController.php';
$estudianteController = new EstudianteController();

include_once '../../controllers/DocenteController.php';
$docenteController = new DocenteController();
$docentes = $docenteController->listarDocentes();

include_once '../../controllers/MateriaController.php';
$materiaController = new MateriaController();
$materias = $materiaController->listarMaterias();

if (isset($_GET['id'])) {
    $asignacion = $asignarMateriaController->obtenerAsignacionPorId($_GET['id']);
    if ($asignacion) {
        $estudianteSeleccionado = $estudianteController->obtenerEstudiantePorId($asignacion['student_id']);
        if (!$estudianteSeleccionado) {
            error_log("Error: No se encontró el estudiante con ID " . $asignacion['student_id']);
        }
    } else {
        $estudianteSeleccionado = false;
    }
} else {
    $estudianteSeleccionado = false;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['actualizar'])) {
    $resultado = $asignarMateriaController->actualizarAsignacion(
        $_POST['id'],
        $_POST['student_id'],
        $_POST['docente_id'],
        $_POST['materia_id'],
        $_POST['fecha_asignacion'],
        $_POST['estado']
    );
    if ($resultado) {
        echo "<script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    title: '¡Éxito!',
                    text: 'Asignación actualizada 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: 'Error',
                    text: 'Error al actualizar la asignación',
                    icon: 'error',
                    confirmButtonColor: '#ef4444'
                });
            });
        </script>";
    }
}
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Editar Asignación</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-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-input:disabled {
            background-color: #f1f5f9;
            cursor: not-allowed;
        }

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

        .input-container .disabled-label {
            background-color: #f1f5f9;
        }

        .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;
            }
        }
    </style>
</head>

<body>
    <div class="max-w-3xl 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-3xl font-bold text-gray-800 mt-4 relative inline-block">
                Editar Asignación
                <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>

        <!-- Contenedor principal -->
        <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-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">Información de la Asignación</h3>
            </div>
            
            <?php if ($estudianteSeleccionado): ?>
                <form action="editar_asignacion.php?id=<?php echo $asignacion['id']; ?>" method="post" class="space-y-6">
                    <input type="hidden" name="id" value="<?php echo $asignacion['id']; ?>">
                    
                    <!-- Estudiante (disabled) -->
                    <div class="slide-in input-container" style="animation-delay: 0.1s">
                        <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="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
                            <circle cx="12" cy="7" r="4"></circle>
                        </svg>
                        <label for="student_name" class="disabled-label">Estudiante</label>
                        <input type="text" id="student_name" value="<?php echo $estudianteSeleccionado['nombre']; ?>" disabled class="form-input">
                        <input type="hidden" id="student_id" name="student_id" value="<?php echo $asignacion['student_id']; ?>" required>
                    </div>
                    
                    <!-- Docente -->
                    <div class="slide-in input-container" style="animation-delay: 0.2s">
                        <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">
                            <?php
                            foreach ($docentes as $docente) {
                                echo "<option value='" . $docente['cod_docente_int'] . "' " . ($asignacion['docente_id'] == $docente['cod_docente_int'] ? 'selected' : '') . ">" . $docente['nombres_varchar'] . "</option>";
                            }
                            ?>
                        </select>
                    </div>
                    
                    <!-- Materia -->
                    <div class="slide-in input-container" style="animation-delay: 0.3s">
                        <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">
                            <?php
                            foreach ($materias as $materia) {
                                echo "<option value='" . $materia['materia_id'] . "' " . ($asignacion['materia_id'] == $materia['materia_id'] ? 'selected' : '') . ">" . $materia['materia_nombre'] . "</option>";
                            }
                            ?>
                        </select>
                    </div>
                    
                    <!-- Fecha de Asignación -->
                    <div class="slide-in input-container" style="animation-delay: 0.4s">
                        <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" value="<?php echo date('Y-m-d\TH:i', strtotime($asignacion['fecha_asignacion'])); ?>" required class="form-input">
                    </div>
                    
                    <!-- Estado -->
                    <div class="slide-in input-container" style="animation-delay: 0.5s">
                        <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" <?php echo $asignacion['estado'] == 0 ? 'selected' : ''; ?>>Activo</option>
                            <option value="1" <?php echo $asignacion['estado'] == 1 ? 'selected' : ''; ?>>Inactivo</option>
                        </select>
                    </div>
                    
                    <!-- Botones de acción -->
                    <div class="flex justify-center space-x-4 pt-4">
                        <button type="button" onclick="confirmarCancelar()" class="btn btn-danger px-6 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="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>
                            Cancelar
                        </button>
                        <button type="submit" name="actualizar" class="btn btn-primary px-6 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="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
                            </svg>
                            Guardar Cambios
                        </button>
                    </div>
                </form>
            <?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 encontró la asignación</p>
                    <p class="text-sm mt-2">La asignación que intentas editar no existe o ha sido eliminada</p>
                    <a href="gestionar_asignaciones.php" class="btn btn-primary px-6 py-2.5 rounded-full inline-flex items-center mt-4">
                        <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 a Asignaciones
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
    // Función para confirmar cancelación
    function confirmarCancelar() {
        Swal.fire({
            title: '¿Estás seguro?',
            text: "Los cambios no guardados se perderán",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Sí, cancelar',
            cancelButtonText: 'No, continuar editando'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'gestionar_asignaciones.php';
            }
        });
    }

    // Animación para los elementos del formulario
    document.addEventListener('DOMContentLoaded', function() {
        const formElements = document.querySelectorAll('.input-container');
        formElements.forEach((element, index) => {
            element.style.animationDelay = `${index * 0.1}s`;
        });
    });
    </script>
</body>

</html>

