<?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) : '—';
$totalAberto = array_sum(array_column($linhas,'SALDO'));
$qtdVencido  = count(array_filter($linhas, fn($r)=>($r['DIAS_ATRASO']??0)>0));
$totalVencido= array_sum(array_column(array_filter($linhas,fn($r)=>($r['DIAS_ATRASO']??0)>0),'SALDO'));
?>
<div class="pbi-page-header no-print">
    <h1 class="pbi-page-title"><i class="bi bi-exclamation-circle me-2 text-accent"></i>Inadimplência / Contas em Aberto</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">Vencimento 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'  => 'Inadimplência',
    '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' => 'Títulos em Aberto', 'valor' => count($linhas)],
        ['label' => 'Total em Aberto',   'valor' => $fmt($totalAberto)],
        ['label' => 'Títulos Vencidos',  'valor' => $qtdVencido],
        ['label' => 'Total Vencido',     'valor' => $fmt($totalVencido)],
    ],
], 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">Títulos em Aberto</div><div class="pbi-kpi-value"><?= count($linhas) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Total em Aberto</div><div class="pbi-kpi-value text-warning"><?= $fmt($totalAberto) ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Títulos Vencidos</div><div class="pbi-kpi-value text-danger"><?= $qtdVencido ?></div></div>
    <div class="pbi-kpi-card"><div class="pbi-kpi-label">Total Vencido</div><div class="pbi-kpi-value text-danger"><?= $fmt($totalVencido) ?></div></div>
</div>

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

<?php if($qtdVencido > 0): ?>
<div class="alert alert-danger d-flex gap-2 align-items-center mb-3 no-print">
    <i class="bi bi-exclamation-triangle-fill"></i>
    <strong><?= $qtdVencido ?> título(s)</strong> vencidos totalizando <strong><?= $fmt($totalVencido) ?></strong>.
</div>
<?php endif; ?>

<div class="pbi-card" data-export-secao="dados">
    <div class="pbi-card-header d-flex justify-content-between">
        <span><i class="bi bi-exclamation-circle me-2"></i>Contas a Receber em Aberto</span>
        <small class="text-muted no-print"><?= count($linhas) ?> títulos</small>
    </div>
    <div class="pbi-hint mb-2" style="margin-top:0">Contas a receber ainda em aberto. <strong>Saldo</strong> = quanto falta receber do título; <strong>Atraso</strong> = dias após o vencimento. Situação: A vencer (no prazo), Vencido, Alerta (+15 dias) e Crítico (+30 dias).</div>
    <div class="table-responsive">
        <table class="pbi-table pbi-table-print">
            <thead><tr>
                <th>Cliente</th>
                <th>Nota</th>
                <th>Parcela</th>
                <th class="text-end">Valor</th>
                <th class="text-end">Saldo</th>
                <th>Vencimento</th>
                <th class="text-end">Atraso</th>
                <th>Situação</th>
            </tr></thead>
            <tbody>
            <?php foreach($linhas as $r):
                $dias = (int)($r['DIAS_ATRASO']??0);
                $vencido = $dias > 0;
            ?>
            <tr <?= $vencido?'class="table-danger"':'' ?>>
                <td><?= \App\Core\View::e(mb_substr($r['CLIENTE']??'—',0,35)) ?></td>
                <td class="text-muted small"><?= \App\Core\View::e($r['NR_NOTA']??'—') ?></td>
                <td class="text-center"><?= (int)($r['NR_PARCELA']??1) ?>/<?= (int)($r['QT_PARCELAS']??1) ?></td>
                <td class="text-end"><?= $fmt($r['VALOR']??0) ?></td>
                <td class="text-end fw-bold <?= $vencido?'text-danger':'text-warning' ?>"><?= $fmt($r['SALDO']??0) ?></td>
                <td><?= $fmtData($r['DT_VENCIMENTO']) ?></td>
                <td class="text-end <?= $vencido?'text-danger fw-bold':'' ?>"><?= $vencido ? $dias.' dias' : '—' ?></td>
                <td>
                    <?php if($vencido): ?>
                        <span class="pbi-badge" style="background:#dc262620;color:#dc2626"><?= $dias>30?'Crítico':($dias>15?'Alerta':'Vencido') ?></span>
                    <?php else: ?>
                        <span class="pbi-badge pbi-badge-warning">A vencer</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if(!$linhas): ?><tr><td colspan="8" class="text-center py-3 text-muted">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-warning"><?= $fmt($totalAberto) ?></td>
                <td colspan="3"></td>
            </tr></tfoot>
        </table>
    </div>
</div>
