@extends('layouts.app')

@section('title', 'Disciplinas - SGE')

@section('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;">
            <h5 class="mb-0" style="font-weight: 600;">Disciplinas</h5>
            <a href="{{ route('admin.disciplinas.create') }}" class="btn btn-sm btn-primary">Nova Disciplina</a>
        </div>

        <form method="GET" action="{{ route('admin.disciplinas.index') }}" class="mb-2" style="display: flex; gap: 8px; align-items: end;">
            <input type="text" class="form-control form-control-sm" name="search" 
                   placeholder="Pesquisar..." value="{{ request('search') }}" style="flex: 1;">
            <select class="form-select form-select-sm" name="nivel_ensino" id="nivel_ensino" style="width: 150px;">
                <option value="">Todos os Níveis</option>
                <option value="PRIMARIO" {{ request('nivel_ensino') == 'PRIMARIO' ? 'selected' : '' }}>Primário</option>
                <option value="SECUNDARIO" {{ request('nivel_ensino') == 'SECUNDARIO' ? 'selected' : '' }}>Secundário</option>
            </select>
            <button type="submit" class="btn btn-sm btn-primary">Filtrar</button>
            @if(request('search') || request('nivel_ensino'))
                <a href="{{ route('admin.disciplinas.index') }}" class="btn btn-sm btn-secondary">Limpar</a>
            @endif
        </form>

        <div class="mb-3 js-ajax-pagination">
            <div class="table-responsive">
                <table class="table table-sm table-bordered" style="font-size: 0.85rem; margin-bottom: 0;">
                    <thead style="background-color: #f8f9fa;">
                        <tr>
                            <th style="padding: 6px;">Código</th>
                            <th style="padding: 6px;">Nome</th>
                            <th style="padding: 6px;">Carga Horária</th>
                            <th style="padding: 6px;">Nível</th>
                            <th style="padding: 6px;">Status</th>
                            <th style="padding: 6px;">Acções</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($disciplinas as $disciplina)
                            <tr>
                                <td style="padding: 5px;">{{ $disciplina->codigo }}</td>
                                <td style="padding: 5px;">{{ $disciplina->nome }}</td>
                                <td style="padding: 5px;">
                                    <span style="font-size: 0.75rem; color: #666;">{{ $disciplina->carga_horaria_formatada }}</span>
                                </td>
                                <td style="padding: 5px;">
                                    {{ ($disciplina->nivel_ensino ?? 'PRIMARIO') === 'SECUNDARIO' ? 'Secundário' : 'Primário' }}
                                </td>
                                <td style="padding: 5px;">
                                    @if($disciplina->ativa)
                                        <span style="font-size: 0.75rem; padding: 2px 6px; background: #d4edda; color: #155724; border-radius: 3px;">Activa</span>
                                    @else
                                        <span style="font-size: 0.75rem; padding: 2px 6px; background: #e2e3e5; color: #383d41; border-radius: 3px;">Inactiva</span>
                                    @endif
                                </td>
                                <td style="padding: 5px;">
                                    <div style="display: flex; gap: 4px;">
                                        <a href="{{ route('admin.disciplinas.edit', $disciplina) }}" class="btn btn-sm" style="padding: 2px 6px; font-size: 0.75rem; background: #fff3cd; color: #856404; border: none;" title="Editar">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <form action="{{ route('admin.disciplinas.destroy', $disciplina) }}" method="POST" class="d-inline delete-form"
                                              data-id="{{ $disciplina->id }}"
                                              data-confirm="Tem certeza que deseja eliminar esta disciplina?">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-sm" style="padding: 2px 6px; font-size: 0.75rem; background: #f8d7da; color: #721c24; border: none;" title="Eliminar">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="text-center text-muted">
                                    <i class="bi bi-inbox"></i> Nenhuma disciplina encontrada
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            
            @if(method_exists($disciplinas, 'links'))
                <div class="mt-3">
                    {{ $disciplinas->appends(request()->query())->links() }}
                </div>
            @endif
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Interceptar formulários de delete
    document.querySelectorAll('.delete-form').forEach(function(form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const confirmMsg = this.getAttribute('data-confirm');
            if (!confirm(confirmMsg)) {
                return false;
            }
            
            const formData = new FormData(this);
            const row = this.closest('tr');
            const url = this.action;
            
            // Mostrar loading
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalHTML = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i>';
            
            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': formData.get('_token'),
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.message || 'Erro ao processar requisição');
                    });
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Remover linha da tabela com animação
                    row.style.transition = 'opacity 0.3s';
                    row.style.opacity = '0';
                    setTimeout(function() {
                        row.remove();
                        // Verificar se a tabela ficou vazia
                        const tbody = document.querySelector('tbody');
                        if (tbody && tbody.children.length === 0) {
                            tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted"><i class="bi bi-inbox"></i> Nenhuma disciplina encontrada</td></tr>';
                        }
                    }, 300);
                } else {
                    alert('Erro: ' + (data.message || 'Erro desconhecido'));
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalHTML;
                }
            })
            .catch(error => {
                console.error('Erro:', error);
                alert('Erro: ' + (error.message || 'Erro ao eliminar disciplina. Por favor, tente novamente.'));
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalHTML;
            });
        });
    });
});
</script>
@endsection
