<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
.content-header {
    background:linear-gradient(135deg,#0f2a4a,#1a659e);
    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:linear-gradient(135deg,#1a659e,#0f2a4a);
    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; text-decoration:none; line-height:28px; }

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

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

.bpo-table { width:100%; border-collapse:collapse; }
.bpo-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; }
.bpo-table tbody tr { border-bottom:1px solid #f0f0f0; transition:background .1s; }
.bpo-table tbody tr:hover { background:#f0f6ff; }
.bpo-table tbody td { padding:10px 12px; font-size:13px; vertical-align:middle; }
.bpo-table tfoot td { padding:10px 12px; font-weight:700; background:#f5f7fa; border-top:2px solid #e0e0e0; }
.bpo-table tbody tr.row-vencido { border-left:3px solid #C00000; }

.badge-status { display:inline-block; padding:3px 9px; border-radius:20px; font-size:11px; font-weight:600; }
.badge-danger  { background:#ffebee; color:#C00000; }
.badge-warning { background:#fff8e1; color:#C55A11; }
.badge-success { background:#e8f5e9; color:#1D6B3B; }

.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; float:right; margin-top:-20px; }
</style>

<section class="content-header">
    <h1><i class="fa fa-university"></i> BPO Financeiro <small>Gestão Financeira Centralizada</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">BPO Financeiro</li>
    </ol>
</section>

<!-- Filtros -->
<form method="get" action="<?php echo site_url('admin/financeiro/bpo') ?>">
<div class="filter-bar">
    <label>Cliente</label>
    <select name="client_id" class="form-control" style="width:180px">
        <option value="">Todos</option>
        <?php foreach ($clientes as $c): ?>
        <option value="<?php echo $c->id ?>" <?php echo $this->input->get('client_id') == $c->id ? 'selected' : '' ?>>
            <?php echo htmlspecialchars($c->name) ?>
        </option>
        <?php endforeach; ?>
    </select>
    <label>De</label>
    <input type="date" name="data_ini" class="form-control" style="width:130px" value="<?php echo $this->input->get('data_ini') ?: date('Y-m-01') ?>">
    <label>Até</label>
    <input type="date" name="data_fim" class="form-control" style="width:130px" value="<?php echo $this->input->get('data_fim') ?: date('Y-m-t') ?>">
    <label>Status</label>
    <select name="status" class="form-control" style="width:120px">
        <option value="">Todos</option>
        <option value="pendente" <?php echo $this->input->get('status') === 'pendente' ? 'selected' : '' ?>>Pendente</option>
        <option value="pago"     <?php echo $this->input->get('status') === 'pago'     ? 'selected' : '' ?>>Pago</option>
    </select>
    <button type="submit" class="btn-filtrar"><i class="fa fa-search"></i> Filtrar</button>
    <a href="<?php echo site_url('admin/financeiro/bpo') ?>" class="btn-limpar">Limpar</a>
    <div style="margin-left:auto;display:flex;gap:6px">
        <a href="<?php echo site_url('admin/financeiro/add_honorario') ?>" class="btn btn-sm btn-success" style="border-radius:6px;height:30px;line-height:18px;font-size:12px">
            <i class="fa fa-plus"></i> Registrar Honorário
        </a>
        <a href="<?php echo site_url('admin/financeiro/bpo_pdf') ?>" class="btn btn-sm btn-danger" style="border-radius:6px;height:30px;line-height:18px;font-size:12px">
            <i class="fa fa-file-pdf-o"></i> Exportar PDF
        </a>
    </div>
</div>
</form>

<section class="content">

<?php if (!empty($alertas)): ?>
<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((array)$alertas) ?> honorário(s) VENCIDO(s)</strong> sem baixa.
    <a href="#sec-vencidos" class="btn btn-danger btn-xs pull-right">Ver Agora</a>
</div>
<?php endif; ?>

<!-- KPIs -->
<?php
$grand_total    = array_sum(array_column((array)$resumo_bpo, 'total_receber'));
$grand_recebido = array_sum(array_column((array)$resumo_bpo, 'total_recebido'));
$grand_pendente = array_sum(array_column((array)$resumo_bpo, 'total_pendente'));
$grand_vencido  = array_sum(array_column((array)$resumo_bpo, 'total_vencido'));
?>
<div class="row">
    <div class="col-md-3 col-sm-6">
        <div class="kpi-card" style="background:linear-gradient(135deg,#1a659e,#2980b9)">
            <div class="kl">Total Honorários</div>
            <div class="kv">R$ <?php echo number_format($grand_total, 2, ',', '.') ?></div>
            <i class="fa fa-money ki"></i>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="kpi-card" style="background:linear-gradient(135deg,#1D6B3B,#27ae60)">
            <div class="kl">Recebido</div>
            <div class="kv">R$ <?php echo number_format($grand_recebido, 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,#C55A11,#e67e22)">
            <div class="kl">Pendente</div>
            <div class="kv">R$ <?php echo number_format($grand_pendente, 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:linear-gradient(135deg,#C00000,#e74c3c)">
            <div class="kl">Vencido</div>
            <div class="kv">R$ <?php echo number_format($grand_vencido, 2, ',', '.') ?></div>
            <i class="fa fa-exclamation-triangle ki"></i>
        </div>
    </div>
</div>

<!-- Posição por cliente -->
<div class="section-divider"><i class="fa fa-users" style="margin-right:6px"></i> Posição Financeira por Cliente</div>
<div class="box" style="border-top:3px solid #1a659e">
    <div class="box-header with-border" style="background:linear-gradient(to right,rgba(26,101,158,.08),transparent)">
        <h3 class="box-title" style="color:#1a659e"><i class="fa fa-users"></i> <?php echo count((array)$resumo_bpo) ?> cliente(s)</h3>
    </div>
    <div class="box-body no-padding">
        <?php if (empty($resumo_bpo)): ?>
        <div class="text-center text-muted" style="padding:40px">
            <i class="fa fa-university" style="font-size:36px;opacity:.3;display:block;margin-bottom:10px"></i>
            Nenhum dado encontrado para os filtros selecionados.
        </div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table class="bpo-table" id="tbl-bpo">
            <thead>
                <tr>
                    <th>Cliente</th>
                    <th class="text-right">Total (R$)</th>
                    <th class="text-right">Recebido (R$)</th>
                    <th class="text-right">Pendente (R$)</th>
                    <th class="text-right">Vencido (R$)</th>
                    <th class="text-center">Situação</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($resumo_bpo as $r):
                $venc  = (float)$r->total_vencido;
                $pend  = (float)$r->total_pendente;
                $is_vencido = $venc > 0;
                $is_pendente = $pend > 0 && !$is_vencido;
            ?>
            <tr class="<?php echo $is_vencido ? 'row-vencido' : '' ?>">
                <td>
                    <strong><?php echo htmlspecialchars($r->client_nome) ?></strong>
                </td>
                <td class="text-right">R$ <?php echo number_format($r->total_receber, 2, ',', '.') ?></td>
                <td class="text-right" style="color:#1D6B3B;font-weight:600">R$ <?php echo number_format($r->total_recebido, 2, ',', '.') ?></td>
                <td class="text-right" style="color:#C55A11">R$ <?php echo number_format($r->total_pendente, 2, ',', '.') ?></td>
                <td class="text-right">
                    <strong style="color:<?php echo $is_vencido ? '#C00000' : '#aaa' ?>">
                        R$ <?php echo number_format($r->total_vencido, 2, ',', '.') ?>
                    </strong>
                </td>
                <td class="text-center">
                    <?php if ($is_vencido): ?>
                        <span class="badge-status badge-danger"><i class="fa fa-times-circle"></i> VENCIDO</span>
                    <?php elseif ($is_pendente): ?>
                        <span class="badge-status badge-warning"><i class="fa fa-clock-o"></i> Pendente</span>
                    <?php else: ?>
                        <span class="badge-status badge-success"><i class="fa fa-check-circle"></i> Em dia</span>
                    <?php endif; ?>
                </td>
                <td style="white-space:nowrap">
                    <a href="<?php echo site_url('admin/financeiro/bpo_cliente/' . $r->client_id) ?>" class="btn btn-info btn-xs">
                        <i class="fa fa-folder-open"></i> Ficha
                    </a>
                    <a href="<?php echo site_url('admin/financeiro/bpo_pdf/' . $r->client_id) ?>" class="btn btn-danger btn-xs" title="PDF">
                        <i class="fa fa-file-pdf-o"></i>
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td>TOTAIS</td>
                    <td class="text-right">R$ <?php echo number_format($grand_total,    2, ',', '.') ?></td>
                    <td class="text-right" style="color:#1D6B3B">R$ <?php echo number_format($grand_recebido, 2, ',', '.') ?></td>
                    <td class="text-right" style="color:#C55A11">R$ <?php echo number_format($grand_pendente, 2, ',', '.') ?></td>
                    <td class="text-right" style="color:#C00000">R$ <?php echo number_format($grand_vencido,  2, ',', '.') ?></td>
                    <td colspan="2"></td>
                </tr>
            </tfoot>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Alertas vencidos -->
<?php if (!empty($alertas)): ?>
<div class="section-divider" id="sec-vencidos"><i class="fa fa-exclamation-circle" style="margin-right:6px;color:#C00000"></i> Honorários 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,.07),transparent)">
        <h3 class="box-title text-danger"><i class="fa fa-exclamation-circle"></i> <?php echo count((array)$alertas) ?> honorário(s) aguardando baixa</h3>
    </div>
    <div class="box-body no-padding">
        <table class="bpo-table">
            <thead>
                <tr>
                    <th>Cliente</th>
                    <th>Descrição</th>
                    <th>Processo</th>
                    <th>Vencimento</th>
                    <th>Atraso</th>
                    <th class="text-right">Valor</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($alertas as $a):
                $dias = (int)floor((time() - strtotime($a->vencimento)) / 86400);
            ?>
            <tr class="row-vencido">
                <td><strong><?php echo htmlspecialchars($a->client_nome ?? '—') ?></strong></td>
                <td><?php echo htmlspecialchars($a->descricao) ?></td>
                <td><small><?php echo htmlspecialchars($a->case_no ?? '—') ?></small></td>
                <td class="text-danger" style="white-space:nowrap">
                    <i class="fa fa-calendar-times-o"></i> <?php echo date('d/m/Y', strtotime($a->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($a->valor, 2, ',', '.') ?></strong>
                </td>
                <td style="white-space:nowrap">
                    <button class="btn btn-success btn-xs btn-baixar" data-id="<?php echo $a->id ?>">
                        <i class="fa fa-check"></i> Baixar
                    </button>
                    <a href="<?php echo site_url('admin/financeiro/recibo/' . $a->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/' . $a->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);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-bpo').dataTable({
        "order": [[4, 'desc']],
        "pageLength": 25,
        "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>
