<?php
/**
 * Clientes / Cadastro — shell instantâneo.
 * KPIs e tabela carregados via fetch() depois do DOM pronto.
 * TTFB = tempo de render PHP (<10ms), sem nenhuma query Firebird aqui.
 */
?>
<div class="pbi-page-header">
    <h1 class="pbi-page-title"><i class="bi bi-people-fill me-2 text-accent"></i>Clientes</h1>
</div>
<?php include __DIR__ . '/_submenu.php' ?>

<form method="get" action="/clientes/cadastro" class="pbi-filtro-barra mb-3 d-flex gap-2">
    <input type="text" name="busca" value="<?= \App\Core\View::e($_GET['busca'] ?? '') ?>" placeholder="Buscar cliente..." class="pbi-filtro-input form-control" style="max-width:320px;" id="input-busca">
    <button type="submit" class="pbi-btn-filtrar btn"><i class="bi bi-search me-1"></i>Buscar</button>
    <?php if (!empty($_GET['busca'])): ?><a href="/clientes/cadastro" class="btn btn-sm btn-outline-secondary">Limpar</a><?php endif; ?>
</form>

<!-- ── KPIs skeleton ─────────────────────────────────────────────────────── -->
<div class="pbi-kpi-grid mb-4" id="kpi-grid">
    <?php for ($i = 0; $i < 4; $i++): ?>
    <div class="pbi-kpi-card">
        <div class="pbi-kpi-label pbi-skeleton" style="width:60%;height:.8rem;border-radius:4px">&nbsp;</div>
        <div class="pbi-kpi-value pbi-skeleton mt-2" style="width:80%;height:1.6rem;border-radius:4px">&nbsp;</div>
    </div>
    <?php endfor; ?>
</div>
<div class="pbi-hint mb-3" style="margin-top:0"><strong>Compraram (30d)</strong> = clientes que fizeram pelo menos uma compra nos últimos 30 dias. <strong>Volume Total Hist.</strong> = soma de tudo que esses clientes já compraram desde o cadastro.</div>

<!-- ── Tabela de Cadastro (async) ────────────────────────────────────────── -->
<div class="pbi-card" id="card-cadastro">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-person-lines-fill me-2"></i>Cadastro de Clientes</span>
        <small class="text-muted" id="cadastro-badge">
            <span class="pbi-skeleton d-inline-block" style="width:80px;height:.75rem;border-radius:3px">&nbsp;</span>
        </small>
        <div class="pbi-hint" style="margin-top:.35rem">Lista de todos os seus clientes cadastrados, com data do cadastro, última compra e quanto já gastaram no total.</div>
    </div>
    <div id="cadastro-body">
        <div class="table-responsive">
            <table class="pbi-table">
                <thead><tr>
                    <th>#</th><th>Nome</th><th>CPF/CNPJ</th><th>Telefone</th>
                    <th>Bairro</th><th>Cadastro</th><th>Última Compra</th>
                    <th class="text-end">Valor Últ.</th><th class="text-end">Nº Compras</th><th>Ativo</th>
                </tr></thead>
                <tbody>
                <?php for ($i = 0; $i < 8; $i++): ?>
                <tr>
                    <?php for ($j = 0; $j < 10; $j++): ?>
                    <td><span class="pbi-skeleton d-inline-block" style="width:<?= [30,120,80,80,80,65,65,70,50,45][$j] ?>px;height:.75rem;border-radius:3px">&nbsp;</span></td>
                    <?php endfor; ?>
                </tr>
                <?php endfor; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ── Config injetada pelo PHP para o JS usar ──────────────────────────── -->
<script>
window.__CLIENTES_CADASTRO = {
    busca: <?= json_encode($_GET['busca'] ?? '') ?>
};
</script>

