<?php /* Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva */ ?>
<?php
$fmt     = fn($v,$d=2) => 'R$ '.number_format((float)$v,$d,',','.');
$fmtData = fn($d) => $d ? substr($d,8,2).'/'.substr($d,5,2).'/'.substr($d,0,4) : '—';
$totalVal = array_sum(array_column($linhas,'VALOR_TOTAL'));
$mediaTicket = count($linhas)>0 ? array_sum(array_column($linhas,'TICKET_MEDIO'))/count($linhas) : 0;
?>
<div class="pbi-page-header no-print">
    <h1 class="pbi-page-title"><i class="bi bi-people me-2 text-accent"></i>Ranking de Clientes</h1>
</div>
<form method="get" class="pbi-filtro-barra mb-3 no-print">
    <div class="pbi-filtro-row">
        <div class="pbi-filtro-field"><label class="pbi-filtro-label">De</label>
            <input type="date" name="data_ini" value="<?= $filtros['dataIni'] ?>" class="pbi-filtro-input form-control"></div>
        <div class="pbi-filtro-field"><label class="pbi-filtro-label">Até</label>
            <input type="date" name="data_fim" value="<?= $filtros['dataFim'] ?>" class="pbi-filtro-input form-control"></div>
        <button type="submit" class="pbi-btn-filtrar btn"><i class="bi bi-funnel me-1"></i>Filtrar</button>
    </div>
</form>

<?php include __DIR__ . '/_header.php' ?>

<script type="application/json" id="relatorio-meta"><?= json_encode([
    'titulo' => 'Relatório de Clientes',
    'empresa' => $empresa ?? '',
    'periodo' => (!empty($filtros['dataIni']) && !empty($filtros['dataFim']))
        ? date('d/m/Y', strtotime($filtros['dataIni'])).' a '.date('d/m/Y', strtotime($filtros['dataFim']))
        : null,
    'totais' => [
        ['label' => 'Clientes Fidelizados', 'valor' => count($linhas)],
        ['label' => 'Valor Total', 'valor' => $fmt($totalVal)],
        ['label' => 'Ticket Médio Geral', 'valor' => $fmt($mediaTicket)],
        ['label' => 'Maior Ticket', 'valor' => $linhas ? $fmt($linhas[0]['TICKET_MEDIO'] ?? 0) : '—'],
    ],
], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?></script>

<div class="pbi-kpi-grid mb-3 no-print" data-export-secao="kpis">
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Clientes Fidelizados</div><div class="pbi-kpi-value"><?= count($linhas) ?></div><div class="pbi-kpi-sub">≥ 2 compras</div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Valor Total</div><div class="pbi-kpi-value text-accent"><?= $fmt($totalVal) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Ticket Médio Geral</div><div class="pbi-kpi-value"><?= $fmt($mediaTicket) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Maior Ticket</div><div class="pbi-kpi-value text-success"><?= $linhas?$fmt($linhas[0]['TICKET_MEDIO']??0):'—' ?></div></div>
</div>

<div class="mb-2"><?php include __DIR__ . '/_acoes.php' ?></div>

<div class="pbi-card" data-export-secao="dados">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-people me-2"></i>Ranking por Ticket Médio</span>
        <small class="text-muted no-print"><?= count($linhas) ?> clientes</small>
    </div>
    <div class="pbi-hint mb-2" style="margin-top:0">Seus melhores clientes no período. <strong>Compras</strong> = quantas vezes comprou; <strong>Valor Total</strong> = soma gasta; <strong>Ticket Médio</strong> = valor médio por compra.</div>
    <div class="table-responsive">
        <table class="pbi-table pbi-table-print">
            <thead><tr>
                <th>#</th><th>Cliente</th>
                <th class="text-end">Compras</th>
                <th class="text-end">Valor Total</th>
                <th class="text-end">Ticket Médio</th>
                <th>Última Compra</th>
            </tr></thead>
            <tbody>
            <?php foreach($linhas as $i=>$r): ?>
            <tr>
                <td class="text-muted"><?= $i+1 ?></td>
                <td><?= \App\Core\View::e($r['NOME']??'—') ?></td>
                <td class="text-end"><?= (int)($r['QTD_NOTAS']??0) ?>x</td>
                <td class="text-end"><?= $fmt($r['VALOR_TOTAL']??0) ?></td>
                <td class="text-end fw-bold text-accent"><?= $fmt($r['TICKET_MEDIO']??0) ?></td>
                <td><?= $fmtData($r['ULTIMA_COMPRA']) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if(!$linhas): ?><tr><td colspan="6" class="text-center py-3 text-muted">Sem dados</td></tr><?php endif; ?>
            </tbody>
            <tfoot><tr class="pbi-table-total">
                <td colspan="3" class="text-end fw-bold">Total:</td>
                <td class="text-end fw-bold text-accent"><?= $fmt($totalVal) ?></td>
                <td class="text-end fw-bold"><?= $fmt($mediaTicket) ?></td>
                <td></td>
            </tr></tfoot>
        </table>
    </div>
</div>
