@extends('layouts.app')
@section('title','Gerar Excel Vencedores')
@section('content')
@include('components.seletor-contest')

 
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.5rem;margin-bottom:1rem">
    <div>
        <h2 style="margin:0">🏆 Gerar Excel Vencedores</h2>
        <p style="margin:.25rem 0 0;color:var(--muted);font-size:.82rem">
            Apenas os <strong>primeiros colocados</strong> por categoria.
            Clique nos cabeçalhos para ordenar.
        </p>
    </div>
    <div class="stats-grid" style="max-width:500px;margin:0">
        <div class="stat-card stat-card-green">
            <div class="stat-number">{{ number_format(count($vencedores)) }}</div>
            <div class="stat-label">Vencedores</div>
        </div>
        <div class="stat-card {{ $qrzAtivo ? 'stat-card-green' : '' }}">
            <div class="stat-number">{{ $qrzAtivo ? $qrzConsultas : '—' }}</div>
            <div class="stat-label">E-mails via QRZ</div>
        </div>
        <div class="stat-card stat-card-red">
            <div class="stat-number">
                {{ $vencedores->filter(fn($v) => empty(trim($v->email ?? '')))->count() }}
            </div>
            <div class="stat-label">Sem E-mail</div>
        </div>
    </div>
</div>
 
@if(!$qrzAtivo)
<div class="alert alert-warning" style="max-width:650px;margin-bottom:1rem">
    ⚠️ <strong>QRZ não configurado.</strong>
    Adicione <code>QRZ_USERNAME</code> e <code>QRZ_PASSWORD</code> no <code>.env</code>
    para buscar e-mails automaticamente.
</div>
@elseif($qrzConsultas > 0)
<div class="alert alert-success" style="max-width:650px;margin-bottom:1rem">
    ✅ <strong>{{ $qrzConsultas }}</strong> e-mail(s) obtido(s) via QRZ.com.
</div>
@endif
 
{{-- Botão download --}}
<form method="POST" action="{{ route('relatorios.emails') }}" style="margin-bottom:1.5rem">
    @csrf
    <button type="submit" class="btn btn-primary">
        ⬇ Baixar CSV (Vencedores)
    </button>
    <span style="font-size:.82rem;color:var(--muted);margin-left:.75rem">
        CSV separado por ponto-e-vírgula, UTF-8 com BOM (compatível com Excel)
    </span>
</form>
 
{{-- Tabela --}}
<div style="overflow-x:auto">
<table class="table" id="tbl-vencedores" style="font-size:.85rem">
    <thead>
        <tr>
            @php
                $cols = [
                    ['callsign',    'Callsign',    'text',   'left'],
                    ['nome',        'Nome',        'text',   'left'],
                    ['email',       'E-mail',      'text',   'left'],
                    ['email_fonte', 'Fonte',       'text',   'center'],
                    ['categoria',   'Categoria',   'text',   'left'],
                    ['rk',          'Rank',        'num',    'center'],
                    ['final_score', 'Final Score', 'num',    'right'],
                ];
            @endphp
            @foreach($cols as [$key, $label, $tipo, $align])
            <th style="cursor:pointer;white-space:nowrap;user-select:none;text-align:{{ $align }}"
                onclick="sortTable('{{ $key }}','{{ $tipo }}')"
                id="th-{{ $key }}">
                {{ $label }} <span id="ic-{{ $key }}" style="opacity:.7;font-size:.8em">⇅</span>
            </th>
            @endforeach
        </tr>
    </thead>
    <tbody id="tbl-body">
        @forelse($vencedores as $v)
        <tr
            data-callsign="{{ $v->callsign }}"
            data-nome="{{ $v->nome ?? '' }}"
            data-email="{{ $v->email ?? '' }}"
            data-email_fonte="{{ $v->email_fonte ?? 'banco' }}"
            data-categoria="{{ $v->categoria }}"
            data-rk="{{ $v->rk }}"
            data-final_score="{{ $v->final_score }}">
            <td><strong>{{ $v->callsign }}</strong></td>
            <td>{{ $v->nome ?? '—' }}</td>
            <td style="font-size:.8rem">
                @if(!empty(trim($v->email ?? '')))
                    <a href="mailto:{{ $v->email }}" style="color:var(--blue)">{{ $v->email }}</a>
                @else
                    <span style="color:#aaa">—</span>
                @endif
            </td>
            <td style="text-align:center;font-size:.78rem">
                @if(($v->email_fonte ?? '') === 'qrz')
                    <span style="color:var(--green);font-weight:bold" title="Obtido via QRZ.com">QRZ</span>
                @elseif(($v->email_fonte ?? '') === 'nao_encontrado')
                    <span style="color:#C62828" title="Não encontrado no QRZ">❌</span>
                @else
                    <span style="color:#888" title="E-mail do LOG">LOG</span>
                @endif
            </td>
            <td style="font-size:.78rem">{{ $v->categoria }}</td>
            <td style="text-align:center;font-weight:bold;color:var(--blue)">{{ $v->rk }}</td>
            <td style="text-align:right;font-weight:bold">{{ number_format($v->final_score) }}</td>
        </tr>
        @empty
        <tr>
            <td colspan="7" style="text-align:center;color:#aaa;padding:1.5rem">
                Nenhum vencedor encontrado. Execute a Etapa 9 primeiro.
            </td>
        </tr>
        @endforelse
    </tbody>
</table>
</div>
 
<script>
let sortCol = null, sortDir = 'asc';
 
function sortTable(col, tipo) {
    if (sortCol === col) {
        sortDir = sortDir === 'asc' ? 'desc' : 'asc';
    } else {
        sortCol = col;
        sortDir = 'asc';
    }
 
    // Atualizar ícones
    document.querySelectorAll('[id^="ic-"]').forEach(function(el) {
        el.textContent = '⇅';
    });
    const ic = document.getElementById('ic-' + col);
    if (ic) ic.textContent = sortDir === 'asc' ? ' ▲' : ' ▼';
 
    const tbody = document.getElementById('tbl-body');
    const rows  = Array.from(tbody.querySelectorAll('tr[data-' + col + ']'));
 
    rows.sort(function(a, b) {
        const va = a.dataset[col] || '';
        const vb = b.dataset[col] || '';
 
        let cmp;
        if (tipo === 'num') {
            cmp = (parseFloat(va) || 0) - (parseFloat(vb) || 0);
        } else {
            cmp = va.localeCompare(vb, 'pt-BR', {sensitivity: 'base'});
        }
        return sortDir === 'asc' ? cmp : -cmp;
    });
 
    rows.forEach(function(r) { tbody.appendChild(r); });
}
</script>
 
@endsection