@extends('layouts.app')
@section('title','LOGs Recebidos — Diretório')
@section('content')
 
<div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.5rem;margin-bottom:1rem">
    <div>
        <h2 style="margin:0">📂 LOGs Recebidos — Diretório</h2>
        <p style="margin:.25rem 0 0;color:var(--muted);font-size:.85rem">
            Lê os arquivos <code>.log</code> do diretório físico sem importar para o banco.
        </p>
    </div>
    <div class="stat-card" style="max-width:220px">
        <div class="stat-number">{{ number_format($total) }}</div>
        <div class="stat-label">Arquivos no diretório</div>
    </div>
</div>
 
@if($total === 0)
    <div class="alert alert-warning">
        ⚠️ Nenhum arquivo <code>.log</code> encontrado no diretório de uploads.
    </div>
@else
 
{{-- Barra de progresso --}}
<div id="bloco-progresso" style="background:#fff;border-radius:8px;padding:1.25rem 1.5rem;
     box-shadow:0 2px 12px rgba(0,0,0,.08);max-width:700px;margin-bottom:1.5rem">
 
    <div id="prog-arquivo" style="font-size:.82rem;color:var(--muted);margin-bottom:.5rem;
         background:#f8f9fa;border-radius:4px;padding:.3rem .7rem;font-family:monospace;
         min-height:1.4em">Aguardando leitura...</div>
 
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:.3rem">
        <span id="prog-label" style="font-weight:600;font-size:.9rem">Clique em "Ler LOGs" para iniciar</span>
        <span id="prog-pct" style="font-weight:700;color:var(--blue);font-size:1rem">0%</span>
    </div>
    <div style="background:#e9ecef;border-radius:50px;height:22px;overflow:hidden;margin-bottom:.4rem">
        <div id="prog-bar" style="height:100%;width:0%;background:linear-gradient(90deg,#1B4F8C,#2E86DE);
             border-radius:50px;transition:width .4s ease;position:relative">
            <div id="prog-shimmer" style="position:absolute;inset:0;background:linear-gradient(90deg,
                 transparent,rgba(255,255,255,.25),transparent);animation:shimmer 1.2s infinite;
                 display:none"></div>
        </div>
    </div>
    <div id="prog-sub" style="font-size:.8rem;color:var(--muted)">&nbsp;</div>
 
    <button id="btn-ler" onclick="lerLogs()"
            class="btn btn-primary" style="margin-top:.75rem">
        📂 Ler LOGs ({{ $total }} arquivo{{ $total > 1 ? 's' : '' }})
    </button>
</div>
 
{{-- Filtro (aparece após carregar) --}}
<div id="bloco-filtro" style="display:none;margin-bottom:1rem">
    <input type="text" id="filtro-call" placeholder="Filtrar por callsign, banda ou modo..."
           oninput="filtrar(this.value)"
           style="padding:.45rem .8rem;border:1px solid #ddd;border-radius:var(--radius);
                  font-size:.9rem;min-width:280px">
    <span id="filtro-count" style="font-size:.82rem;color:var(--muted);margin-left:.5rem"></span>
</div>
 
{{-- Tabela de resultados --}}
<div id="bloco-tabela" style="display:none">
    <table class="table" id="tbl-logs">
        <thead>
            <tr>
                <th onclick="sortTable('callsign')"  style="cursor:pointer;white-space:nowrap">Callsign <span id="ic-callsign">⇅</span></th>
                <th onclick="sortTable('categoria')" style="cursor:pointer;white-space:nowrap">Categoria <span id="ic-categoria">⇅</span></th>
                <th onclick="sortTable('banda')"     style="cursor:pointer;white-space:nowrap">Banda <span id="ic-banda">⇅</span></th>
                <th onclick="sortTable('modo')"      style="cursor:pointer;white-space:nowrap">Modo <span id="ic-modo">⇅</span></th>
                <th onclick="sortTable('potencia')"  style="cursor:pointer;white-space:nowrap">Potência <span id="ic-potencia">⇅</span></th>
                <th onclick="sortTable('claimed')"   style="cursor:pointer;white-space:nowrap">Claimed <span id="ic-claimed">⇅</span></th>
                <th onclick="sortTable('qsos')"      style="cursor:pointer;white-space:nowrap;color:#FFD700">QSOs <span id="ic-qsos">⇅</span></th>
                <th>Arquivo</th>
                <th style="text-align:center;width:60px">Ações</th>
            </tr>
        </thead>
        <tbody id="tbl-body"></tbody>
        <tfoot>
            <tr style="background:#f0f0f0;font-weight:bold">
                <td colspan="5">TOTAL</td>
                <td id="tot-claimed">—</td>
                <td id="tot-qsos" style="color:var(--green)">—</td>
                <td></td>
                <td></td>
            </tr>
        </tfoot>
    </table>
</div>
 
@endif
 
<style>
@keyframes shimmer { from{transform:translateX(-100%)} to{transform:translateX(100%)} }
</style>
 
<script>
let todosLogs  = [];
const verLogUrl = '{{ route("logs.ver", ["arquivo" => "__ARQUIVO__"]) }}';
let sortCol    = 'callsign';
let sortDir    = 'asc';
 
