

<?php $__env->startSection('title', 'Atribuir Disciplinas - SGE'); ?>

<?php $__env->startSection('content'); ?>
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-2" style="border-bottom: 1px solid #dee2e6; padding-bottom: 8px;">
            <div>
                <h5 class="mb-0" style="font-weight: 600;">Atribuir Disciplinas e Professores</h5>
                <small class="text-muted"><?php echo e($turma->codigo); ?> - Turma <?php echo e($turma->nome); ?><?php if($anoLetivo): ?> | <?php echo e($anoLetivo->ano_inicial ?? $anoLetivo->ano); ?><?php endif; ?></small>
            </div>
            <a href="<?php echo e(route('admin.turmas.show', $turma)); ?>" class="btn btn-sm btn-secondary">
                <i class="bi bi-arrow-left"></i> Voltar
            </a>
        </div>

        <div class="row">
            <!-- Disciplinas Atribuídas -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header" style="background-color: #f8f9fa; padding: 8px;">
                        <small class="text-muted" style="font-weight: 600;">
                            <i class="bi bi-check-circle text-success"></i> Disciplinas Atribuídas (<?php echo e(count($disciplinasComProfessores)); ?>)
                        </small>
                    </div>
                    <div class="card-body" style="padding: 10px;">
                        <?php if(count($disciplinasComProfessores) > 0): ?>
                            <div class="table-responsive" style="max-height: 500px; overflow-y: auto;">
                                <table class="table table-sm table-bordered mb-0" style="font-size: 0.85rem;">
                                    <thead style="background-color: #f8f9fa; position: sticky; top: 0;">
                                        <tr>
                                            <th style="padding: 6px;">Disciplina</th>
                                            <th style="padding: 6px;">Professor</th>
                                            <th style="padding: 6px;">Carga</th>
                                            <th style="padding: 6px; width: 50px;">Acções</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $__currentLoopData = $disciplinasComProfessores; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <?php
                                                $disciplina = $item['disciplina'];
                                                $professor = $item['professor'];
                                                $cargaMin = $disciplina->pivot->carga_horaria_semanal ?? $disciplina->carga_horaria_semanal ?? null;
                                                $horas = $cargaMin !== null ? floor($cargaMin / 60) : null;
                                                $minutos = $cargaMin !== null ? ($cargaMin % 60) : null;
                                                $cargaLabel = $cargaMin === null ? '-' : ($horas > 0 ? "{$horas}h" : '') . ($minutos > 0 ? " {$minutos}min" : ($horas === 0 ? "{$minutos}min" : ''));
                                            ?>
                                            <tr>
                                                <td style="padding: 5px;">
                                                    <strong><?php echo e($disciplina->nome); ?></strong>
                                                </td>
                                                <td style="padding: 5px;">
                                                    <?php if($professor): ?>
                                                        <span class="badge bg-info"><?php echo e($professor->professor_nome); ?></span>
                                                    <?php else: ?>
                                                        <span class="text-muted" style="font-size: 0.75rem;">Sem professor</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td style="padding: 5px;">
                                                    <small class="text-muted"><?php echo e(trim($cargaLabel)); ?></small>
                                                </td>
                                                <td style="padding: 5px;">
                                                    <form action="<?php echo e(route('admin.turmas.remover-disciplina', ['turma' => $turma, 'disciplina' => $disciplina])); ?>" 
                                                          method="POST" 
                                                          class="d-inline"
                                                          onsubmit="return confirm('Tem certeza que deseja remover esta disciplina da turma?');">
                                                        <?php echo csrf_field(); ?>
                                                        <?php echo method_field('DELETE'); ?>
                                                        <button type="submit" class="btn btn-sm" style="padding: 2px 6px; font-size: 0.75rem; background: #f8d7da; color: #721c24; border: none;" title="Remover">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <p class="text-muted text-center mb-0" style="font-size: 0.85rem; padding: 20px;">
                                <i class="bi bi-inbox"></i> Nenhuma disciplina atribuída
                            </p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Disciplinas Disponíveis -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header" style="background-color: #f8f9fa; padding: 8px;">
                        <small class="text-muted" style="font-weight: 600;">
                            <i class="bi bi-plus-circle text-primary"></i> Disciplinas Disponíveis (<?php echo e($disciplinasDisponiveis->count()); ?>)
                        </small>
                    </div>
                    <div class="card-body" style="padding: 10px;">
                        <?php if($disciplinasDisponiveis->count() > 0): ?>
                            <form id="atribuir-multiplas-form" action="<?php echo e(route('admin.turmas.atribuir-disciplinas.store', $turma)); ?>" method="POST">
                                <?php echo csrf_field(); ?>
                                <input type="hidden" name="ano_letivo_id" value="<?php echo e($anoLetivo->id); ?>">
                                
                                <div class="mb-2 d-flex justify-content-between align-items-center">
                                    <div>
                                        <input type="checkbox" id="selectAllDisciplinas" style="width: 16px; height: 16px; cursor: pointer;">
                                        <label for="selectAllDisciplinas" class="ms-1" style="font-size: 0.85rem; cursor: pointer;">Selecionar todas</label>
                                    </div>
                                    <button type="submit" class="btn btn-sm btn-primary" id="btnAtribuirMultiplas" disabled>
                                        <i class="bi bi-plus-circle"></i> Atribuir Selecionadas
                                    </button>
                                </div>
                                
                                <div class="table-responsive" style="max-height: 450px; overflow-y: auto;">
                                    <table class="table table-sm table-bordered mb-0" style="font-size: 0.85rem;">
                                        <thead style="background-color: #f8f9fa; position: sticky; top: 0;">
                                            <tr>
                                                <th style="padding: 6px; width: 30px;">
                                                    <input type="checkbox" id="selectAllHeader" style="width: 16px; height: 16px;">
                                                </th>
                                                <th style="padding: 6px;">Disciplina</th>
                                                <th style="padding: 6px;">Carga</th>
                                                <th style="padding: 6px;">Professor</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php $__currentLoopData = $disciplinasDisponiveis; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $disciplina): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                <?php
                                                    $professoresDisciplina = $professoresPorDisciplina[$disciplina->id] ?? collect();
                                                ?>
                                                <tr class="disciplina-row" data-disciplina-id="<?php echo e($disciplina->id); ?>" data-tem-professor="<?php echo e($professoresDisciplina->count() > 0 ? '1' : '0'); ?>">
                                                    <td style="padding: 5px;">
                                                        <?php if($professoresDisciplina->count() > 0): ?>
                                                            <input type="checkbox" 
                                                                   name="disciplinas[<?php echo e($disciplina->id); ?>][selecionada]" 
                                                                   value="1"
                                                                   class="disciplina-checkbox"
                                                                   data-disciplina-id="<?php echo e($disciplina->id); ?>"
                                                                   style="width: 16px; height: 16px; cursor: pointer;">
                                                        <?php else: ?>
                                                            <span style="font-size: 0.7rem; color: #6c757d;">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td style="padding: 5px;">
                                                        <strong><?php echo e($disciplina->nome); ?></strong>
                                                    </td>
                                                    <td style="padding: 5px;">
                                                        <small class="text-muted"><?php echo e($disciplina->carga_horaria_formatada); ?></small>
                                                    </td>
                                                    <td style="padding: 5px;">
                                                        <?php if($professoresDisciplina->count() > 0): ?>
                                                            <select name="disciplinas[<?php echo e($disciplina->id); ?>][professor_id]" 
                                                                    class="form-select form-select-sm professor-select" 
                                                                    style="min-width: 150px;" 
                                                                    data-disciplina-id="<?php echo e($disciplina->id); ?>"
                                                                    disabled>
                                                                <option value="">Selecione...</option>
                                                                <?php $__currentLoopData = $professoresDisciplina; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $prof): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                                    <option value="<?php echo e($prof['id']); ?>"><?php echo e($prof['name']); ?></option>
                                                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                            </select>
                                                        <?php else: ?>
                                                            <small class="text-danger" style="font-size: 0.7rem;">
                                                                Sem professor disponível
                                                            </small>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                        </tbody>
                                    </table>
                                </div>
                            </form>
                        <?php else: ?>
                            <p class="text-muted text-center mb-0" style="font-size: 0.85rem; padding: 20px;">
                                <i class="bi bi-inbox"></i> Nenhuma disciplina disponível
                            </p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAllHeader = document.getElementById('selectAllHeader');
    const selectAllDisciplinas = document.getElementById('selectAllDisciplinas');
    const checkboxes = document.querySelectorAll('.disciplina-checkbox');
    const btnAtribuirMultiplas = document.getElementById('btnAtribuirMultiplas');
    const form = document.getElementById('atribuir-multiplas-form');
    
    // Selecionar todas (header)
    if (selectAllHeader) {
        selectAllHeader.addEventListener('change', function() {
            checkboxes.forEach(checkbox => {
                if (checkbox.closest('tr').dataset.temProfessor === '1') {
                    checkbox.checked = this.checked;
                    toggleProfessorSelect(checkbox);
                }
            });
            if (selectAllDisciplinas) {
                selectAllDisciplinas.checked = this.checked;
            }
            updateButtonState();
        });
    }
    
    // Selecionar todas (label)
    if (selectAllDisciplinas) {
        selectAllDisciplinas.addEventListener('change', function() {
            checkboxes.forEach(checkbox => {
                if (checkbox.closest('tr').dataset.temProfessor === '1') {
                    checkbox.checked = this.checked;
                    toggleProfessorSelect(checkbox);
                }
            });
            if (selectAllHeader) {
                selectAllHeader.checked = this.checked;
            }
            updateButtonState();
        });
    }
    
    // Checkboxes individuais
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            toggleProfessorSelect(this);
            updateSelectAllState();
            updateButtonState();
        });
    });
    
    function toggleProfessorSelect(checkbox) {
        const row = checkbox.closest('tr');
        const select = row.querySelector('.professor-select');
        if (select) {
            select.disabled = !checkbox.checked;
            if (!checkbox.checked) {
                select.value = '';
            }
        }
    }
    
    function updateSelectAllState() {
        const checkboxesComProfessor = Array.from(checkboxes).filter(cb => cb.closest('tr').dataset.temProfessor === '1');
        const allChecked = checkboxesComProfessor.length > 0 && checkboxesComProfessor.every(cb => cb.checked);
        const someChecked = checkboxesComProfessor.some(cb => cb.checked);
        
        if (selectAllHeader) {
            selectAllHeader.checked = allChecked && checkboxesComProfessor.length > 0;
            selectAllHeader.indeterminate = someChecked && !allChecked;
        }
        if (selectAllDisciplinas) {
            selectAllDisciplinas.checked = allChecked && checkboxesComProfessor.length > 0;
            selectAllDisciplinas.indeterminate = someChecked && !allChecked;
        }
    }
    
    function updateButtonState() {
        if (btnAtribuirMultiplas) {
            const hasSelected = Array.from(checkboxes).some(cb => cb.checked);
            btnAtribuirMultiplas.disabled = !hasSelected;
        }
    }
    
    // Validação ao submeter o formulário
    if (form) {
        form.addEventListener('submit', function(e) {
            const disciplinasSelecionadas = Array.from(checkboxes).filter(cb => cb.checked);
            
            if (disciplinasSelecionadas.length === 0) {
                e.preventDefault();
                alert('Por favor, selecione pelo menos uma disciplina.');
                return false;
            }
            
            // Validar se todas as disciplinas selecionadas têm professor
            let disciplinasSemProfessor = [];
            disciplinasSelecionadas.forEach(checkbox => {
                const row = checkbox.closest('tr');
                const select = row.querySelector('.professor-select');
                if (!select || !select.value) {
                    const disciplinaNome = row.querySelector('td:nth-child(2) strong').textContent;
                    disciplinasSemProfessor.push(disciplinaNome);
                }
            });
            
            if (disciplinasSemProfessor.length > 0) {
                e.preventDefault();
                alert('Por favor, selecione um professor para todas as disciplinas selecionadas:\n\n' + disciplinasSemProfessor.join('\n'));
                return false;
            }
        });
    }
    
    // Inicializar estado
    updateButtonState();
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\Users\Alcidio\Desktop\escola\resources\views/admin/turmas/atribuir-disciplinas.blade.php ENDPATH**/ ?>