<style>
@keyframes pbi-pulse { 0%,100%{opacity:1} 50%{opacity:.4} }
.pbi-skeleton { background:var(--pbi-border,#e2e8f0); animation:pbi-pulse 1.4s ease-in-out infinite; pointer-events:none; color:transparent !important; }
</style>

<script>
(function () {
'use strict';

var busca = window.__CLIENTES_CADASTRO.busca;
var qs = busca ? '?busca=' + encodeURIComponent(busca) : '';

function fmtR(v) { return 'R$ ' + parseFloat(v||0).toLocaleString('pt-BR',{minimumFractionDigits:2,maximumFractionDigits:2}); }
function fmtN(v,d) { return parseFloat(v||0).toLocaleString('pt-BR',{minimumFractionDigits:d===undefined?0:d,maximumFractionDigits:d===undefined?0:d}); }
function fmtData(s) { if(!s)return'—'; return s.substring(8,10)+'/'+s.substring(5,7)+'/'+s.substring(0,4); }
function esc(s) { var d=document.createElement('div'); d.textContent=s||''; return d.innerHTML; }
function apiFetch(url) {
    return fetch(url,{credentials:'same-origin'}).then(function(r){
        if(!r.ok) return r.json().then(function(e){throw new Error(e.erro||'HTTP '+r.status);});
        return r.json();
    });
}

function renderKpis(kpis) {
    var defs = [
        {label:'Total Clientes',    val:fmtN(kpis.TOTAL_CLIENTES||0,0), cls:''},
        {label:'Ativos',            val:fmtN(kpis.ATIVOS||0,0),          cls:'text-success'},
        {label:'Compraram (30d)',   val:fmtN(kpis.COMPRARAM_30D||0,0),   cls:'text-accent'},
        {label:'Volume Total Hist.',val:fmtR(kpis.VOLUME_TOTAL||0),      cls:''},
    ];
    document.getElementById('kpi-grid').innerHTML = defs.map(function(d){
        return '<div class="pbi-kpi-card"><div class="pbi-kpi-label">'+d.label+'</div>'
             + '<div class="pbi-kpi-value '+d.cls+'">'+d.val+'</div></div>';
    }).join('');
}

function renderCadastro(linhas) {
    document.getElementById('cadastro-badge').textContent = linhas.length + ' registros';
    if (!linhas.length) {
        document.getElementById('cadastro-body').innerHTML =
            '<p class="text-center text-muted py-4">Nenhum cliente encontrado.</p>';
        return;
    }
    var rows = linhas.map(function(r, i) {
        var doc = (r.CPF||r.CNPJ||'').trim();
        var tel = (r.CEL_PRINC||r.FONE_PRINC||'').trim();
        var ativo = (r.ATIVO||'').trim()==='S'
            ? '<span class="pbi-badge pbi-badge-success">Ativo</span>'
            : '<span class="pbi-badge">Inativo</span>';
        return '<tr>'
            + '<td class="text-muted">'+(i+1)+'</td>'
            + '<td>'+esc(r.NOME||'')+'</td>'
            + '<td class="text-muted small">'+esc(doc)+'</td>'
            + '<td class="text-muted small">'+esc(tel)+'</td>'
            + '<td>'+esc((r.BAIRRO_PRINC||'').substring(0,20))+'</td>'
            + '<td>'+fmtData(r.DATA_CADASTRO)+'</td>'
            + '<td>'+fmtData(r.DATA_ULT_COMPRA)+'</td>'
            + '<td class="text-end">'+fmtR(r.VLR_ULT_COMPRA||0)+'</td>'
            + '<td class="text-end">'+parseInt(r.NUMERO_COMPRAS||0)+'</td>'
            + '<td>'+ativo+'</td>'
            + '</tr>';
    }).join('');
    document.getElementById('cadastro-body').innerHTML =
        '<div class="table-responsive"><table class="pbi-table">'
        + '<thead><tr><th>#</th><th>Nome</th><th>CPF/CNPJ</th><th>Telefone</th>'
        + '<th>Bairro</th><th>Cadastro</th><th>Última Compra</th>'
        + '<th class="text-end">Valor Últ.</th><th class="text-end">Nº Compras</th><th>Ativo</th>'
        + '</tr></thead><tbody>'+rows+'</tbody></table></div>';
}

window.addEventListener('DOMContentLoaded', function () {
    apiFetch('/api/clientes/kpis')
        .then(function(d){ renderKpis(d.kpis||{}); })
        .catch(function(e){
            var el=document.getElementById('kpi-grid');
            if(el) el.innerHTML='<div class="alert alert-warning small py-2">Erro KPIs: '+esc(e.message)+'</div>';
        });

    apiFetch('/api/clientes/cadastro'+qs)
        .then(function(d){ renderCadastro(d.linhas||[]); })
        .catch(function(e){
            var el=document.getElementById('cadastro-body');
            if(el) el.innerHTML='<div class="px-3 py-3 alert alert-warning small">Erro ao carregar: '+esc(e.message)+'</div>';
        });
});

})();
</script>