function lerLogs() {
    const btn   = document.getElementById('btn-ler');
    const bar   = document.getElementById('prog-bar');
    const shimm = document.getElementById('prog-shimmer');
    const label = document.getElementById('prog-label');
    const pct   = document.getElementById('prog-pct');
    const sub   = document.getElementById('prog-sub');
    const arq   = document.getElementById('prog-arquivo');
 
    btn.disabled = true;
    btn.textContent = '⏳ Lendo...';
    shimm.style.display = 'block';
 
    // Animação de progresso simulada durante o fetch
    let prog = 0;
    const timer = setInterval(function() {
        prog = Math.min(prog + Math.random() * 3, 92);
        bar.style.width = prog + '%';
        pct.textContent = Math.round(prog) + '%';
        label.textContent = 'Lendo e contando QSOs de {{ $total }} arquivos...';
        sub.textContent   = 'Aguarde...';
    }, 200);
 
    fetch('{{ route("logs.recebidos.processar") }}', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Content-Type': 'application/json',
            'Accept':       'application/json',
        },
    })
    .then(function(r) {
        // Verifica HTTP status antes de tentar parsear JSON
        if (!r.ok) {
            return r.text().then(function(txt) {
                throw new Error('HTTP ' + r.status + ': ' + txt.substring(0, 200));
            });
        }
        return r.json();
    })
    .then(function(d) {
        clearInterval(timer);
        bar.style.width = '100%';
        pct.textContent = '100%';
        shimm.style.display = 'none';
 
        if (d.ok) {
            bar.style.background = 'linear-gradient(90deg,#2E7D32,#43A047)';
            label.textContent = '✅ ' + d.total + ' LOGs lidos | ' + d.total_qsos_geral.toLocaleString('pt-BR') + ' QSOs no total';
            sub.textContent   = '';
            arq.textContent   = '✅ Leitura concluída.';
            btn.style.display = 'none';
            todosLogs = d.logs;
            renderTabela(todosLogs);
            document.getElementById('bloco-filtro').style.display = 'block';
            document.getElementById('bloco-tabela').style.display = 'block';
        } else {
            bar.style.background = '#C62828';
            label.textContent = '❌ Erro: ' + (d.erro || 'Falha desconhecida');
            btn.disabled = false;
            btn.textContent = '📂 Tentar novamente';
        }
    })
    .catch(function(e) {
        clearInterval(timer);
        bar.style.background = '#C62828';
        bar.style.width = '100%';
        pct.textContent = '100%';
        shimm.style.display = 'none';
        label.textContent = '❌ Erro ao ler os LOGs: ' + e.message;
        arq.textContent   = 'Verifique o console para detalhes.';
        btn.disabled = false;
        btn.textContent = '📂 Tentar novamente';
        console.error('Erro fetch LOGs:', e);
    });
}
 
function renderTabela(dados) {
    const tbody = document.getElementById('tbl-body');
    tbody.innerHTML = '';
    let totClaimed = 0, totQsos = 0;
 
    dados.forEach(function(l) {
        const tr = document.createElement('tr');
        tr.dataset.search = (l.callsign + ' ' + l.banda + ' ' + l.modo).toLowerCase();
        tr.innerHTML =
            '<td><strong>' + l.callsign + '</strong></td>' +
            '<td style="font-size:.82rem">' + (l.categoria||'—') + '</td>' +
            '<td>' + (l.banda||'—') + '</td>' +
            '<td>' + (l.modo||'—') + '</td>' +
            '<td>' + (l.potencia||'—') + '</td>' +
            '<td>' + (l.claimed||0).toLocaleString('pt-BR') + '</td>' +
            '<td style="font-weight:bold;color:var(--blue)">' + (l.qsos||0).toLocaleString('pt-BR') + '</td>' +
            '<td style="font-size:.75rem;color:#aaa">' + l.arquivo + '</td>' +
            '<td style="text-align:center">' +
                '<a href="' + verLogUrl.replace('__ARQUIVO__', encodeURIComponent(l.arquivo)) + '" ' +
                   'title="Visualizar conteúdo" style="text-decoration:none;font-size:1.1rem">📄</a>' +
            '</td>';
        tbody.appendChild(tr);
        totClaimed += (l.claimed || 0);
        totQsos    += (l.qsos    || 0);
    });
 
    document.getElementById('tot-claimed').textContent = totClaimed.toLocaleString('pt-BR');
    document.getElementById('tot-qsos').textContent    = totQsos.toLocaleString('pt-BR');
    document.getElementById('filtro-count').textContent = dados.length + ' registro(s)';
}
 
function filtrar(termo) {
    const lower = termo.toLowerCase();
    const filtrado = lower
        ? todosLogs.filter(l => (l.callsign+' '+l.banda+' '+l.modo).toLowerCase().includes(lower))
        : todosLogs;
    renderTabela(filtrado);
}
 
function sortTable(col) {
    if (sortCol === col) {
        sortDir = sortDir === 'asc' ? 'desc' : 'asc';
    } else {
        sortCol = col; sortDir = 'asc';
    }
 
    // Atualizar ícones
    ['callsign','categoria','banda','modo','potencia','claimed','qsos'].forEach(function(c) {
        const el = document.getElementById('ic-' + c);
        if (el) el.textContent = c === sortCol ? (sortDir === 'asc' ? '▲' : '▼') : '⇅';
    });
 
    const sorted = [...todosLogs].sort(function(a, b) {
        const va = a[col] ?? '';
        const vb = b[col] ?? '';
        if (typeof va === 'number') return sortDir === 'asc' ? va - vb : vb - va;
        return sortDir === 'asc'
            ? String(va).localeCompare(String(vb))
            : String(vb).localeCompare(String(va));
    });
 
    // Reaplicar filtro atual
    const termo = document.getElementById('filtro-call').value.toLowerCase();
    const filtrado = termo
        ? sorted.filter(l => (l.callsign+' '+l.banda+' '+l.modo).toLowerCase().includes(termo))
        : sorted;
 
    todosLogs = sorted; // mantém base completa ordenada
    renderTabela(filtrado);
}
</script>
@endsection