<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<link href="<?php echo base_url('assets/css/datatables/dataTables.bootstrap.css') ?>" rel="stylesheet">
<style>
.kpi-card{background:#fff;border:1px solid #e2e6ea;border-radius:10px;padding:14px 16px;border-left:4px solid #1e3a5f;position:relative;overflow:hidden;margin-bottom:14px}
.kpi-card .kv{font-size:24px;font-weight:700;color:#1e3a5f;line-height:1}
.kpi-card .kl{font-size:10px;color:#888;text-transform:uppercase;letter-spacing:.5px;margin-top:4px}
.kpi-card .ks{font-size:11px;color:#aaa;margin-top:2px}
.kpi-card .ki{position:absolute;right:12px;top:50%;transform:translateY(-50%);font-size:38px;opacity:.06;color:#1e3a5f}
.kpi-card.g{border-left-color:#2e7d32}.kpi-card.g .kv{color:#2e7d32}
.kpi-card.r{border-left-color:#c0392b}.kpi-card.r .kv{color:#c0392b}
.kpi-card.o{border-left-color:#d35400}.kpi-card.o .kv{color:#d35400}
.devedor-type{display:inline-block;padding:2px 7px;border-radius:4px;font-size:10px;font-weight:700}
.type-pj{background:#e3f2fd;color:#1565c0}
.type-pf{background:#f3e5f5;color:#6a1b9a}
.api-badge{display:inline-block;padding:1px 6px;border-radius:4px;font-size:9.5px;font-weight:700;background:#e8f5e9;color:#2e7d32;margin-left:4px}
.alerta-item{padding:9px 14px;border-bottom:1px solid #f0f2f5;display:flex;align-items:center;gap:10px}
.alerta-item:last-child{border-bottom:none}
.alerta-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
</style>

<section class="content-header">
    <h1><i class="fa fa-search"></i> Central de Busca Patrimonial</h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li class="active">Busca Patrimonial</li>
    </ol>
</section>

<section class="content">

<?php if(isset($kpis)): ?>
<div class="row">
    <div class="col-md-2 col-sm-4 col-xs-6"><div class="kpi-card"><div class="kv"><?php echo $kpis->total_expedientes ?></div><div class="kl">Execuções Ativas</div><i class="fa fa-folder-open ki"></i></div></div>
    <div class="col-md-2 col-sm-4 col-xs-6"><div class="kpi-card o"><div class="kv"><?php echo $kpis->dilig_vencendo ?></div><div class="kl">Vencendo em 30 dias</div><i class="fa fa-clock-o ki"></i></div></div>
    <div class="col-md-2 col-sm-4 col-xs-6"><div class="kpi-card r"><div class="kv"><?php echo $kpis->dilig_vencidas ?></div><div class="kl">Diligências Vencidas</div><i class="fa fa-exclamation-circle ki"></i></div></div>
    <div class="col-md-2 col-sm-4 col-xs-6"><div class="kpi-card r"><div class="kv"><?php echo $kpis->sem_bens ?></div><div class="kl">Sem Bens Localizados</div><i class="fa fa-times-circle ki"></i></div></div>
    <div class="col-md-2 col-sm-4 col-xs-6"><div class="kpi-card g"><div class="kv"><?php echo $kpis->com_bens ?></div><div class="kl">Com Bens Encontrados</div><i class="fa fa-check-circle ki"></i></div></div>
    <div class="col-md-2 col-sm-4 col-xs-6"><div class="kpi-card g"><div class="kv">R$ <?php echo number_format(($kpis->valor_encontrado??0)/1000,1) ?>k</div><div class="kl">Total em Ativos</div><div class="ks">de R$ <?php echo number_format(($kpis->valor_execucao??0)/1000,1) ?>k executados</div><i class="fa fa-money ki"></i></div></div>
</div>
<?php endif; ?>

<div class="row">
<div class="col-md-9">
    <div class="box box-default" style="margin-bottom:10px">
        <div class="box-body" style="padding:10px 14px">
            <form method="get" class="form-inline">
                <input type="text" name="q" value="<?php echo htmlspecialchars($filtros['busca']??'') ?>" class="form-control input-sm" placeholder="Buscar devedor..." style="width:180px;margin-right:6px">
                <select name="status" class="form-control input-sm" style="margin-right:6px">
                    <option value="">Todos</option>
                    <option value="ativo" <?php echo ($filtros['status']??'')==='ativo'?'selected':'' ?>>Ativo</option>
                    <option value="suspenso" <?php echo ($filtros['status']??'')==='suspenso'?'selected':'' ?>>Suspenso</option>
                    <option value="encerrado" <?php echo ($filtros['status']??'')==='encerrado'?'selected':'' ?>>Encerrado</option>
                </select>
                <select name="tipo" class="form-control input-sm" style="margin-right:6px">
                    <option value="">PF + PJ</option>
                    <option value="pf" <?php echo ($filtros['devedor_tipo']??'')==='pf'?'selected':'' ?>>Pessoa Física</option>
                    <option value="pj" <?php echo ($filtros['devedor_tipo']??'')==='pj'?'selected':'' ?>>Pessoa Jurídica</option>
                </select>
                <button type="submit" class="btn btn-default btn-sm"><i class="fa fa-search"></i></button>
                <a href="<?php echo site_url('admin/patrimonio') ?>" class="btn btn-default btn-sm">Limpar</a>
                <a href="<?php echo site_url('admin/patrimonio/add') ?>" class="btn btn-primary btn-sm" style="margin-left:10px"><i class="fa fa-plus"></i> Novo Expediente</a>
            </form>
        </div>
    </div>

    <div class="box box-primary">
        <div class="box-header with-border"><h3 class="box-title"><i class="fa fa-search"></i> Expedientes</h3></div>
        <div class="box-body no-padding">
            <table id="tbl-pat" class="table table-hover" style="margin:0">
                <thead>
                    <tr>
                        <th>Devedor</th>
                        <th>Processo</th>
                        <th>Valor Execução</th>
                        <th>Diligências</th>
                        <th>Bens</th>
                        <th style="width:90px">Ações</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach($expedientes as $exp):
                    $has_alerta = ($exp->dilig_vencendo > 0 || $exp->dilig_vencidas > 0);
                ?>
                <tr>
                    <td>
                        <strong><?php echo htmlspecialchars($exp->devedor_nome) ?></strong>
                        <span class="devedor-type type-<?php echo $exp->devedor_tipo ?>"><?php echo strtoupper($exp->devedor_tipo) ?></span>
                        <?php if($exp->devedor_tipo==='pj'): ?><span class="api-badge">API</span><?php endif; ?>
                        <br><small class="text-muted"><?php echo htmlspecialchars($exp->devedor_doc) ?></small>
                    </td>
                    <td>
                        <a href="<?php echo site_url('admin/cases/view_case/'.$exp->case_id) ?>" style="font-size:11px;font-family:monospace"><?php echo $exp->case_no ?></a>
                        <br><small class="text-muted"><?php echo htmlspecialchars(mb_substr($exp->case_title,0,30)) ?></small>
                    </td>
                    <td>
                        <strong>R$ <?php echo number_format($exp->valor_execucao,2,',','.') ?></strong>
                        <?php if($exp->valor_encontrado>0): ?>
                        <br><small class="text-success"><i class="fa fa-check-circle"></i> R$ <?php echo number_format($exp->valor_encontrado,2,',','.') ?> encontrado</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php echo $exp->total_diligencias ?> diligência(s)
                        <?php if($exp->dilig_vencidas>0): ?>
                        <br><small class="text-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $exp->dilig_vencidas ?> vencida(s)</small>
                        <?php elseif($exp->dilig_vencendo>0): ?>
                        <br><small class="text-warning"><i class="fa fa-clock-o"></i> <?php echo $exp->dilig_vencendo ?> vencendo</small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if($exp->total_bens>0): ?>
                        <span class="label label-success"><?php echo $exp->total_bens ?> bem(ns)</span>
                        <?php else: ?>
                        <span class="label label-default">Nenhum</span>
                        <?php endif; ?>
                    </td>
                    <td style="white-space:nowrap">
                        <a href="<?php echo site_url('admin/patrimonio/view/'.$exp->id) ?>" class="btn btn-xs btn-primary" title="Ver"><i class="fa fa-eye"></i></a>
                        <?php if($has_alerta): ?><a href="<?php echo site_url('admin/patrimonio/view/'.$exp->id) ?>" class="btn btn-xs btn-warning" title="Alerta"><i class="fa fa-bell"></i></a><?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="col-md-3">
    <div class="box" style="border-top:3px solid #c0392b">
        <div class="box-header with-border"><h3 class="box-title"><i class="fa fa-bell text-danger"></i> Alertas de Renovação</h3></div>
        <div class="box-body no-padding">
            <?php if(empty($alertas)): ?>
            <div style="padding:20px;text-align:center;color:#aaa;font-size:12px">
                <i class="fa fa-check-circle" style="font-size:28px;color:#2e7d32;display:block;margin-bottom:8px"></i>Nenhuma diligência vencendo em 30 dias
            </div>
            <?php else: foreach($alertas as $a):
                $cor = $a->dias_restantes<0?'#c0392b':($a->dias_restantes<=7?'#d35400':'#f39c12');
            ?>
            <div class="alerta-item">
                <div class="alerta-dot" style="background:<?php echo $cor ?>"></div>
                <div style="flex:1;min-width:0">
                    <div style="font-size:12px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo htmlspecialchars($a->devedor_nome) ?></div>
                    <div style="font-size:11px;color:#666"><?php echo strtoupper($a->sistema) ?> · <?php echo date('d/m/Y',strtotime($a->data_vencimento)) ?></div>
                    <div style="font-size:11px;font-weight:600;color:<?php echo $cor ?>">
                        <?php if($a->dias_restantes<0): ?>Vencida há <?php echo abs($a->dias_restantes) ?> dias
                        <?php else: ?>Vence em <?php echo $a->dias_restantes ?> dias<?php endif; ?>
                    </div>
                </div>
                <a href="<?php echo site_url('admin/patrimonio/view/'.$a->expediente_id) ?>" class="btn btn-xs btn-default"><i class="fa fa-eye"></i></a>
            </div>
            <?php endforeach; endif; ?>
        </div>
    </div>

    <div class="box" style="border-top:3px solid #2e7d32">
        <div class="box-header with-border"><h3 class="box-title"><i class="fa fa-plug"></i> Saúde das APIs</h3></div>
        <div class="box-body" style="padding:14px;text-align:center">
            <p style="font-size:12px;color:#888;margin-bottom:10px">
                Execute um teste real para ver o status atual de cada API integrada.
            </p>
            <a href="<?php echo site_url('admin/patrimonio/diagnostico') ?>" class="btn btn-primary btn-sm btn-block" style="margin-bottom:6px">
                <i class="fa fa-heartbeat"></i> Diagnóstico de APIs
            </a>
            <a href="<?php echo site_url('admin/patrimonio/configuracoes') ?>" class="btn btn-default btn-sm btn-block">
                <i class="fa fa-key"></i> Configurar Tokens
            </a>
        </div>
    </div>
</div>
</div>
</section>

<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-pat').dataTable({order:[[0,'asc']],pageLength:20,language:{url:'//cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json'}});
});
</script>
