<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
.content-header {
    background:linear-gradient(135deg,<?php echo $tipo==='receber'?'#1a3a1a,#1D6B3B':'#3a1a1a,#C00000'?>);
    padding:18px 24px !important; margin-bottom: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; }
.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); }

.filter-bar {
    background:<?php echo $tipo==='receber'?'linear-gradient(135deg,#1D6B3B,#1a3a1a)':'linear-gradient(135deg,#C00000,#3a1a1a)'?>;
    padding:10px 24px; margin-bottom:20px;
    display:flex; align-items:center; flex-wrap:wrap; gap:8px;
}
.filter-bar label { color:rgba(255,255,255,.75); font-size:11px; text-transform:uppercase; letter-spacing:.7px; margin:0 3px 0 0; }
.filter-bar .form-control { height:30px; font-size:12px; border-radius:6px; border:1px solid rgba(255,255,255,.2); background:rgba(255,255,255,.12); color:#fff; }
.filter-bar .form-control option { color:#333; background:#fff; }
.filter-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; }
.filter-bar .btn-limpar  { background:transparent; color:rgba(255,255,255,.6); border:1px solid rgba(255,255,255,.2); border-radius:6px; height:30px; padding:0 12px; font-size:12px; }

.kpi-card {
    border-radius:12px; padding:16px 18px; color:#fff; margin-bottom:16px;
    position:relative; overflow:hidden; box-shadow:0 4px 14px rgba(0,0,0,.15);
    transition:transform .2s;
}
.kpi-card:hover { transform:translateY(-2px); }
.kpi-card .kv  { font-size:22px; font-weight:700; margin:6px 0 2px; letter-spacing:-.5px; }
.kpi-card .kl  { font-size:10px; opacity:.8; text-transform:uppercase; letter-spacing:1px; }
.kpi-card .ki  { position:absolute; right:14px; top:50%; transform:translateY(-50%); font-size:46px; opacity:.12; }

.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-footer { border-radius:0 0 12px 12px !important; background:#fafafa !important; border-top:1px solid #f0f0f0 !important; }

.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-vencido { border-left:3px solid #C00000; background:#fff8f8; }
.lancam-table tbody tr.row-pago td { opacity:.7; }
.lancam-table tfoot td { padding:10px 12px; font-weight:700; background:#f5f7fa; border-top:2px solid #e0e0e0; }

.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; }
</style>

<section class="content-header">
    <h1>
        <i class="fa fa-<?php echo $tipo==='receber'?'arrow-down':'arrow-up'?>"></i>
        <?php echo $page_title ?>
        <small><?php echo count($lancamentos) ?> lançamento(s)</small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin/financeiro') ?>"><i class="fa fa-money"></i> Financeiro</a></li>
        <li class="active"><?php echo $page_title ?></li>
    </ol>
</section>

<!-- Barra de filtros -->
<form method="get" action="<?php echo site_url('admin/financeiro/lancamentos/' . $tipo) ?>">
<input type="hidden" name="tipo" value="<?php echo $tipo ?>">
<div class="filter-bar">
    <label>De</label>
    <input type="date" name="data_ini" class="form-control" style="width:130px" value="<?php echo $filtros['data_ini'] ?>">
    <label>Até</label>
    <input type="date" name="data_fim" class="form-control" style="width:130px" value="<?php echo $filtros['data_fim'] ?>">
    <label>Status</label>
    <select name="status" class="form-control" style="width:130px">
        <option value="">Todos</option>
        <option value="pendente"  <?php echo $filtros['status']==='pendente'  ?'selected':''?>>Pendente</option>
        <option value="pago"      <?php echo $filtros['status']==='pago'      ?'selected':''?>>Pago/Recebido</option>
        <option value="cancelado" <?php echo $filtros['status']==='cancelado' ?'selected':''?>>Cancelado</option>
    </select>
    <label>Conta</label>
    <select name="conta_id" class="form-control" style="width:140px">
        <option value="">Todas</option>
        <?php foreach ($contas as $ct): ?>
        <option value="<?php echo $ct->id ?>" <?php echo $filtros['conta_id']==$ct->id?'selected':''?>><?php echo htmlspecialchars($ct->nome) ?></option>
        <?php endforeach; ?>
    </select>
    <label>Cliente</label>
    <select name="client_id" class="form-control" style="width:160px">
        <option value="">Todos</option>
        <?php foreach ($clientes as $c): ?>
        <option value="<?php echo $c->id ?>" <?php echo $filtros['client_id']==$c->id?'selected':''?>><?php echo htmlspecialchars($c->name) ?></option>
        <?php endforeach; ?>
    </select>
    <button type="submit" class="btn-filtrar"><i class="fa fa-search"></i> Filtrar</button>
    <a href="<?php echo site_url('admin/financeiro/lancamentos/'.$tipo) ?>" class="btn-limpar">Limpar</a>
    <div style="margin-left:auto">
        <a href="<?php echo site_url('admin/financeiro/add_lancamento?tipo='.$tipo) ?>"
           class="btn btn-sm" style="background:#fff;color:<?php echo $tipo==='receber'?'#1D6B3B':'#C00000'?>;border-radius:6px;height:30px;line-height:18px;font-size:12px;font-weight:600">
            <i class="fa fa-plus"></i> Novo <?php echo $tipo==='receber'?'Receita':'Despesa' ?>
        </a>
    </div>
</div>
</form>

<section class="content">

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

<!-- KPIs -->
<div class="row">
    <?php
    $cor_pago  = $tipo==='receber' ? 'linear-gradient(135deg,#1D6B3B,#27ae60)' : 'linear-gradient(135deg,#C00000,#e74c3c)';
    $label_pago= $tipo==='receber' ? 'Recebido' : 'Pago';
    $key_pago  = $tipo==='receber' ? 'total_recebido' : 'total_pago';
    $key_pend  = 'total_pendente_' . $tipo;
    $key_venc  = 'total_vencido_' . $tipo;
    $key_total = 'total_' . $tipo;
    ?>
    <div class="col-md-3 col-sm-6">
        <div class="kpi-card" style="background:linear-gradient(135deg,#C55A11,#e67e22)">
            <div class="kl">Pendente</div>
            <div class="kv">R$ <?php echo number_format($totais->$key_pend ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-clock-o ki"></i>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="kpi-card" style="background:<?php echo $cor_pago ?>">
            <div class="kl"><?php echo $label_pago ?></div>
            <div class="kv">R$ <?php echo number_format($totais->$key_pago ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-check ki"></i>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="kpi-card" style="background:linear-gradient(135deg,#C00000,#e74c3c)">
            <div class="kl">Vencido</div>
            <div class="kv">R$ <?php echo number_format($totais->$key_venc ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-exclamation-triangle ki"></i>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="kpi-card" style="background:linear-gradient(135deg,#1F4E79,#2980b9)">
            <div class="kl">Total no Período</div>
            <div class="kv">R$ <?php echo number_format($totais->$key_total ?? 0, 2, ',', '.') ?></div>
            <i class="fa fa-money ki"></i>
        </div>
    </div>
</div>

<!-- Tabela -->
<div class="box" style="border-top:3px solid <?php echo $tipo==='receber'?'#1D6B3B':'#C00000' ?>">
    <div class="box-header with-border" style="background:linear-gradient(to right,<?php echo $tipo==='receber'?'rgba(29,107,59,.07)':'rgba(192,0,0,.06)'?>,transparent)">
        <h3 class="box-title" style="color:<?php echo $tipo==='receber'?'#1D6B3B':'#C00000' ?>">
            <i class="fa fa-list"></i> <?php echo count($lancamentos) ?> lançamento(s)
        </h3>
        <div class="box-tools pull-right">
            <a href="<?php echo site_url('admin/financeiro') ?>" class="btn btn-xs btn-default"><i class="fa fa-arrow-left"></i> Voltar</a>
        </div>
    </div>
    <div class="box-body no-padding">
        <?php if (empty($lancamentos)): ?>
        <div class="text-center text-muted" style="padding:40px">
            <i class="fa fa-<?php echo $tipo==='receber'?'arrow-down':'arrow-up' ?>" style="font-size:36px;opacity:.3;display:block;margin-bottom:10px"></i>
            Nenhum lançamento encontrado para os filtros selecionados.
        </div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table class="lancam-table" id="tbl-lanc">
            <thead>
                <tr>
                    <th></th>
                    <th>Lançto</th>
                    <th><?php echo $tipo==='receber'?'Categoria/Tipo':'Descrição' ?></th>
                    <th>Processo/Mês</th>
                    <th>Cliente</th>
                    <th>Conta</th>
                    <th>Vencimento</th>
                    <th class="text-right">Valor</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($lancamentos 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:4px;padding:2px 0">
                    <div style="width:4px;min-height:38px;border-radius:2px;background:<?php
                        echo $l->status==='pago' ? '#27ae60' : ($vencido ? '#C00000' : ($tipo==='receber'?'#C55A11':'#e67e22'))
                    ?>"></div>
                </td>
                <td style="white-space:nowrap"><small class="text-muted"><?php echo date('d/m/y', strtotime($l->created_at)) ?></small></td>
                <td><?php echo htmlspecialchars($l->categoria ?? $l->descricao ?? '—') ?></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><small><?php echo htmlspecialchars($l->conta_nome ?? '—') ?></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'?($tipo==='receber'?'#1D6B3B':'#888'):($vencido?'#C00000':'#333') ?>">
                        R$ <?php echo number_format($l->valor, 2, ',', '.') ?>
                    </strong>
                </td>
                <td>
                    <?php if ($l->status === 'pago'): ?>
                        <span class="badge-status badge-pago"><?php echo $tipo==='receber'?'Recebido':'Pago' ?></span>
                    <?php elseif ($l->status === 'cancelado'): ?>
                        <span class="badge-status badge-cancelado">Cancelado</span>
                    <?php elseif ($vencido): ?>
                        <span class="badge-status badge-vencido">Vencido</span>
                    <?php else: ?>
                        <span class="badge-status badge-pendente">Pendente</span>
                    <?php endif; ?>
                </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>
                    <?php if ($tipo === 'receber'): ?>
                    <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>
                    <?php endif; ?>
                    <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>
            <tfoot>
                <tr>
                    <td colspan="7" class="text-right text-muted" style="font-size:12px">TOTAL DO PERÍODO:</td>
                    <td class="text-right" style="color:<?php echo $tipo==='receber'?'#1D6B3B':'#C00000' ?>">
                        <strong>R$ <?php echo number_format(array_sum(array_column((array)$lancamentos, 'valor')), 2, ',', '.') ?></strong>
                    </td>
                    <td colspan="2"></td>
                </tr>
            </tfoot>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>

</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);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</button>
                </div>
            </form>
        </div>
    </div>
</div>

<link href="<?php echo base_url('assets/css/datatables/dataTables.bootstrap.css') ?>" rel="stylesheet">
<script src="<?php echo base_url('assets/js/plugins/datatables/jquery.dataTables.js') ?>"></script>
<script src="<?php echo base_url('assets/js/plugins/datatables/dataTables.bootstrap.js') ?>"></script>
<script>
$(function () {
    $('#tbl-lanc').dataTable({
        "order": [[6, 'asc']],
        "pageLength": 50,
        "language": { "url": "//cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json" }
    });
    $('.btn-baixar').on('click', function () {
        $('#form-baixar').attr('action', '<?php echo site_url('admin/financeiro/baixar/') ?>' + $(this).data('id'));
        $('#modal-baixar').modal('show');
    });
});
</script>
