@extends('layouts.master')
@section('title') Inicio @endsection
@section('content')
<!-- this is breadcrumbs -->
@component('components.breadcrumb')
@slot('li_1') Inicio @endslot
@slot('li_2') Panel Academico @endslot
@slot('title') Unidades Didacticas @endslot
@endcomponent

<!-- start page content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body mb-n3">
                

                <div class="table-responsive">
                
                <form id="form-curso" method="POST">
                    @csrf

                    <div class="card shadow-sm mb-4">
                        <div class="card-header bg-primary text-white fw-semibold">
                            <i class="fas fa-book me-2"></i>Registrar Curso
                        </div>
                        <div class="card-body">
                            <div class="row g-4">
                                {{-- Columna 1 --}}
                                <div class="col-md-4">
                                    <h6 class="text-secondary mb-3">Información del Curso</h6>

                                    <div class="mb-3">
                                        <label for="nombre" class="form-label">Nombre</label>
                                        <input type="text" name="nombre" class="form-control" required>
                                    </div>

                                    <div class="mb-3">
                                        <label for="tipo" class="form-label">Tipo</label>
                                        <select name="tipo" class="form-select" required>
                                            <option value="">Seleccione</option>
                                            <option value="Especialidad">Especialidad</option>
                                            <option value="Transversal">Transversal</option>
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="descripcion" class="form-label">Descripción</label>
                                        <textarea name="descripcion" class="form-control" rows="4" placeholder="Descripción breve..."></textarea>
                                    </div>
                                </div>

                                {{-- Columna 2 --}}
                                <div class="col-md-4">
                                    <h6 class="text-secondary mb-3">Carga Académica</h6>

                                    <div class="mb-3">
                                        <label for="creditos" class="form-label">Créditos</label>
                                        <input type="text" name="creditos" class="form-control">
                                    </div>

                                    <div class="mb-3">
                                        <label for="horas_semestrales" class="form-label">Horas Semestrales</label>
                                        <input type="number" name="horas_semestrales" class="form-control">
                                    </div>

                                    <div class="mb-3">
                                        <label for="orden" class="form-label">Orden</label>
                                        <input type="number" name="orden" class="form-control">
                                    </div>

                                    <div class="mb-3">
                                        <label for="semestre_id" class="form-label">Semestre</label>
                                        <select name="semestre_id" class="form-select" required>
                                            <option value="">Seleccione</option>
                                            @foreach($semestres as $semestre)
                                                <option value="{{ $semestre->id }}">{{ $semestre->nombre }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>

                                {{-- Columna 3 --}}
                                <div class="col-md-4">
                                    <h6 class="text-secondary mb-3">Asociación Curricular</h6>

                                    <div class="mb-3">
                                        <label for="planes_estudio" class="form-label">Plan de Estudio</label>
                                        <select name="planes_estudio[]" id="planes_estudio" class="form-select" required>
                                            <option value="">Seleccione</option>
                                            @foreach($planesEstudio as $plan)
                                                <option value="{{ $plan->id }}">{{ $plan->nombre }}</option>
                                            @endforeach
                                        </select>
                                    </div>

                                    <div class="mb-3">
                                        <label for="id_modulo" class="form-label">Módulo Formativo</label>
                                        <select name="id_modulo" id="id_modulo" class="form-select" required>
                                            <option value="">Seleccione un plan primero</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- Botones --}}
                    <div class="d-flex justify-content-end gap-2">
                        <a href="{{ route('cursos.index') }}" class="btn btn-outline-danger">
                            <i class="fas fa-times"></i> Cancelar
                        </a>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-save me-1"></i> Guardar Curso
                        </button>
                    </div>
                </form>

                </div>
            </div>
            <!--end card-body-->
        </div>
        <!--end card-->
    </div>
    <!--end col-->
</div>







<!--end row-->


@endsection
@section('script')
<!-- jQuery y DataTables -->

<!-- jQuery y DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<!-- DataTables Buttons -->
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.colVis.min.js"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function () {
        $("#tablaCursos").DataTable({
            "responsive": true,
            "lengthChange": true,
            "autoWidth": false,
            "buttons": [
                {
                    extend: 'collection',
                    text: 'Opciones',
                    buttons: [
                        { extend: 'copy', text: 'Copiar' },
                        { extend: 'csv', text: 'CSV' },
                        { extend: 'excel', text: 'Excel', title: 'Periodos Académicos' },
                        { extend: 'pdf', text: 'PDF' },
                        { extend: 'print', text: 'Imprimir' }
                    ]
                },
                { extend: 'colvis', text: 'Visibilidad de Columna' }
            ],
            "paging": true,
            "searching": true,
            "info": true,
            "language": {
                "search": "Buscar:",
                "lengthMenu": "Mostrar _MENU_ registros por página",
                "info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
                "paginate": {
                    "first": "Primero",
                    "previous": "Anterior",
                    "next": "Siguiente",
                    "last": "Último"
                }
            }
        }).buttons().container().appendTo('#tablaCursos_wrapper .col-md-6:eq(0)');
    });
</script>


<script>
    // Cuando se cambie el plan de estudio
    document.getElementById('planes_estudio').addEventListener('change', function () {
        const planId = this.value;

        if (!planId) return;

        fetch(`/modulos-por-plan/${planId}`)
            .then(response => response.json())
            .then(data => {
                const moduloSelect = document.getElementById('id_modulo');
                moduloSelect.innerHTML = '<option value="">Seleccione</option>';

                data.forEach(modulo => {
                    const option = document.createElement('option');
                    option.value = modulo.id_modulo;
                    option.text = modulo.nombre;
                    moduloSelect.appendChild(option);
                });
            })
            .catch(error => {
                console.error('Error al cargar módulos:', error);
            });
    });

    // Enviar el formulario con AJAX
    document.getElementById('form-curso').addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        
        fetch("{{ route('cursos.store') }}", {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Alerta de éxito
                Swal.fire({
                    icon: 'success',
                    title: '¡Curso Guardado!',
                    text: data.message,
                    confirmButtonText: 'OK'
                }).then(() => {
                    window.location.href = "{{ route('cursos.index') }}";
                });
            } else {
                // Alerta de error
                Swal.fire({
                    icon: 'error',
                    title: '¡Error!',
                    text: data.message,
                    confirmButtonText: 'Reintentar'
                });
            }
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: '¡Algo salió mal!',
                text: 'Hubo un error al guardar el curso. Intenta nuevamente.',
                confirmButtonText: 'Reintentar'
            });
            console.error('Error:', error);
        });
    });
</script>




@endsection
