@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') Aulas @endslot
@endcomponent

<!-- start page content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body mb-n3">
                <button type="button" class="btn btn-de-primary btn-sm px-4 mt-0 mb-3" 
                    data-bs-toggle="modal" 
                    data-bs-target="#modalNuevaAula">
                    <i class="fas fa-plus"></i> Agregar Nueva Aula
                </button>
                <div class="table-responsive">
                    <table id="tablaAulas" class="table table-striped mb-0 table-hover">
                        <thead class="thead-light">
                            <tr>
                                <th>ID</th>
                                <th>Nombre</th>
                                <th>N° de Aula</th>
                                <th>Capacidad</th>
                                <th>Pabellón</th>
                                <th>Tipo</th>
                                <th class="text-center">Acciones</th>
                            </tr>
                        </thead>

                        <tbody>
                            @foreach ($aulas as $aula)
                                <tr>
                                    <td>{{ $aula->id }}</td>
                                    <td>{{ $aula->nombre }}</td>
                                    <td>{{ $aula->numero_aula }}</td>
                                    <td>{{ $aula->capacidad ?? '-' }}</td>
                                    <td>{{ $aula->pabellon->nombre ?? '-' }}</td>
                                    <td>{{ $aula->tipo ?? '-' }}</td>

                                    <td class="text-center">

                                        <!-- EDITAR -->
                                        <a href="#"
                                        class="text-warning btn-editar-aula"
                                        data-bs-toggle="modal"
                                        data-bs-target="#modalEditarAula"
                                        data-id="{{ $aula->id }}"
                                        data-nombre="{{ $aula->nombre }}"
                                        data-numero="{{ $aula->numero_aula }}"
                                        data-capacidad="{{ $aula->capacidad }}"
                                        data-id_pabellon="{{ $aula->id_pabellon }}"
                                        data-tipo="{{ $aula->tipo }}">
                                            <i class="las la-pen text-secondary font-18"></i>
                                        </a>

                                        <!-- ELIMINAR -->
                                        <a href="#"
                                        class="text-danger btn-eliminar-aula"
                                        data-id="{{ $aula->id }}">
                                            <i class="las la-trash-alt text-secondary font-18"></i>
                                        </a>

                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>



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

<!-- MODAL REGISTRAR AULA -->
<div class="modal fade" id="modalNuevaAula" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Registrar Nueva Aula</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>

            <form id="formNuevaAula">
                @csrf

                <div class="modal-body">

                    {{-- NOMBRE --}}
                    <div class="mb-3">
                        <label class="form-label">Nombre del Aula</label>
                        <input type="text" name="nombre" class="form-control" required>
                    </div>

                    {{-- NÚMERO DE AULA (NUEVO) --}}
                    <div class="mb-3">
                        <label class="form-label">Número de Aula</label>
                        <input type="text" name="numero_aula" class="form-control" placeholder="Ej: 101, B-203, L-05">
                    </div>

                    {{-- CAPACIDAD --}}
                    <div class="mb-3">
                        <label class="form-label">Capacidad</label>
                        <input type="number" name="capacidad" class="form-control" min="1">
                    </div>

                    {{-- PABELLÓN --}}
                    <div class="mb-3">
                        <label class="form-label">Pabellón</label>
                        <select name="id_pabellon" class="form-select" required>
                            <option value="">-- Seleccionar --</option>
                            @foreach($pabellones as $p)
                                <option value="{{ $p->id }}">{{ $p->nombre }}</option>
                            @endforeach
                        </select>
                    </div>

                    {{-- TIPO --}}
                    <div class="mb-3">
                        <label class="form-label">Tipo de Aula</label>
                        <select name="tipo" class="form-select" required>
                            <option value="">-- Seleccionar --</option>
                            <option value="Aula">Aula</option>
                            <option value="Laboratorio">Laboratorio</option>
                        </select>
                    </div>

                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                    <button type="submit" class="btn btn-de-primary">Guardar</button>
                </div>

            </form>

        </div>
    </div>
</div>



