<?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,',','.');
$fmtN = fn($v,$d=1) => number_format((float)$v,$d,',','.');
$fmtP = fn($v) => number_format((float)$v,1,',','.').'%';
$qtdA = count(array_filter($linhas,fn($r)=>$r['CLASSE']==='A'));
$qtdB = count(array_filter($linhas,fn($r)=>$r['CLASSE']==='B'));
$qtdC = count(array_filter($linhas,fn($r)=>$r['CLASSE']==='C'));
$totalFat = array_sum(array_column($linhas,'FATURAMENTO'));
?>
<div class="pbi-page-header no-print">
    <h1 class="pbi-page-title"><i class="bi bi-bar-chart-steps me-2 text-accent"></i>Curva ABC de Produtos</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' ?>

<?php
$__meta = [
    'titulo' => 'Curva ABC de Produtos',
    'empresa' => $empresa ?? '',
    'totais' => [
        ['label' => 'Total Produtos', 'valor' => count($linhas)],
        ['label' => 'Faturamento',    'valor' => $fmt($totalFat)],
        ['label' => 'Classe A',       'valor' => $qtdA . ' itens'],
        ['label' => 'Classe B',       'valor' => $qtdB . ' itens'],
    ],
];
if (!empty($filtros['dataIni']) && !empty($filtros['dataFim'])) {
    $__meta['periodo'] = date('d/m/Y', strtotime($filtros['dataIni'])) . ' a ' . date('d/m/Y', strtotime($filtros['dataFim']));
}
?>
<script type="application/json" id="relatorio-meta"><?= json_encode($__meta, 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">Total Produtos</div><div class="pbi-kpi-value"><?= count($linhas) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Faturamento</div><div class="pbi-kpi-value text-accent"><?= $fmt($totalFat) ?></div></div>
    <div class="pbi-kpi-card" style="border-color:#22c55e"><div class="pbi-kpi-label">Classe A</div><div class="pbi-kpi-value text-success"><?= $qtdA ?> itens</div><div class="pbi-kpi-sub">70% fat.</div></div>
    <div class="pbi-kpi-card" style="border-color:#f59e0b"><div class="pbi-kpi-label">Classe B</div><div class="pbi-kpi-value text-warning"><?= $qtdB ?> itens</div><div class="pbi-kpi-sub">20% fat.</div></div>
    <div class="pbi-kpi-card" style="border-color:#6b7280"><div class="pbi-kpi-label">Classe C</div><div class="pbi-kpi-value text-muted"><?= $qtdC ?> itens</div><div class="pbi-kpi-sub">10% fat.</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-bar-chart-steps me-2"></i>Curva ABC Completa</span>
        <small class="text-muted no-print"><?= count($linhas) ?> produtos</small>
    </div>
    <div class="pbi-hint mb-2" style="margin-top:0">Produtos ordenados pelo que mais faturam. <strong>Classe A</strong> = poucos itens que trazem a maior parte da receita; <strong>B</strong> = intermediários; <strong>C</strong> = muitos itens de pouco peso. <strong>% Fat.</strong> = fatia do produto no faturamento; <strong>% Acum.</strong> = soma acumulada de cima para baixo.</div>
    <div class="table-responsive">
        <table class="pbi-table pbi-table-print">
            <thead><tr>
                <th>#</th><th>Código</th><th>Produto</th><th>Un</th><th>Classe</th>
                <th class="text-end">Qtd Vendida</th>
                <th class="text-end">Faturamento</th>
                <th class="text-end">% Fat.</th>
                <th class="text-end">% Acum.</th>
                <th class="text-end">Notas</th>
            </tr></thead>
            <tbody>
            <?php foreach($linhas as $i=>$r): $cls=$r['CLASSE']==='A'?'text-success fw-bold':($r['CLASSE']==='B'?'text-warning fw-bold':'text-muted'); ?>
            <tr>
                <td class="text-muted"><?= $i+1 ?></td>
                <td class="fw-semibold"><?= \App\Core\View::e($r['COD_ITEM']??'') ?></td>
                <td><?= \App\Core\View::e(mb_substr($r['DESCRICAO']??'',0,40)) ?></td>
                <td><span class="badge bg-secondary"><?= \App\Core\View::e($r['COD_UNIDADE']??'-') ?></span></td>
                <td><span class="pbi-badge <?= $r['CLASSE']==='A'?'pbi-badge-success':($r['CLASSE']==='B'?'pbi-badge-warning':'') ?>"><?= $r['CLASSE'] ?></span></td>
                <td class="text-end"><?= $fmtN($r['QTD_TOTAL']) ?></td>
                <td class="text-end fw-bold"><?= $fmt($r['FATURAMENTO']) ?></td>
                <td class="text-end"><?= $fmtP($r['PERC_FAT']) ?></td>
                <td class="text-end"><?= $fmtP($r['PERC_ACUM']) ?></td>
                <td class="text-end"><?= $r['QTD_NOTAS'] ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if(!$linhas): ?><tr><td colspan="10" class="text-center py-3 text-muted">Sem dados</td></tr><?php endif; ?>
            </tbody>
            <tfoot><tr class="pbi-table-total">
                <td colspan="6" class="text-end fw-bold">Total:</td>
                <td class="text-end fw-bold text-accent"><?= $fmt($totalFat) ?></td>
                <td colspan="3"></td>
            </tr></tfoot>
        </table>
    </div>
</div>
