<div>
    {{-- Modal --}}
    <div wire:ignore.self class="modal fade" id="modalDocente" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Agregar Docente al Grupo</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {{-- Docente --}}
                    <div class="mb-3">
                        <label>Docente</label>
                        <select class="form-control" wire:model="docente_id">
                            <option value="">Seleccionar docente...</option>
                            @foreach ($docentes as $docente)
                                @php $usr = $docente->docentes->first() @endphp
                                <option value="{{ $docente->id }}">
                                    {{ $usr?->name }}
                                    {{ $usr?->apellidoPaterno }}
                                </option>
                            @endforeach
                        </select>
                        @error('docente_id')
                            <span class="text-danger small">{{ $message }}</span>
                        @enderror
                    </div>

                    {{-- Materia --}}
                    <div class="mb-3">
                        <label>Materia</label>
                        <select class="form-control" wire:model="materia_id">
                            <option value="">Seleccionar materia...</option>
                            @foreach ($materiasSelect as $materia)
                                <option value="{{ $materia->id }}">
                                    ciclo {{ $materia->ciclo }} - {{ $materia->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('materia_id')
                            <span class="text-danger small">{{ $message }}</span>
                        @enderror
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <button wire:click="guardar" class="btn btn-success">Guardar</button>
                </div>
            </div>
        </div>
    </div>

    {{-- Tabla docentes asignados --}}
        <table id="tcont2" class="table table-striped table-bordered table-hover" style="width:100%;">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Materia</th>
                    <th>Ciclo</th>
                    <th>Docente asignado</th>
                    @hasrole('Coordinación académica')
                    <th>Opciones</th>
                                @endhasrole

                </tr>
            </thead>
            <tbody>
                @forelse ($materias as $materia)
                    @php
                        $docenteAsignado = $grupo->docentes->firstWhere('pivot.materia_id', $materia->id);
                        $usr = $docenteAsignado?->docentes->first();
                    @endphp
                    <tr>
                        <td>{{ $materia->id }}</td>
                        <td>{{ $materia->name }}</td>
                        <td>{{ $materia->ciclo }}</td>
                        <td>
                            @if($usr)
                                {{ $usr->name }} {{ $usr->apellidoPaterno }}
                            @else
                                <span class="badge badge-secondary">Sin docente</span>
                            @endif
                        </td>


                                @hasrole('Coordinación académica')
                                <td>
                                    @if($docenteAsignado)
                                    <button
                                        onclick="confirmarEliminar({{ $docenteAsignado->id }}, {{ $materia->id }}, '{{ $usr?->name }} {{ $usr?->apellidoPaterno }}', '{{ $materia->name }}')"
                                        style="border:none; background:none;">
                                        <i class="fa-regular fa-circle-user-circle-minus fa-2xl" style="color: rgb(255, 0, 0);"></i>
                                    </button>
                                    @endif
                            </td>

                                @endhasrole

                    </tr>
                @empty
                    <tr>Sin materias en este plan.</tr>
                @endforelse
            </tbody>
    </table>

</div>


@push('scripts')
<script>


document.addEventListener('DOMContentLoaded', initTable);

document.addEventListener('livewire:init', () => {
    // ✅ Este hook es el correcto para Livewire v3
    Livewire.hook('commit', ({ component, succeed }) => {
        succeed(() => {
            setTimeout(() => initTable(), 50);
        });
    });
});

    function confirmarEliminar(docenteId, materiaId, nombreDocente, nombreMateria) {
        Swal.fire({
            title: "¿Eliminar docente?",
            html: `¿Deseas quitar a <b>${nombreDocente}</b> de <b>${nombreMateria}</b>?`,
            icon: "warning",
            showCancelButton: true,
            confirmButtonText: "Sí, eliminar",
            cancelButtonText: "Cancelar",
            confirmButtonColor: '#e74a3b',
        }).then((result) => {
            if (result.isConfirmed) {
                @this.eliminar(docenteId, materiaId);
            }
        });
    }

    function initTable() {
    // ✅ Destroy correcto
    if ($.fn.DataTable.isDataTable('#tcont2')) {
        $('#tcont2').DataTable().destroy();
        $('#tcont2').empty(); // limpia el DOM completamente
    }

    new DataTable('#tcont2', {
        retrieve: true, // ✅ evita el error de reinicialización
        responsive: true,
        order: [],
        language: {
            "decimal": "",
            "emptyTable": "No hay información",
            "info": "Mostrando _START_ a _END_ de _TOTAL_ Entradas",
            "infoEmpty": "Mostrando 0 to 0 of 0 Entradas",
            "infoFiltered": "(Filtrado de _MAX_ total entradas)",
            "infoPostFix": "",
            "thousands": ",",
            "lengthMenu": "Mostrar _MENU_ Entradas",
            "loadingRecords": "Cargando...",
            "processing": "Procesando...",
            "search": "Buscar:",
            "zeroRecords": "Sin resultados encontrados"
        },
        lengthMenu: [
            [10, 25, 50, -1],
            ['10 filas', '25 filas', '50 filas', 'Todos']
        ],
        layout: {
            topStart: {
                buttons: ['colvis', 'pageLength']
            },
            topEnd: ['search'],
            bottomStart: [{
                buttons: [
                    { extend: 'excel', title: 'Excel' },
                    { extend: 'pdfHtml5', title: 'PDF' },
                    { extend: 'print' }
                ]
            }, 'info'],
        }
    });

    $("#tcont2_wrapper").removeClass("form-inline");
    $("#tcont2_wrapper").addClass("w-100");
}

    document.addEventListener('livewire:init', () => {
        Livewire.on('open-modal-docente', () => {
            $('#modalDocente').modal('show');
        });
        Livewire.on('close-modal-docente', () => {
            $('#modalDocente').modal('hide');
        });
    });
</script>
@endpush
