<?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) : '—';
$totalFat = array_sum(array_column($linhas,'TOTAL_NOTA'));
?>
<div class="pbi-page-header no-print">
    <h1 class="pbi-page-title"><i class="bi bi-bag-check me-2 text-accent"></i>Relatório de Compras</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 Compras',
    'empresa' => $empresa ?? '',
    'periodo' => ($filtros['dataIni'] ?? '') && ($filtros['dataFim'] ?? '')
        ? $fmtData($filtros['dataIni']).' a '.$fmtData($filtros['dataFim'])
        : '',
    'totais'  => [
        ['label' => 'Notas de Entrada', 'valor' => (int)($kpis['QTD_NOTAS'] ?? 0)],
        ['label' => 'Total Compras',    'valor' => $fmt($kpis['TOTAL_COMPRAS'] ?? 0)],
        ['label' => 'Fornecedores',     'valor' => (int)($kpis['QTD_FORNECEDORES'] ?? 0)],
        ['label' => 'Total Produtos',   'valor' => $fmt($kpis['TOTAL_PRODUTOS'] ?? 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">Notas de Entrada</div><div class="pbi-kpi-value"><?= (int)($kpis['QTD_NOTAS']??0) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Total Compras</div><div class="pbi-kpi-value text-danger"><?= $fmt($kpis['TOTAL_COMPRAS']??0) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Fornecedores</div><div class="pbi-kpi-value"><?= (int)($kpis['QTD_FORNECEDORES']??0) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Total Produtos</div><div class="pbi-kpi-value"><?= $fmt($kpis['TOTAL_PRODUTOS']??0) ?></div></div>
</div>

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

<!-- Por Fornecedor -->
<?php if($forn): ?>
<div class="pbi-card mb-3">
    <div class="pbi-card-header"><i class="bi bi-building me-2"></i>Por Fornecedor</div>
    <div class="pbi-hint mb-2" style="margin-top:0">Quanto você comprou de cada fornecedor. <strong>% Part.</strong> = fatia desse fornecedor no total comprado no período.</div>
    <div class="table-responsive">
        <table class="pbi-table pbi-table-print">
            <thead><tr><th>#</th><th>Fornecedor</th><th class="text-end">Notas</th><th class="text-end">Total</th><th class="text-end">% Part.</th></tr></thead>
            <tbody>
            <?php $totF = array_sum(array_column($forn,'TOTAL_COMPRAS')); foreach($forn as $i=>$r): ?>
            <tr>
                <td class="text-muted"><?= $i+1 ?></td>
                <td><?= \App\Core\View::e($r['FORNECEDOR']??'—') ?></td>
                <td class="text-end"><?= (int)($r['QTD_NOTAS']??0) ?></td>
                <td class="text-end fw-bold text-danger"><?= $fmt($r['TOTAL_COMPRAS']??0) ?></td>
                <td class="text-end text-muted"><?= $totF>0?number_format((float)($r['TOTAL_COMPRAS']??0)/$totF*100,1,',','.').'%':'—' ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<!-- Notas detalhadas -->
<div class="pbi-card" data-export-secao="dados">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-bag-check me-2"></i>Notas de Entrada</span>
        <small class="text-muted no-print"><?= count($linhas) ?> registros</small>
    </div>
    <div class="pbi-hint mb-2" style="margin-top:0">Cada nota de compra recebida. <strong>Total Prod.</strong> = só os produtos; <strong>Total Nota</strong> = valor final pago (com impostos/frete).</div>
    <div class="table-responsive">
        <table class="pbi-table pbi-table-print">
            <thead><tr><th>Data</th><th>Nota</th><th>Fornecedor</th><th class="text-end">Total Prod.</th><th class="text-end">Total Nota</th></tr></thead>
            <tbody>
            <?php foreach($linhas as $r): ?>
            <tr>
                <td><?= $fmtData($r['DATA_EMISSAO']) ?></td>
                <td><?= $r['NR_NOTA'] ?>/<?= $r['SERIE'] ?></td>
                <td><?= \App\Core\View::e(mb_substr($r['FORNECEDOR']??'—',0,40)) ?></td>
                <td class="text-end"><?= $fmt($r['TOTAL_PRODUTOS']) ?></td>
                <td class="text-end fw-bold text-danger"><?= $fmt($r['TOTAL_NOTA']) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if(!$linhas): ?><tr><td colspan="5" class="text-center text-muted py-3">Sem dados</td></tr><?php endif; ?>
            </tbody>
            <tfoot><tr class="pbi-table-total"><td colspan="4" class="text-end fw-bold">Total:</td><td class="text-end fw-bold text-danger"><?= $fmt($totalFat) ?></td></tr></tfoot>
        </table>
    </div>
</div>
