@extends('layouts.app')

@section('title', 'Alunos - 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;">{{ __('common.students') }}</h5>
            <div class="btn-group btn-group-sm">
                <a href="{{ route('admin.alunos.create') }}" class="btn btn-primary">{{ __('common.new_student') }}</a>
                <a href="{{ route('admin.inscricoes.index') }}" class="btn btn-outline-success">{{ __('common.enrollments') }}</a>
                <a href="{{ route('admin.cartoes-estudantes.index') }}" class="btn btn-outline-primary">Cartões de Estudantes</a>
            </div>
        </div>

        <form method="GET" action="{{ route('admin.alunos.index') }}" class="mb-2" style="display: flex; gap: 8px; align-items: end;">
            <select class="form-select form-select-sm" id="ano_letivo_id" name="ano_letivo_id" style="width: 150px;">
                <option value="">{{ __('common.all_years') }}</option>
                @foreach($anosLetivos ?? [] as $ano)
                    <option value="{{ $ano->id }}" {{ ($anoLetivoId ?? null) == $ano->id ? 'selected' : '' }}>
                        @php
                            if (strpos($ano->ano, '/') !== false) {
                                $partes = explode('/', $ano->ano);
                                $anoInicial = $partes[0];
                                $anoFinal = $partes[1];
                                $anoExibido = $anoInicial; // Mostrar ano inicial
                            } else {
                                $anoExibido = $ano->ano;
                            }
                        @endphp
                        {{ $anoExibido }}
                        @if($ano->ativo) ({{ __('common.active') }}) @endif
                    </option>
                @endforeach
            </select>
            <input type="text" class="form-control form-control-sm" id="search" name="search" 
                   value="{{ request('search') }}" placeholder="{{ __('common.search') }}..." style="flex: 1;">
            <select class="form-select form-select-sm" id="classe" name="classe" style="width: 150px;">
                <option value="">{{ __('common.all_classes') }}</option>
                @foreach($classes ?? [] as $classe)
                    <option value="{{ $classe }}" {{ request('classe') == $classe ? 'selected' : '' }}>{{ $classe }}</option>
                @endforeach
            </select>
            <select class="form-select form-select-sm" id="turma" name="turma" style="width: 150px;">
                <option value="">{{ __('common.all_turmas') }}</option>
                @foreach($turmas ?? [] as $turma)
                    <option value="{{ $turma }}" {{ request('turma') == $turma ? 'selected' : '' }}>{{ $turma }}</option>
                @endforeach
            </select>
            <button type="submit" class="btn btn-sm btn-primary">{{ __('common.filter') }}</button>
            @if(request('search') || request('classe') || request('turma') || request('ano_letivo_id'))
                <a href="{{ route('admin.alunos.index') }}" class="btn btn-sm btn-secondary">{{ __('common.clear') }}</a>
            @endif
        </form>

        <div class="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;">{{ __('common.code') }}</th>
                        <th style="padding: 6px;">{{ __('common.name') }}</th>
                        <th style="padding: 6px;">{{ __('common.class_turma') }}</th>
                        <th style="padding: 6px;">{{ __('common.phone') }}</th>
                        <th style="padding: 6px;">{{ __('common.status') }}</th>
                        <th style="padding: 6px;">{{ __('common.actions') }}</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($alunos as $aluno)
                        <tr>
                            <td style="padding: 5px;">{{ $aluno->codigo_estudante }}</td>
                            <td style="padding: 5px;">{{ $aluno->user->name }}</td>
                            <td style="padding: 5px;">
                                @if($aluno->turmas->count() > 0)
                                    @foreach($aluno->turmas as $turma)
                                        <span style="font-size: 0.75rem; padding: 2px 6px; background: #e7f3ff; color: #0066cc; border-radius: 3px;">{{ $turma->codigo }} - {{ $turma->nome }}</span>
                                    @endforeach
                                @else
                                    <span style="color: #999;">{{ __('common.no_class') }}</span>
                                @endif
                            </td>
                            <td style="padding: 5px;">{{ $aluno->telefone ?? '-' }}</td>
                            <td style="padding: 5px;">
                                @if($aluno->user && $aluno->user->is_active)
                                    <span style="font-size: 0.75rem; padding: 2px 6px; background: #d4edda; color: #155724; border-radius: 3px;">{{ __('common.active') }}</span>
                                @else
                                    <span style="font-size: 0.75rem; padding: 2px 6px; background: #f8d7da; color: #721c24; border-radius: 3px;">{{ __('common.blocked') }}</span>
                                @endif
                            </td>
                            <td style="padding: 5px;">
                                <div style="display: flex; gap: 4px;">
                                    <a href="{{ route('admin.alunos.show', $aluno) }}" class="btn btn-sm" style="padding: 2px 6px; font-size: 0.75rem; background: #e7f3ff; color: #0066cc; border: none;" title="{{ __('common.view') }}">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                    <a href="{{ route('admin.alunos.edit', $aluno) }}" class="btn btn-sm" style="padding: 2px 6px; font-size: 0.75rem; background: #fff3cd; color: #856404; border: none;" title="{{ __('common.edit') }}">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <a href="{{ route('admin.alunos.alocar', $aluno) }}" class="btn btn-sm" style="padding: 2px 6px; font-size: 0.75rem; background: #d1ecf1; color: #0c5460; border: none;" title="Alocar a Turma">
                                        <i class="bi bi-person-plus"></i>
                                    </a>
                                    <form action="{{ route('admin.alunos.toggle-status', $aluno) }}" method="POST" class="d-inline">
                                        @csrf
                                        @method('PATCH')
                                        <button type="submit" class="btn btn-sm" style="padding: 2px 6px; font-size: 0.75rem; background: {{ $aluno->user && $aluno->user->is_active ? '#fff3cd' : '#d4edda' }}; color: {{ $aluno->user && $aluno->user->is_active ? '#856404' : '#155724' }}; border: none;" title="{{ $aluno->user && $aluno->user->is_active ? __('common.block') : __('common.unblock') }}">
                                            <i class="bi bi-{{ $aluno->user && $aluno->user->is_active ? 'lock' : 'unlock' }}"></i>
                                        </button>
                                    </form>
                                    <form action="{{ route('admin.alunos.destroy', $aluno) }}" method="POST" class="d-inline delete-form"
                                          data-id="{{ $aluno->id }}"
                                          data-confirm="Tem certeza que deseja eliminar este aluno? Esta acção não pode ser desfeita.">
                                        @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">Nenhum aluno encontrado</td>
                        </tr>
                    @endforelse
                </tbody>
                </table>
            </div>

            @if(method_exists($alunos, 'links'))
                <div class="mt-3">
                    {{ $alunos->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">Nenhum aluno encontrado</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 aluno. Por favor, tente novamente.'));
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalHTML;
            });
        });
    });
});
</script>
@endsection