<!-- MODAL EDITAR AULA -->
<div class="modal fade" id="modalEditarAula" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">

            <div class="modal-header bg-warning">
                <h5 class="modal-title">Editar Aula</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <form id="formEditarAula">
                @csrf
                @method('PUT')

                <input type="hidden" id="edit_id" name="id">

                <div class="modal-body">

                    {{-- NOMBRE --}}
                    <div class="mb-3">
                        <label class="form-label">Nombre del Aula</label>
                        <input type="text" id="edit_nombre" name="nombre" class="form-control" required>
                    </div>

                    {{-- NÚMERO DE AULA --}}
                    <div class="mb-3">
                        <label class="form-label">Número de Aula</label>
                        <input type="text" id="edit_numero_aula" name="numero_aula" class="form-control" placeholder="Ej: 101, B-203, L-01">
                    </div>

                    {{-- CAPACIDAD --}}
                    <div class="mb-3">
                        <label class="form-label">Capacidad</label>
                        <input type="number" id="edit_capacidad" name="capacidad" class="form-control">
                    </div>

                    {{-- PABELLÓN --}}
                    <div class="mb-3">
                        <label class="form-label">Pabellón</label>
                        <select id="edit_id_pabellon" name="id_pabellon" class="form-select" required>
                            <option value="">-- Seleccionar --</option>
                            @foreach($pabellones as $p)
                                <option value="{{ $p->id }}">{{ $p->nombre }}</option>
                            @endforeach
                        </select>
                    </div>

                    {{-- TIPO --}}
                    <div class="mb-3">
                        <label class="form-label">Tipo de Aula</label>
                        <select id="edit_tipo" name="tipo" class="form-select" required>
                            <option value="Aula">Aula</option>
                            <option value="Laboratorio">Laboratorio</option>
                        </select>
                    </div>

                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
                    <button type="submit" class="btn btn-warning">Guardar Cambios</button>
                </div>

            </form>

        </div>
    </div>
</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 () {
        $("#tablaAulas").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('#tablaAulas_wrapper .col-md-6:eq(0)');
    });
</script>


<script>
/* ============================
    REGISTRAR AULA (AJAX)
============================ */
$('#formNuevaAula').on('submit', function(e){
    e.preventDefault();

    let formData = new FormData(this);

    $.ajax({
        url: "{{ route('aulas.store') }}",
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        beforeSend: () => Swal.showLoading(),

        success: function(res){
            Swal.close();

            Swal.fire({
                icon: "success",
                title: "Registrado",
                text: res.message,
                timer: 1500,
                showConfirmButton: false
            });

            setTimeout(() => location.reload(), 1600);
        },

        error: function(xhr){
            Swal.close();
            Swal.fire("Error", "No se pudo registrar el aula", "error");
        }
    });
});


/* ============================
    ABRIR MODAL EDITAR
============================ */
$(document).on('click', '.btn-editar-aula', function () {

    $('#edit_id').val($(this).data('id'));
    $('#edit_nombre').val($(this).data('nombre'));
    $('#edit_numero_aula').val($(this).data('numero')); // 🆕
    $('#edit_capacidad').val($(this).data('capacidad'));
    $('#edit_id_pabellon').val($(this).data('id_pabellon'));
    $('#edit_tipo').val($(this).data('tipo'));

    new bootstrap.Modal(document.getElementById('modalEditarAula')).show();
});


/* ============================
    ACTUALIZAR AULA (AJAX)
============================ */
$('#formEditarAula').on('submit', function(e){
    e.preventDefault();

    let id = $('#edit_id').val();
    let formData = new FormData(this);

    $.ajax({
        url: "/aulas/" + id,
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        beforeSend: () => Swal.showLoading(),

        success: function (res) {
            Swal.close();

            Swal.fire({
                icon: "success",
                title: "Actualizado",
                text: res.message,
                timer: 1500,
                showConfirmButton: false
            });

            setTimeout(() => location.reload(), 1600);
        },

        error: function () {
            Swal.close();
            Swal.fire("Error", "No se pudo actualizar el aula", "error");
        }
    });

});



/* ============================
    ELIMINAR AULA (AJAX)
============================ */
$(document).on('click', '.btn-eliminar-aula', function () {
    
    let id = $(this).data('id');

    Swal.fire({
        title: "¿Eliminar aula?",
        text: "Esta acción no se puede deshacer.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sí, eliminar",
        cancelButtonText: "Cancelar"
    }).then((result) => {

        if (result.isConfirmed) {

            $.ajax({
                url: "/aulas/" + id,
                type: "DELETE",
                data: {_token: "{{ csrf_token() }}"},

                success: function (res) {
                    Swal.fire("Eliminado", res.message, "success");
                    setTimeout(() => location.reload(), 1500);
                },

                error: function () {
                    Swal.fire("Error", "No se pudo eliminar el aula", "error");
                }
            });
        }

    });

});
</script>


@endsection
