<div>
    {{-- Modal: Agregar docente --}}
    <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">Asignar Docente al Grupo</h5>
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <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?->apellidoPaterno }} {{ $usr?->apellidoMaterno }} {{ $usr?->name }}
                                </option>
                            @endforeach
                        </select>
                        @error('docente_id')<span class="text-danger small">{{ $message }}</span>@enderror
                    </div>
                    <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>

    {{-- Modal: Reemplazar docente --}}
    <div wire:ignore.self class="modal fade" id="modalReemplazo" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Reemplazar Docente</h5>
                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info mb-3">
                        <i class="fas fa-info-circle"></i>
                        Materia: <strong>{{ $reemplazoMateriaNombre }}</strong><br>
                        <small>Las tareas ya asignadas por el docente actual se conservarán y quedarán bajo el nuevo docente.</small>
                    </div>
                    <div class="mb-3">
                        <label>Nuevo docente</label>
                        <select class="form-control" wire:model="reemplazoDocenteId">
                            <option value="">Seleccionar docente...</option>
                            @foreach ($docentes as $docente)
                                @php $usr = $docente->docentes->first() @endphp
                                @if ($docente->id != $reemplazoDocenteActualId)
                                    <option value="{{ $docente->id }}">
                                        {{ $usr?->apellidoPaterno }} {{ $usr?->apellidoMaterno }} {{ $usr?->name }}
                                    </option>
                                @endif
                            @endforeach
                        </select>
                        @error('reemplazoDocenteId')<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="reemplazar" class="btn btn-warning">
                        <i class="fas fa-exchange-alt fa-sm"></i> Confirmar reemplazo
                    </button>
                </div>
            </div>
        </div>
    </div>

    {{-- Tabla materias / docentes --}}
    <table id="tcont2" class="table table-striped table-bordered table-hover" style="width:100%;">
        <thead>
            <tr>
                <th>Materia</th>
                <th>Ciclo</th>
                <th>Docente asignado</th>
                @hasrole('Coordinación académica')
                <th>Ver tareas</th>
                <th>Acciones</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->name }}</td>
                    <td>{{ $materia->ciclo }}</td>
                    <td>
                        @if ($usr)
                            {{ $usr->apellidoPaterno }} {{ $usr->apellidoMaterno }} {{ $usr->name }}
                        @else
                            <span class="badge badge-secondary">Sin docente</span>
                        @endif
                    </td>

                    @hasrole('Coordinación académica')
                    {{-- Columna Ver tareas --}}
                    <td>
                        @if ($docenteAsignado)
                            <a href="{{ route('grupo.material.tareas', [$grupo->id, $materia->id]) }}"
                               class="btn btn-sm btn-info">
                                <i class="fas fa-tasks fa-sm"></i> Ver tareas
                            </a>
                        @else
                            <span class="text-muted small">Sin asignar</span>
                        @endif
                    </td>
                    {{-- Columna Acciones --}}
                    <td>
                        @if ($docenteAsignado)
                            <button
                                wire:click="abrirReemplazo({{ $docenteAsignado->id }}, {{ $materia->id }}, '{{ addslashes($materia->name) }}')"
                                class="btn btn-sm btn-warning" title="Reemplazar docente">
                                <i class="fas fa-exchange-alt fa-sm"></i> Reemplazar
                            </button>
                            <button
                                onclick="confirmarEliminar({{ $docenteAsignado->id }}, {{ $materia->id }}, '{{ $usr?->apellidoPaterno }} {{ $usr?->name }}', '{{ addslashes($materia->name) }}')"
                                class="btn btn-sm btn-danger" title="Quitar docente">
                                <i class="fas fa-user-minus fa-sm"></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', () => {
    Livewire.hook('commit', ({ component, succeed }) => {
        succeed(() => setTimeout(() => initTable(), 50));
    });

    Livewire.on('open-modal-docente',   () => $('#modalDocente').modal('show'));
    Livewire.on('close-modal-docente',  () => $('#modalDocente').modal('hide'));
    Livewire.on('open-modal-reemplazo', () => $('#modalReemplazo').modal('show'));
    Livewire.on('close-modal-reemplazo',() => $('#modalReemplazo').modal('hide'));
});

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

function initTable() {
    if ($.fn.DataTable.isDataTable('#tcont2')) {
        $('#tcont2').DataTable().destroy();
        $('#tcont2').empty();
    }
    new DataTable('#tcont2', {
        retrieve: true,
        responsive: true,
        order: [],
        language: {
            emptyTable: "No hay información",
            info: "Mostrando _START_ a _END_ de _TOTAL_ entradas",
            infoEmpty: "Mostrando 0 de 0 entradas",
            infoFiltered: "(filtrado de _MAX_ entradas)",
            lengthMenu: "Mostrar _MENU_ entradas",
            loadingRecords: "Cargando...",
            processing: "Procesando...",
            search: "Buscar:",
            zeroRecords: "Sin resultados",
            thousands: ",",
        },
        lengthMenu: [[10, 25, 50, -1], ['10', '25', '50', '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").addClass("w-100");
}
</script>
@endpush
