<?php
include_once '../../controllers/CursoController.php';
$cursoController = new CursoController();
$cursos = $cursoController->listarCursos();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['agregar'])) {
        $resultado = $cursoController->agregarCurso(
            $_POST['nombre_curso'],
            $_POST['estado'],
            $_POST['detalle'],
            $_POST['sucursal']
        );
        if ($resultado) {
            $successMessage = "Curso agregado correctamente.";
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    Swal.fire({
                        icon: 'success',
                        title: 'Éxito',
                        text: '$successMessage',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(function() {
                        window.location.href = 'gestionar_cursos.php';
                    });
                });
            </script>";
        } else {
            $errorMessage = "Error al agregar curso.";
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: '$errorMessage'
                    });
                });
            </script>";
        }
    } elseif (isset($_POST['actualizar'])) {
        $resultado = $cursoController->actualizarCurso(
            $_POST['id'],
            $_POST['nombre_curso'],
            $_POST['estado'],
            $_POST['detalle'],
            $_POST['sucursal']
        );
        if ($resultado) {
            $successMessage = "Curso actualizado correctamente.";
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    Swal.fire({
                        icon: 'success',
                        title: 'Éxito',
                        text: '$successMessage',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(function() {
                        window.location.href = 'gestionar_cursos.php';
                    });
                });
            </script>";
        } else {
            $errorMessage = "Error al actualizar curso.";
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: '$errorMessage'
                    });
                });
            </script>";
        }
    } elseif (isset($_POST['eliminar'])) {
        // Manejar la eliminación del curso
        $resultado = $cursoController->eliminarCurso($_POST['id']);
        if ($resultado) {
            $successMessage = "Curso eliminado correctamente.";
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    Swal.fire({
                        icon: 'success',
                        title: 'Éxito',
                        text: '$successMessage',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(function() {
                        window.location.href = 'gestionar_cursos.php';
                    });
                });
            </script>";
        } else {
            $errorMessage = "Error al eliminar curso.";
            echo "<script>
                document.addEventListener('DOMContentLoaded', function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: '$errorMessage'
                    });
                });
            </script>";
        }
    }
}
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestionar Cursos</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#f0f9ff',
                            100: '#e0f2fe',
                            200: '#bae6fd',
                            300: '#7dd3fc',
                            400: '#38bdf8',
                            500: '#0ea5e9',
                            600: '#0284c7',
                            700: '#0369a1',
                            800: '#075985',
                            900: '#0c4a6e',
                        },
                        secondary: {
                            50: '#f8fafc',
                            100: '#f1f5f9',
                            200: '#e2e8f0',
                            300: '#cbd5e1',
                            400: '#94a3b8',
                            500: '#64748b',
                            600: '#475569',
                            700: '#334155',
                            800: '#1e293b',
                            900: '#0f172a',
                        },
                        accent: {
                            50: '#ecfdf5',
                            100: '#d1fae5',
                            200: '#a7f3d0',
                            300: '#6ee7b7',
                            400: '#34d399',
                            500: '#10b981',
                            600: '#059669',
                            700: '#047857',
                            800: '#065f46',
                            900: '#064e3b',
                        },
                        danger: {
                            50: '#fef2f2',
                            100: '#fee2e2',
                            200: '#fecaca',
                            300: '#fca5a5',
                            400: '#f87171',
                            500: '#ef4444',
                            600: '#dc2626',
                            700: '#b91c1c',
                            800: '#991b1b',
                            900: '#7f1d1d',
                        }
                    },
                    animation: {
                        'fade-in': 'fadeIn 0.5s ease-out',
                        'slide-up': 'slideUp 0.5s ease-out',
                        'slide-down': 'slideDown 0.5s ease-out',
                        'bounce-in': 'bounceIn 0.8s ease-out',
                    },
                    keyframes: {
                        fadeIn: {
                            '0%': { opacity: '0' },
                            '100%': { opacity: '1' },
                        },
                        slideUp: {
                            '0%': { transform: 'translateY(20px)', opacity: '0' },
                            '100%': { transform: 'translateY(0)', opacity: '1' },
                        },
                        slideDown: {
                            '0%': { transform: 'translateY(-20px)', opacity: '0' },
                            '100%': { transform: 'translateY(0)', opacity: '1' },
                        },
                        bounceIn: {
                            '0%': { transform: 'scale(0.8)', opacity: '0' },
                            '70%': { transform: 'scale(1.05)', opacity: '1' },
                            '100%': { transform: 'scale(1)', opacity: '1' },
                        },
                    },
                }
            }
        }
    </script>
    
    <!-- Alpine.js -->
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- Animate.css -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f2 100%);
            background-attachment: fixed;
        }
        
        .card-hover {
            transition: all 0.3s ease;
        }
        
        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .input-focus {
            transition: all 0.3s ease;
        }
        
        .input-focus:focus {
            border-color: #0ea5e9;
            box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.2);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #0ea5e9 0%, #0369a1 100%);
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #0284c7 0%, #075985 100%);
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #64748b 0%, #475569 100%);
            transition: all 0.3s ease;
        }
        
        .btn-secondary:hover {
            background: linear-gradient(135deg, #475569 0%, #334155 100%);
            transform: translateY(-2px);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #10b981 0%, #047857 100%);
            transition: all 0.3s ease;
        }
        
        .btn-success:hover {
            background: linear-gradient(135deg, #059669 0%, #065f46 100%);
            transform: translateY(-2px);
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            transition: all 0.3s ease;
        }
        
        .btn-warning:hover {
            background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
            transform: translateY(-2px);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #ef4444 0%, #b91c1c 100%);
            transition: all 0.3s ease;
        }
        
        .btn-danger:hover {
            background: linear-gradient(135deg, #dc2626 0%, #991b1b 100%);
            transform: translateY(-2px);
        }
        
        .table-row {
            transition: all 0.2s ease;
        }
        
        .table-row:hover {
            background-color: rgba(14, 165, 233, 0.05);
        }
        
        /* DataTables Custom Styling */
        .dataTables_wrapper .dataTables_length, 
        .dataTables_wrapper .dataTables_filter {
            margin-bottom: 1.5rem;
        }
        
        .dataTables_wrapper .dataTables_length select, 
        .dataTables_wrapper .dataTables_filter input {
            padding: 0.5rem;
            border-radius: 0.375rem;
            border: 1px solid #e2e8f0;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            margin: 0 0.25rem;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {
            background: #0ea5e9;
            color: white !important;
            border: none;
        }
        
        .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
            background: #0284c7;
            color: white !important;
            border: none;
        }
    </style>
</head>

<body class="min-h-screen py-8" x-data="{ showDeleteConfirm: false, cursoIdToDelete: null }">
    <div class="container mx-auto px-4 max-w-6xl" x-data="{ showForm: true }">
        <div class="text-center mb-8 animate_animated animate_fadeIn">
            <img src="../../public/images/logo.png" alt="Logo de la Institución" class="mx-auto h-24 object-contain mb-4">
            <h1 class="text-3xl font-bold text-gray-800 mb-2">Gestión de Cursos</h1>
            <p class="text-gray-600 mb-4">Administre los cursos de la institución</p>
            <a href="../superadmin/dashboard.php" class="inline-flex items-center px-4 py-2 rounded-lg bg-secondary-600 text-white hover:bg-secondary-700 transition-all duration-300 shadow-md">
                <i class="fas fa-arrow-left mr-2"></i> Volver al Menú Principal
            </a>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Formulario de Agregar Curso -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-xl overflow-hidden card-hover animate_animated animate_fadeInLeft">
                    <div class="bg-gradient-to-r from-primary-600 to-primary-700 px-6 py-4">
                        <div class="flex items-center justify-between">
                            <h2 class="text-xl font-semibold text-white">
                                <i class="fas fa-plus-circle mr-2"></i> Agregar Curso
                            </h2>
                            <button @click="showForm = !showForm" class="text-white hover:text-primary-100 transition-colors">
                                <i class="fas" :class="showForm ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
                            </button>
                        </div>
                    </div>
                    <div x-show="showForm" x-transition:enter="transition ease-out duration-300" 
                         x-transition:enter-start="opacity-0 transform -translate-y-4" 
                         x-transition:enter-end="opacity-100 transform translate-y-0"
                         class="px-6 py-4">
                        <form action="gestionar_cursos.php" method="post" class="space-y-4">
                            <div>
                                <label for="nombre_curso" class="block text-sm font-medium text-gray-700 mb-1">
                                    <i class="fas fa-book mr-1"></i> Nombre del Curso
                                </label>
                                <input type="text" id="nombre_curso" name="nombre_curso" required
                                       class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none input-focus"
                                       placeholder="Ingrese el nombre del curso">
                            </div>
                            
                            <div>
                                <label for="estado" class="block text-sm font-medium text-gray-700 mb-1">
                                    <i class="fas fa-toggle-on mr-1"></i> Estado
                                </label>
                                <select id="estado" name="estado" required
                                        class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none input-focus">
                                    <option value="0">Activo</option>
                                    <option value="1">Inactivo</option>
                                </select>
                            </div>
                            
                            <div>
                                <label for="detalle" class="block text-sm font-medium text-gray-700 mb-1">
                                    <i class="fas fa-info-circle mr-1"></i> Detalle
                                </label>
                                <input type="text" id="detalle" name="detalle" required
                                       class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none input-focus"
                                       placeholder="Ingrese el detalle del curso">
                            </div>
                            
                            <div>
                                <label for="sucursal" class="block text-sm font-medium text-gray-700 mb-1">
                                    <i class="fas fa-building mr-1"></i> Sucursal
                                </label>
                                <input type="text" id="sucursal" name="sucursal" required
                                       class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none input-focus"
                                       placeholder="Ingrese la sucursal">
                            </div>
                            
                            <button type="submit" name="agregar" 
                                    class="w-full py-2 px-4 rounded-lg text-white btn-success flex items-center justify-center">
                                <i class="fas fa-save mr-2"></i> Agregar Curso
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- Lista de Cursos -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-xl overflow-hidden card-hover animate_animated animate_fadeInRight">
                    <div class="bg-gradient-to-r from-primary-600 to-primary-700 px-6 py-4">
                        <h2 class="text-xl font-semibold text-white">
                            <i class="fas fa-list mr-2"></i> Lista de Cursos
                        </h2>
                    </div>
                    <div class="p-6">
                        <?php if (!empty($cursos)): ?>
                            <div class="overflow-x-auto">
                                <table id="tablaCursos" class="w-full text-sm text-left">
                                    <thead class="text-xs text-white uppercase bg-primary-700">
                                        <tr>
                                            <th class="px-6 py-3 rounded-tl-lg">ID</th>
                                            <th class="px-6 py-3">Nombre del Curso</th>
                                            <th class="px-6 py-3">Estado</th>
                                            <th class="px-6 py-3">Detalle</th>
                                            <th class="px-6 py-3">Sucursal</th>
                                            <th class="px-6 py-3 rounded-tr-lg">Acciones</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($cursos as $curso): ?>
                                            <tr class="bg-white border-b table-row">
                                                <td class="px-6 py-4"><?php echo $curso['id']; ?></td>
                                                <td class="px-6 py-4 font-medium"><?php echo $curso['nombre_curso']; ?></td>
                                                <td class="px-6 py-4">
                                                    <?php if ($curso['estado'] == 0): ?>
                                                        <span class="px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                                            <i class="fas fa-check-circle mr-1"></i> Activo
                                                        </span>
                                                    <?php else: ?>
                                                        <span class="px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
                                                            <i class="fas fa-times-circle mr-1"></i> Inactivo
                                                        </span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-6 py-4"><?php echo $curso['detalle']; ?></td>
                                                <td class="px-6 py-4"><?php echo $curso['sucursal']; ?></td>
                                                <td class="px-6 py-4 flex gap-2">
                                                    <a href="editar_curso.php?id=<?php echo $curso['id']; ?>" 
                                                       class="inline-flex items-center px-3 py-1 rounded-lg btn-warning text-white text-sm">
                                                        <i class="fas fa-edit mr-1"></i> Editar
                                                    </a>
                                                    <button type="button" 
                                                            @click="showDeleteConfirm = true; cursoIdToDelete = <?php echo $curso['id']; ?>"
                                                            class="inline-flex items-center px-3 py-1 rounded-lg btn-danger text-white text-sm">
                                                        <i class="fas fa-trash-alt mr-1"></i> Eliminar
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-8 animate_animated animate_fadeIn">
                                <i class="fas fa-folder-open text-gray-400 text-5xl mb-4"></i>
                                <p class="text-gray-500">No se encontraron cursos registrados.</p>
                                <p class="text-gray-400 text-sm mt-2">Utilice el formulario para agregar un nuevo curso.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Formulario oculto para eliminar -->
    <form id="deleteForm" action="gestionar_cursos.php" method="post" class="hidden">
        <input type="hidden" name="id" id="cursoIdInput">
        <input type="hidden" name="eliminar" value="1">
    </form>
    
    <!-- Modal de confirmación de eliminación -->
    <div x-show="showDeleteConfirm" 
         class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full p-6 animate_animated animatefadeInUp animate_faster">
            <div class="text-center mb-6">
                <div class="bg-red-50 rounded-full p-4 inline-block mb-4">
                    <i class="fas fa-exclamation-triangle text-red-500 text-3xl"></i>
                </div>
                <h3 class="text-xl font-bold text-gray-900 mb-2">¿Eliminar este curso?</h3>
                <p class="text-gray-600">Esta acción no se puede deshacer. ¿Está seguro de que desea eliminar permanentemente este curso?</p>
            </div>
            <div class="flex flex-col sm:flex-row gap-3 justify-center">
                <button @click="showDeleteConfirm = false" class="px-5 py-2.5 rounded-lg bg-gray-200 text-gray-800 font-medium hover:bg-gray-300 transition-colors">
                    Cancelar
                </button>
                <button @click="document.getElementById('cursoIdInput').value = cursoIdToDelete; document.getElementById('deleteForm').submit();" 
                        class="px-5 py-2.5 rounded-lg btn-danger text-white font-medium flex items-center justify-center">
                    <i class="fas fa-trash-alt mr-2"></i> Sí, eliminar
                </button>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Inicializar DataTables
            if (document.getElementById('tablaCursos')) {
                $('#tablaCursos').DataTable({
                    language: {
                        url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/es-ES.json',
                    },
                    responsive: true,
                    pageLength: 10,
                    dom: '<"flex flex-col md:flex-row justify-between items-start md:items-center mb-4"lf>rtip',
                    initComplete: function() {
                        // Agregar clases de Tailwind a los elementos de DataTables
                        $('.dataTables_length select').addClass('rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-200 focus:ring-opacity-50');
                        $('.dataTables_filter input').addClass('rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-200 focus:ring-opacity-50 ml-2');
                        $('.dataTables_paginate').addClass('mt-4');
                    }
                });
            }
            
            // Animación para las filas de la tabla
            const tableRows = document.querySelectorAll('tbody tr');
            tableRows.forEach((row, index) => {
                row.classList.add('animate_animated', 'animate_fadeIn');
                row.style.animationDelay = ${index * 0.05}s;
            });
            
            // Efecto de entrada para el formulario
            const formInputs = document.querySelectorAll('form input, form select');
            formInputs.forEach((input, index) => {
                input.classList.add('animate_animated', 'animate_fadeInUp');
                input.style.animationDelay = ${index * 0.1}s;
            });
        });
    </script>
</body>

</html>