<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
/* ── Base ─────────────────────────────────────── */
.content-wrapper { background:#f0f2f5; }

/* ── Header ───────────────────────────────────── */
.content-header {
    background:linear-gradient(135deg,#1a1a2e,#0f3460);
    padding:18px 24px !important; margin-bottom:0; border-radius:0;
}
.content-header h1 { color:#fff !important; margin:0; font-size:22px; font-weight:700; }
.content-header h1 small { color:rgba(255,255,255,.6) !important; font-size:13px; font-weight:400; }
.content-header .breadcrumb { background:transparent !important; margin:6px 0 0; padding:0; }
.content-header .breadcrumb li { color:rgba(255,255,255,.6); font-size:12px; }
.content-header .breadcrumb li.active { color:rgba(255,255,255,.9); }
.content-header .breadcrumb > li+li:before { color:rgba(255,255,255,.4); }

/* ── Período bar ──────────────────────────────── */
.periodo-bar {
    background:linear-gradient(135deg,#0f3460,#1a1a2e);
    padding:10px 24px; margin-bottom:20px;
    display:flex; align-items:center; flex-wrap:wrap; gap:10px;
}
.periodo-bar label { color:rgba(255,255,255,.7); font-size:11px; text-transform:uppercase; letter-spacing:.8px; margin:0 4px 0 0; }
.periodo-bar .form-control { height:30px; font-size:12px; border-radius:6px; border:1px solid rgba(255,255,255,.2); background:rgba(255,255,255,.1); color:#fff; width:140px; }
.periodo-bar .form-control:focus { background:rgba(255,255,255,.2); }
.periodo-bar .btn-filtrar { background:rgba(255,255,255,.15); color:#fff; border:1px solid rgba(255,255,255,.3); border-radius:6px; height:30px; padding:0 14px; font-size:12px; }
.periodo-bar .btn-filtrar:hover { background:rgba(255,255,255,.25); }
.periodo-bar .btn-acao { border-radius:6px; height:30px; padding:0 12px; font-size:12px; }

/* ── Cards KPI ────────────────────────────────── */
.fin-card {
    border-radius:12px; padding:20px 22px; color:#fff;
    margin-bottom:16px; position:relative; overflow:hidden;
    box-shadow:0 4px 15px rgba(0,0,0,.15);
    transition:transform .2s, box-shadow .2s; cursor:default;
}
.fin-card:hover { transform:translateY(-3px); box-shadow:0 8px 25px rgba(0,0,0,.2); }
.fin-card .fc-lbl { font-size:10px; opacity:.8; text-transform:uppercase; letter-spacing:1px; }
.fin-card .fc-val { font-size:24px; font-weight:700; margin:6px 0 4px; letter-spacing:-.5px; line-height:1; }
.fin-card .fc-sub { font-size:11px; opacity:.75; }
.fin-card .fc-ico { position:absolute; right:16px; top:50%; transform:translateY(-50%); font-size:52px; opacity:.12; }
.fin-card .fc-link { color:rgba(255,255,255,.75); font-size:11px; text-decoration:none; display:block; margin-top:10px; }
.fin-card .fc-link:hover { color:#fff; }
.fin-card.verde    { background:linear-gradient(135deg,#1D6B3B,#27ae60); }
.fin-card.azul     { background:linear-gradient(135deg,#1F4E79,#2980b9); }
.fin-card.laranja  { background:linear-gradient(135deg,#C55A11,#e67e22); }
.fin-card.vermelho { background:linear-gradient(135deg,#C00000,#e74c3c); }
.fin-card.roxo     { background:linear-gradient(135deg,#6c5ce7,#a29bfe); }
.fin-card.cinza    { background:linear-gradient(135deg,#2c3e50,#546e7a); }

/* ── Boxes ────────────────────────────────────── */
.box {
    border-radius:12px !important; border:none !important;
    box-shadow:0 2px 12px rgba(0,0,0,.08) !important; margin-bottom:20px;
}
.box-header { border-radius:12px 12px 0 0 !important; padding:13px 18px !important; }
.box-header.with-border { border-bottom:1px solid #f0f0f0 !important; }
.box-header .box-title { font-size:14px; font-weight:600; color:#333; }
.box-footer { border-radius:0 0 12px 12px !important; background:#fafafa !important; border-top:1px solid #f0f0f0 !important; }

/* ── Section divider ──────────────────────────── */
.section-divider {
    display:flex; align-items:center; margin:22px 0 14px;
    color:#666; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:1.2px;
}
.section-divider::after { content:''; flex:1; height:1px; background:#e0e0e0; margin-left:10px; }

/* ── Tabela lançamentos ───────────────────────── */
.lancam-table { width:100%; border-collapse:collapse; }
.lancam-table thead th {
    background:#f5f7fa; font-size:11px; font-weight:700; color:#666;
    padding:9px 12px; text-transform:uppercase; letter-spacing:.6px;
    border-bottom:2px solid #e8ecf0;
}
.lancam-table tbody tr { border-bottom:1px solid #f0f0f0; transition:background .1s; }
.lancam-table tbody tr:hover { background:#f8f9ff; }
.lancam-table tbody td { padding:9px 12px; font-size:13px; vertical-align:middle; }
.lancam-table tbody tr.row-pago td { opacity:.7; }
.lancam-table tbody tr.row-vencido { border-left:3px solid #C00000; }

/* ── Status badges ────────────────────────────── */
.badge-status { display:inline-block; padding:3px 9px; border-radius:20px; font-size:11px; font-weight:600; }
.badge-pago     { background:#e8f5e9; color:#1D6B3B; }
.badge-pendente { background:#fff8e1; color:#C55A11; }
.badge-vencido  { background:#ffebee; color:#C00000; }
.badge-cancelado{ background:#f5f5f5; color:#888; }
.tribunal-badge { display:inline-block; padding:2px 8px; border-radius:4px; font-size:11px; font-weight:700; background:#1F4E79; color:#fff; }

/* ── Conta card ───────────────────────────────── */
.conta-card {
    border-radius:10px; padding:16px 18px; color:#fff; margin-bottom:12px;
    position:relative; overflow:hidden; box-shadow:0 3px 12px rgba(0,0,0,.15);
    display:flex; align-items:center; justify-content:space-between;
    transition:transform .15s;
}
.conta-card:hover { transform:translateY(-2px); }
.conta-card .cc-nome { font-size:12px; opacity:.85; }
.conta-card .cc-saldo { font-size:20px; font-weight:700; }
.conta-card .cc-banco { font-size:11px; opacity:.7; margin-top:2px; }
.conta-card .cc-ico { font-size:36px; opacity:.2; }
.conta-card a { color:rgba(255,255,255,.75); font-size:11px; text-decoration:none; }
.conta-card a:hover { color:#fff; }

/* ── Linha vencida alert ──────────────────────── */
.venc-item {
    padding:10px 14px; border-left:3px solid #C00000;
    margin-bottom:8px; background:#fff5f5; border-radius:0 8px 8px 0;
}
.venc-item .vi-data { font-size:11px; color:#C00000; font-weight:600; }
.venc-item .vi-nome { font-weight:600; color:#222; font-size:13px; }
.venc-item .vi-val  { font-size:13px; color:#C00000; font-weight:700; }
</style>

<!-- ── HEADER ─────────────────────────────────── -->
<section class="content-header">
    <h1><i class="fa fa-money"></i> Financeiro <small><?php echo date('d/m/Y') ?></small></h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li class="active">Financeiro</li>
    </ol>
</section>

<!-- ── BARRA DE PERÍODO + AÇÕES ───────────────── -->
<form method="get" action="<?php echo site_url('admin/financeiro') ?>">
<div class="periodo-bar">
    <label>De</label>
    <input type="date" name="data_ini" class="form-control" value="<?php echo $data_ini ?>">
    <label>Até</label>
    <input type="date" name="data_fim" class="form-control" value="<?php echo $data_fim ?>">
    <select name="client_id" class="form-control" style="width:160px">
        <option value="">Todos os clientes</option>
        <?php foreach ($contas_clientes ?? [] as $cl): ?>
        <option value="<?php echo $cl->id ?>" <?php echo $this->input->get('client_id') == $cl->id ? 'selected' : '' ?>>
            <?php echo htmlspecialchars($cl->name) ?>
        </option>
        <?php endforeach; ?>
    </select>
    <button type="submit" class="btn-filtrar"><i class="fa fa-search"></i> Atualizar</button>

    <div style="margin-left:auto;display:flex;gap:6px;flex-wrap:wrap">
        <a href="<?php echo site_url('admin/financeiro/add_lancamento?tipo=receber') ?>" class="btn btn-success btn-acao">
            <i class="fa fa-plus"></i> Nova Receita
        </a>
        <a href="<?php echo site_url('admin/financeiro/add_lancamento?tipo=pagar') ?>" class="btn btn-danger btn-acao">
            <i class="fa fa-plus"></i> Nova Despesa
        </a>
        <a href="<?php echo site_url('admin/financeiro/transferencias') ?>" class="btn btn-warning btn-acao">
            <i class="fa fa-exchange"></i> Transferência
        </a>
        <a href="<?php echo site_url('admin/financeiro/relatorio') ?>" class="btn btn-info btn-acao">
            <i class="fa fa-bar-chart"></i> Relatório
        </a>
        <a href="<?php echo site_url('admin/financeiro/bpo') ?>" class="btn btn-acao" style="background:#1a659e;color:#fff;border:none">
            <i class="fa fa-university"></i> BPO
        </a>
    </div>
</div>
</form>

<section class="content">

<?php if ($this->session->flashdata('message')): ?>
<div class="alert alert-success alert-dismissible">
    <button class="close" data-dismiss="alert">&times;</button>
    <?php echo $this->session->flashdata('message') ?>
</div>
<?php endif; ?>

<?php if (!empty($vencidos)): ?>
<div class="alert alert-danger alert-dismissible" style="border-radius:10px;border-left:4px solid #900">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    <i class="fa fa-exclamation-triangle"></i>
    <strong><?php echo count($vencidos) ?> lançamento(s) VENCIDO(s)</strong> aguardando baixa.
    <a href="#sec-vencidos" class="btn btn-danger btn-xs pull-right">Ver agora</a>
</div>
<?php endif; ?>

<!-- ── KPIs ───────────────────────────────────── -->
<div class="section-divider"><i class="fa fa-tachometer" style="margin-right:6px"></i> Resumo do Período</div>
<div class="row">
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="fin-card verde">
            <div class="fc-lbl">Recebido</div>
            <div class="fc-val">R$ <?php echo number_format($totais->total_recebido ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-arrow-down fc-ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/receber?status=pago&data_ini=' . $data_ini . '&data_fim=' . $data_fim) ?>" class="fc-link">Ver detalhes →</a>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="fin-card azul">
            <div class="fc-lbl">A Receber</div>
            <div class="fc-val">R$ <?php echo number_format($totais->total_pendente_receber ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-clock-o fc-ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/receber?status=pendente&data_ini=' . $data_ini . '&data_fim=' . $data_fim) ?>" class="fc-link">Ver detalhes →</a>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="fin-card laranja">
            <div class="fc-lbl">Despesas Pagas</div>
            <div class="fc-val">R$ <?php echo number_format($totais->total_pago ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-arrow-up fc-ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/pagar?status=pago&data_ini=' . $data_ini . '&data_fim=' . $data_fim) ?>" class="fc-link">Ver detalhes →</a>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="fin-card vermelho">
            <div class="fc-lbl">Vencido</div>
            <div class="fc-val">R$ <?php
                $tot_vencido = 0;
                foreach ($vencidos as $v) $tot_vencido += $v->valor;
                echo number_format($tot_vencido, 2, ',', '.');
            ?></div>
            <i class="fa fa-exclamation-triangle fc-ico"></i>
            <a href="#sec-vencidos" class="fc-link">Ver vencidos →</a>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="fin-card roxo">
            <div class="fc-lbl">Total Receitas</div>
            <div class="fc-val">R$ <?php echo number_format($totais->total_receber ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-line-chart fc-ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/receber?data_ini=' . $data_ini . '&data_fim=' . $data_fim) ?>" class="fc-link">Ver todos →</a>
        </div>
    </div>
    <div class="col-md-2 col-sm-4 col-xs-6">
        <div class="fin-card cinza">
            <div class="fc-lbl">Total Despesas</div>
            <div class="fc-val">R$ <?php echo number_format($totais->total_pagar ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-list fc-ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/pagar?data_ini=' . $data_ini . '&data_fim=' . $data_fim) ?>" class="fc-link">Ver todos →</a>
        </div>
    </div>
</div>

<!-- ── GRÁFICO + CONTAS ────────────────────────── -->
<div class="row">
    <div class="col-md-7">
        <div class="box" style="border-top:3px solid #1F4E79">
            <div class="box-header with-border">
                <h3 class="box-title"><i class="fa fa-bar-chart text-blue"></i> Receitas x Despesas no Período</h3>
                <div class="box-tools pull-right">
                    <a href="<?php echo site_url('admin/financeiro/relatorio') ?>" class="btn btn-xs btn-default"><i class="fa fa-external-link"></i> Relatório</a>
                </div>
            </div>
            <div class="box-body"><canvas id="chart-financeiro" height="220"></canvas></div>
        </div>
    </div>
    <div class="col-md-5">
        <div class="box" style="border-top:3px solid #27ae60">
            <div class="box-header with-border">
                <h3 class="box-title"><i class="fa fa-university" style="color:#1D6B3B"></i> Saldo por Conta</h3>
                <div class="box-tools pull-right">
                    <a href="<?php echo site_url('admin/financeiro/contas') ?>" class="btn btn-xs btn-default"><i class="fa fa-cog"></i> Gerenciar</a>
                </div>
            </div>
            <div class="box-body" style="padding:12px;max-height:265px;overflow-y:auto">
                <?php if (empty($contas)): ?>
                <div class="text-center text-muted" style="padding:20px">
                    <i class="fa fa-university" style="font-size:28px;opacity:.3;display:block;margin-bottom:8px"></i>
                    Nenhuma conta cadastrada.
                    <a href="<?php echo site_url('admin/financeiro/contas') ?>" class="btn btn-xs btn-success" style="display:block;margin-top:8px">Cadastrar conta</a>
                </div>
                <?php else: ?>
                <?php foreach ($contas as $conta): ?>
                <div class="conta-card" style="background:<?php echo htmlspecialchars($conta->cor ?? '#3c8dbc') ?>">
                    <div>
                        <div class="cc-nome"><?php echo htmlspecialchars($conta->nome) ?></div>
                        <div class="cc-saldo">R$ <?php echo number_format($conta->saldo_atual, 2, ',', '.') ?></div>
                        <div class="cc-banco"><?php echo htmlspecialchars($conta->banco ?? $conta->tipo ?? '') ?></div>
                        <a href="<?php echo site_url('admin/financeiro/extrato/' . $conta->id) ?>">Ver extrato →</a>
                    </div>
                    <i class="fa fa-bank cc-ico"></i>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- ── A RECEBER ───────────────────────────────── -->
<div class="section-divider"><i class="fa fa-arrow-down" style="margin-right:6px;color:#1D6B3B"></i> Contas a Receber no Período</div>
<div class="box" style="border-top:3px solid #1D6B3B">
    <div class="box-header with-border" style="background:linear-gradient(to right,rgba(29,107,59,.08),transparent)">
        <h3 class="box-title" style="color:#1D6B3B">
            <i class="fa fa-arrow-down"></i>
            Total: <strong>R$ <?php echo number_format($totais->total_receber ?? 0, 2, ',', '.') ?></strong>
        </h3>
        <div class="box-tools pull-right">
            <a href="<?php echo site_url('admin/financeiro/lancamentos/receber?data_ini=' . $data_ini . '&data_fim=' . $data_fim) ?>" class="btn btn-xs btn-success">Ver todos</a>
            <a href="<?php echo site_url('admin/financeiro/add_lancamento?tipo=receber') ?>" class="btn btn-xs btn-default"><i class="fa fa-plus"></i> Nova receita</a>
        </div>
    </div>
    <div class="box-body no-padding">
        <?php if (empty($a_receber)): ?>
        <div class="text-center text-muted" style="padding:30px">
            <i class="fa fa-check-circle text-success" style="font-size:32px;display:block;margin-bottom:8px"></i>
            Nenhum lançamento a receber no período.
        </div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table class="lancam-table" id="tbl-receber">
            <thead>
                <tr>
                    <th></th>
                    <th>Cadastro</th>
                    <th>Tipo / Categoria</th>
                    <th>Processo / Mês</th>
                    <th>Cliente</th>
                    <th>Vencimento</th>
                    <th class="text-right">Valor</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($a_receber as $l):
                $vencido = $l->status === 'pendente' && strtotime($l->vencimento) < time();
            ?>
            <tr class="<?php echo $l->status === 'pago' ? 'row-pago' : ($vencido ? 'row-vencido' : '') ?>">
                <td style="width:8px;padding:0">
                    <?php if ($l->status !== 'pago'): ?>
                    <div style="width:4px;height:100%;background:<?php echo $vencido ? '#C00000' : '#1D6B3B' ?>;min-height:40px;border-radius:2px"></div>
                    <?php endif; ?>
                </td>
                <td style="white-space:nowrap"><small><?php echo date('d/m/y', strtotime($l->created_at)) ?></small></td>
                <td><?php echo htmlspecialchars($l->categoria ?? $l->subcategoria ?? '—') ?></td>
                <td><small class="text-muted"><?php echo htmlspecialchars($l->competencia_mes ?? $l->case_no ?? '—') ?></small></td>
                <td><?php echo htmlspecialchars($l->client_nome ?? '—') ?></td>
                <td style="white-space:nowrap">
                    <?php echo date('d/m/Y', strtotime($l->vencimento)) ?>
                    <?php if ($vencido): ?><br><small class="text-danger"><i class="fa fa-clock-o"></i> Vencido</small><?php endif; ?>
                </td>
                <td class="text-right" style="white-space:nowrap">
                    <strong style="color:<?php echo $l->status === 'pago' ? '#1D6B3B' : ($vencido ? '#C00000' : '#333') ?>">
                        R$ <?php echo number_format($l->valor, 2, ',', '.') ?>
                    </strong>
                </td>
                <td>
                    <?php
                    $badges = ['pago' => 'badge-pago', 'pendente' => 'badge-pendente', 'cancelado' => 'badge-cancelado'];
                    $label  = ['pago' => 'Recebido', 'pendente' => 'Pendente', 'cancelado' => 'Cancelado'];
                    $st = $l->status ?? 'pendente';
                    ?>
                    <span class="badge-status <?php echo $badges[$st] ?? 'badge-pendente' ?>">
                        <?php echo $vencido ? 'Vencido' : ($label[$st] ?? ucfirst($st)) ?>
                    </span>
                </td>
                <td style="white-space:nowrap">
                    <?php if ($l->status === 'pendente'): ?>
                    <button class="btn btn-success btn-xs btn-baixar" data-id="<?php echo $l->id ?>" title="Dar baixa"><i class="fa fa-check"></i></button>
                    <?php endif; ?>
                    <a href="<?php echo site_url('admin/financeiro/add_lancamento/' . $l->id) ?>" class="btn btn-warning btn-xs" title="Editar"><i class="fa fa-pencil"></i></a>
                    <a href="<?php echo site_url('admin/financeiro/recibo/' . $l->id) ?>" class="btn btn-info btn-xs" title="Recibo"><i class="fa fa-file-text-o"></i></a>
                    <a href="<?php echo site_url('admin/financeiro/delete_lancamento/' . $l->id) ?>" class="btn btn-danger btn-xs" onclick="return confirm('Excluir este lançamento?')" title="Excluir"><i class="fa fa-trash"></i></a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ── A PAGAR ────────────────────────────────── -->
<div class="section-divider"><i class="fa fa-arrow-up" style="margin-right:6px;color:#C00000"></i> Contas a Pagar no Período</div>
<div class="box" style="border-top:3px solid #C00000">
    <div class="box-header with-border" style="background:linear-gradient(to right,rgba(192,0,0,.06),transparent)">
        <h3 class="box-title" style="color:#C00000">
            <i class="fa fa-arrow-up"></i>
            Total: <strong>R$ <?php echo number_format($totais->total_pagar ?? 0, 2, ',', '.') ?></strong>
        </h3>
        <div class="box-tools pull-right">
            <a href="<?php echo site_url('admin/financeiro/lancamentos/pagar?data_ini=' . $data_ini . '&data_fim=' . $data_fim) ?>" class="btn btn-xs btn-danger">Ver todos</a>
            <a href="<?php echo site_url('admin/financeiro/add_lancamento?tipo=pagar') ?>" class="btn btn-xs btn-default"><i class="fa fa-plus"></i> Nova despesa</a>
        </div>
    </div>
    <div class="box-body no-padding">
        <?php if (empty($a_pagar)): ?>
        <div class="text-center text-muted" style="padding:30px">
            <i class="fa fa-check-circle text-success" style="font-size:32px;display:block;margin-bottom:8px"></i>
            Nenhum lançamento a pagar no período.
        </div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table class="lancam-table" id="tbl-pagar">
            <thead>
                <tr>
                    <th></th>
                    <th>Cadastro</th>
                    <th>Descrição</th>
                    <th>Fornecedor</th>
                    <th>Forma Pgto</th>
                    <th>Vencimento</th>
                    <th class="text-right">Valor</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($a_pagar as $l):
                $vencido = $l->status === 'pendente' && strtotime($l->vencimento) < time();
            ?>
            <tr class="<?php echo $l->status === 'pago' ? 'row-pago' : ($vencido ? 'row-vencido' : '') ?>">
                <td style="width:8px;padding:0">
                    <?php if ($l->status !== 'pago'): ?>
                    <div style="width:4px;height:100%;background:<?php echo $vencido ? '#C00000' : '#C55A11' ?>;min-height:40px;border-radius:2px"></div>
                    <?php endif; ?>
                </td>
                <td style="white-space:nowrap"><small><?php echo date('d/m/y', strtotime($l->created_at)) ?></small></td>
                <td><?php echo htmlspecialchars($l->descricao ?? '—') ?></td>
                <td><?php echo htmlspecialchars($l->fornecedor ?? $l->client_nome ?? '—') ?></td>
                <td><small><?php echo htmlspecialchars($l->forma_pagamento ?? '—') ?></small></td>
                <td style="white-space:nowrap">
                    <?php echo date('d/m/Y', strtotime($l->vencimento)) ?>
                    <?php if ($vencido): ?><br><small class="text-danger"><i class="fa fa-clock-o"></i> Vencido</small><?php endif; ?>
                </td>
                <td class="text-right" style="white-space:nowrap">
                    <strong style="color:<?php echo $l->status === 'pago' ? '#888' : ($vencido ? '#C00000' : '#333') ?>">
                        R$ <?php echo number_format($l->valor, 2, ',', '.') ?>
                    </strong>
                </td>
                <td>
                    <?php $st = $l->status ?? 'pendente'; ?>
                    <span class="badge-status <?php echo $badges[$st] ?? 'badge-pendente' ?>">
                        <?php echo $vencido ? 'Vencido' : ($label[$st] ?? ucfirst($st)) ?>
                    </span>
                </td>
                <td style="white-space:nowrap">
                    <?php if ($l->status === 'pendente'): ?>
                    <button class="btn btn-success btn-xs btn-baixar" data-id="<?php echo $l->id ?>" title="Pagar"><i class="fa fa-check"></i></button>
                    <?php endif; ?>
                    <a href="<?php echo site_url('admin/financeiro/add_lancamento/' . $l->id) ?>" class="btn btn-warning btn-xs" title="Editar"><i class="fa fa-pencil"></i></a>
                    <a href="<?php echo site_url('admin/financeiro/delete_lancamento/' . $l->id) ?>" class="btn btn-danger btn-xs" onclick="return confirm('Excluir este lançamento?')"><i class="fa fa-trash"></i></a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- ── VENCIDOS ───────────────────────────────── -->
<?php if (!empty($vencidos)): ?>
<div class="section-divider" id="sec-vencidos"><i class="fa fa-exclamation-circle" style="margin-right:6px;color:#C00000"></i> Lançamentos Vencidos</div>
<div class="box" style="border-top:3px solid #C00000">
    <div class="box-header with-border" style="background:linear-gradient(to right,rgba(192,0,0,.08),transparent)">
        <h3 class="box-title text-danger"><i class="fa fa-exclamation-circle"></i> <?php echo count($vencidos) ?> lançamento(s) vencido(s) aguardando baixa</h3>
    </div>
    <div class="box-body no-padding">
        <table class="lancam-table">
            <thead>
                <tr>
                    <th>Cliente</th>
                    <th>Descrição</th>
                    <th>Vencimento</th>
                    <th>Dias em atraso</th>
                    <th class="text-right">Valor</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($vencidos as $v):
                $dias = (int) floor((time() - strtotime($v->vencimento)) / 86400);
            ?>
            <tr class="row-vencido">
                <td><strong><?php echo htmlspecialchars($v->client_nome ?? '—') ?></strong></td>
                <td><?php echo htmlspecialchars($v->descricao ?? '—') ?></td>
                <td class="text-danger" style="white-space:nowrap"><i class="fa fa-calendar-times-o"></i> <?php echo date('d/m/Y', strtotime($v->vencimento)) ?></td>
                <td><span style="background:#C00000;color:#fff;padding:2px 8px;border-radius:10px;font-size:11px"><?php echo $dias ?> dias</span></td>
                <td class="text-right"><strong class="text-danger">R$ <?php echo number_format($v->valor, 2, ',', '.') ?></strong></td>
                <td style="white-space:nowrap">
                    <button class="btn btn-success btn-xs btn-baixar" data-id="<?php echo $v->id ?>"><i class="fa fa-check"></i> Baixar</button>
                    <a href="<?php echo site_url('admin/financeiro/recibo/' . $v->id) ?>" class="btn btn-info btn-xs"><i class="fa fa-file-text-o"></i></a>
                    <a href="<?php echo site_url('admin/financeiro/add_lancamento/' . $v->id) ?>" class="btn btn-warning btn-xs"><i class="fa fa-pencil"></i></a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

</section>

<!-- ── MODAL BAIXAR ───────────────────────────── -->
<div class="modal fade" id="modal-baixar">
    <div class="modal-dialog modal-sm">
        <div class="modal-content" style="border-radius:12px;overflow:hidden">
            <div class="modal-header" style="background:linear-gradient(135deg,#1D6B3B,#27ae60);color:#fff;border:none">
                <h4 class="modal-title" style="color:#fff"><i class="fa fa-check-circle"></i> Confirmar Baixa</h4>
            </div>
            <form id="form-baixar" method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Data do Pagamento</label>
                        <input type="date" name="data_pagamento" class="form-control" value="<?php echo date('Y-m-d') ?>">
                    </div>
                </div>
                <div class="modal-footer" style="border-top:1px solid #f0f0f0">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-success"><i class="fa fa-check"></i> Confirmar Baixa</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
$(function () {
    // Botão baixar
    $('.btn-baixar').on('click', function () {
        var id = $(this).data('id');
        $('#form-baixar').attr('action', '<?php echo site_url('admin/financeiro/baixar/') ?>' + id);
        $('#modal-baixar').modal('show');
    });

    // Gráfico Receitas x Despesas
    var ctx = document.getElementById('chart-financeiro');
    if (ctx) {
        <?php
        // Agrupa por mês os dados do período
        $meses_labels = [];
        $meses_rec    = [];
        $meses_pag    = [];
        $todos = array_merge((array)$a_receber, (array)$a_pagar);
        $por_mes = [];
        foreach ($todos as $l) {
            $m = date('m/Y', strtotime($l->vencimento));
            if (!isset($por_mes[$m])) $por_mes[$m] = ['rec' => 0, 'pag' => 0];
            if ($l->tipo === 'receber') $por_mes[$m]['rec'] += (float)$l->valor;
            else                        $por_mes[$m]['pag'] += (float)$l->valor;
        }
        ksort($por_mes);
        foreach ($por_mes as $mes => $vals) {
            $meses_labels[] = $mes;
            $meses_rec[]    = $vals['rec'];
            $meses_pag[]    = $vals['pag'];
        }
        ?>
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($meses_labels) ?>,
                datasets: [
                    {
                        label: 'Receitas',
                        data: <?php echo json_encode($meses_rec) ?>,
                        backgroundColor: 'rgba(29,107,59,.8)',
                        borderColor: '#1D6B3B',
                        borderWidth: 1,
                        borderRadius: 5
                    },
                    {
                        label: 'Despesas',
                        data: <?php echo json_encode($meses_pag) ?>,
                        backgroundColor: 'rgba(197,90,17,.75)',
                        borderColor: '#C55A11',
                        borderWidth: 1,
                        borderRadius: 5
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'top' },
                    tooltip: {
                        callbacks: {
                            label: function (c) {
                                return c.dataset.label + ': R$ ' + c.parsed.y.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function (v) {
                                return 'R$ ' + v.toLocaleString('pt-BR', { minimumFractionDigits: 0 });
                            }
                        }
                    }
                }
            }
        });
    }
});
</script>
