<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
.nav-tabs-custom{border-radius:10px;box-shadow:0 1px 6px rgba(0,0,0,.07)}
.nav-tabs-custom>.nav-tabs{background:#f8f9fb;border-bottom:1px solid #e2e6ea}
.nav-tabs-custom>.nav-tabs>li>a{border:none;border-radius:0;color:#666;padding:11px 16px;font-size:13px}
.nav-tabs-custom>.nav-tabs>li.active>a{color:#1e3a5f;font-weight:600;border-bottom:3px solid #1e3a5f;background:#fff}
.nav-tabs-custom>.tab-content{background:#fff;padding:16px;border-radius:0 0 10px 10px}
.form-group label{font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:.5px;margin-bottom:5px;display:block}
.sistema-badge{display:inline-block;padding:3px 9px;border-radius:5px;font-size:11px;font-weight:700;text-transform:uppercase}
.s-sisbajud{background:#e3f2fd;color:#1565c0}
.s-renajud{background:#e8f5e9;color:#2e7d32}
.s-infojud{background:#fff3e0;color:#e65100}
.s-sniper{background:#fce4ec;color:#880e4f}
.s-cnib{background:#f3e5f5;color:#6a1b9a}
.s-censec{background:#e0f2f1;color:#00695c}
.s-criptojud{background:#e8eaf6;color:#3949ab}
.s-manual{background:#f5f5f5;color:#616161}
.situacao-vencida{color:#c0392b;font-weight:600}
.situacao-vencendo{color:#d35400;font-weight:600}
.situacao-vigente{color:#2e7d32;font-weight:600}
.bem-card{background:#f8f9fb;border:1px solid #e2e6ea;border-radius:8px;padding:12px;margin-bottom:8px;display:flex;align-items:flex-start;gap:12px}
.bem-icon{width:36px;height:36px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
.check-item{display:flex;align-items:center;gap:10px;padding:9px 14px;border-bottom:1px solid #f0f2f5}
.check-item:last-child{border-bottom:none}
.check-circle{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;flex-shrink:0;cursor:pointer;border:2px solid #e2e6ea}
.check-circle.ok{background:#2e7d32;border-color:#2e7d32;color:#fff}
.check-circle.no{background:#f8f9fb;border-color:#ddd;color:#aaa}
.prog-wrap{background:#e9ecef;border-radius:4px;height:8px;overflow:hidden}
.prog-bar{height:100%;border-radius:4px;background:#1e3a5f;transition:width .3s}
.pet-row{padding:10px 14px;border-bottom:1px solid #f0f2f5;display:flex;align-items:center;justify-content:space-between;gap:12px}
.pet-row:last-child{border-bottom:none}
.modal-header-dark{background:linear-gradient(135deg,#1e3a5f,#2e75b6);border-radius:6px 6px 0 0}
.modal-header-dark .modal-title{color:#fff;font-weight:700}
.modal-header-dark .close{color:#fff;opacity:.8}
</style>

<section class="content-header">
    <h1>
        <i class="fa fa-search"></i> <?php echo htmlspecialchars($exp->devedor_nome) ?>
        <small><?php echo $exp->case_no ?></small>
    </h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li><a href="<?php echo site_url('admin/patrimonio') ?>">Busca Patrimonial</a></li>
        <li class="active"><?php echo htmlspecialchars($exp->devedor_nome) ?></li>
    </ol>
</section>

<section class="content">
<div class="row">

<!-- Coluna principal -->
<div class="col-md-8">

    <!-- Resumo do expediente -->
    <div class="box box-primary" style="margin-bottom:14px">
        <div class="box-body" style="padding:14px 16px">
            <div class="row">
                <div class="col-md-3"><small class="text-muted" style="display:block;text-transform:uppercase;font-size:10px;font-weight:700">Devedor</small><strong><?php echo htmlspecialchars($exp->devedor_nome) ?></strong><br><small><?php echo htmlspecialchars($exp->devedor_doc) ?></small></div>
                <div class="col-md-3"><small class="text-muted" style="display:block;text-transform:uppercase;font-size:10px;font-weight:700">Processo</small><a href="<?php echo site_url('admin/cases/view_case/'.$exp->case_id) ?>" style="font-family:monospace"><?php echo $exp->case_no ?></a><br><small><?php echo htmlspecialchars(mb_substr($exp->case_title,0,30)) ?></small></div>
                <div class="col-md-3"><small class="text-muted" style="display:block;text-transform:uppercase;font-size:10px;font-weight:700">Valor Executado</small><strong style="color:#c0392b">R$ <?php echo number_format($exp->valor_execucao,2,',','.') ?></strong></div>
                <div class="col-md-3"><small class="text-muted" style="display:block;text-transform:uppercase;font-size:10px;font-weight:700">Bens Encontrados</small><strong style="color:#2e7d32">R$ <?php echo number_format($exp->valor_encontrado,2,',','.') ?></strong></div>
            </div>
        </div>
    </div>

    <!-- Abas -->
    <div class="nav-tabs-custom">
        <ul class="nav nav-tabs">
            <li class="active"><a href="#tab-dilig" data-toggle="tab"><i class="fa fa-gavel"></i> Diligências (<?php echo count($diligencias) ?>)</a></li>
            <li><a href="#tab-bens" data-toggle="tab"><i class="fa fa-home"></i> Bens (<?php echo count($bens) ?>)</a></li>
            <li><a href="#tab-check" data-toggle="tab"><i class="fa fa-check-square-o"></i> Checklist <span class="label label-default" style="font-size:10px"><?php echo $pct_check ?>%</span></a></li>
            <li><a href="#tab-api" data-toggle="tab"><i class="fa fa-plug"></i> Consulta API</a></li>
            <li><a href="#tab-pet" data-toggle="tab"><i class="fa fa-file-text-o"></i> Petições (<?php echo count($peticoes) ?>)</a></li>
        </ul>
        <div class="tab-content">

            <!-- ── TAB DILIGÊNCIAS ── -->
            <div class="tab-pane active" id="tab-dilig">
                <div class="pull-right" style="margin-bottom:12px">
                    <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#modal-nova-dilig"><i class="fa fa-plus"></i> Nova Diligência</button>
                </div>
                <div class="clearfix"></div>
                <?php if(empty($diligencias)): ?>
                <div class="text-center text-muted" style="padding:30px"><i class="fa fa-search" style="font-size:36px;opacity:.2;display:block;margin-bottom:8px"></i>Nenhuma diligência registrada ainda.</div>
                <?php else: ?>
                <table class="table table-hover" style="margin:0">
                    <thead><tr><th>Sistema</th><th>Requerimento</th><th>Validade</th><th>Vencimento</th><th>Resultado</th><th style="width:110px">Ações</th></tr></thead>
                    <tbody>
                    <?php foreach($diligencias as $d): ?>
                    <tr>
                        <td><span class="sistema-badge s-<?php echo $d->sistema ?>"><?php echo strtoupper($d->sistema) ?></span></td>
                        <td><?php echo date('d/m/Y',strtotime($d->data_requerimento)) ?><br><small class="text-muted"><?php echo htmlspecialchars($d->num_peticao??'') ?></small></td>
                        <td><?php echo $d->validade_meses ?> meses</td>
                        <td>
                            <span class="situacao-<?php echo $d->situacao_prazo ?>">
                                <?php echo date('d/m/Y',strtotime($d->data_vencimento)) ?><br>
                                <small>
                                <?php if($d->situacao_prazo==='vencida'): ?><i class="fa fa-exclamation-circle"></i> Vencida há <?php echo abs($d->dias_restantes) ?> dias
                                <?php elseif($d->situacao_prazo==='vencendo'): ?><i class="fa fa-clock-o"></i> <?php echo $d->dias_restantes ?> dias restantes
                                <?php else: ?>Vigente (<?php echo $d->dias_restantes ?> dias)
                                <?php endif; ?>
                                </small>
                            </span>
                        </td>
                        <td>
                            <?php if($d->resultado==='positivo'): ?><span class="label label-success">Positivo</span>
                            <?php elseif($d->resultado==='negativo'): ?><span class="label label-default">Negativo</span>
                            <?php else: ?><span class="label label-warning">Aguardando</span><?php endif; ?>
                            <?php if($d->data_resultado): ?><br><small><?php echo date('d/m/Y',strtotime($d->data_resultado)) ?></small><?php endif; ?>
                        </td>
                        <td style="white-space:nowrap">
                            <button class="btn btn-xs btn-warning" data-toggle="modal" data-target="#modal-resultado-<?php echo $d->id ?>"><i class="fa fa-edit"></i></button>
                            <button class="btn btn-xs btn-success" onclick="gerarPeticaoSistema('<?php echo $d->sistema ?>')" title="Gerar petição"><i class="fa fa-file-text-o"></i></button>
                        </td>
                    </tr>
                    <!-- Modal resultado -->
                    <div class="modal fade" id="modal-resultado-<?php echo $d->id ?>" tabindex="-1">
                        <div class="modal-dialog"><div class="modal-content" style="border-radius:10px;overflow:hidden">
                            <div class="modal-header modal-header-dark"><h4 class="modal-title"><i class="fa fa-edit"></i> Atualizar Resultado — <?php echo strtoupper($d->sistema) ?></h4><button class="close" data-dismiss="modal">&times;</button></div>
                            <form method="post" action="<?php echo site_url('admin/patrimonio/diligencia_resultado/'.$d->id) ?>">
                            <div class="modal-body">
                                <div class="form-group"><label>Resultado</label>
                                    <select name="resultado" class="form-control">
                                        <option value="aguardando" <?php echo $d->resultado==='aguardando'?'selected':'' ?>>Aguardando</option>
                                        <option value="positivo" <?php echo $d->resultado==='positivo'?'selected':'' ?>>Positivo — bens encontrados</option>
                                        <option value="negativo" <?php echo $d->resultado==='negativo'?'selected':'' ?>>Negativo — sem bens</option>
                                    </select>
                                </div>
                                <div class="form-group"><label>Data do Resultado</label><input type="date" name="data_resultado" value="<?php echo $d->data_resultado??'' ?>" class="form-control"></div>
                                <div class="form-group"><label>Observações</label><textarea name="obs" class="form-control" rows="2"><?php echo htmlspecialchars($d->obs??'') ?></textarea></div>
                            </div>
                            <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button><button type="submit" class="btn btn-primary">Salvar</button></div>
                            </form>
                        </div></div>
                    </div>
                    <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <!-- ── TAB BENS ── -->
            <div class="tab-pane" id="tab-bens">
                <div class="pull-right" style="margin-bottom:12px">
                    <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#modal-novo-bem"><i class="fa fa-plus"></i> Registrar Bem</button>
                </div>
                <div class="clearfix"></div>
                <?php if(empty($bens)): ?>
                <div class="text-center text-muted" style="padding:30px"><i class="fa fa-home" style="font-size:36px;opacity:.2;display:block;margin-bottom:8px"></i>Nenhum bem encontrado ainda.</div>
                <?php else:
                    $tipo_icons=['conta_bancaria'=>'🏦','veiculo'=>'🚗','imovel'=>'🏠','quota_societaria'=>'🏢','credito'=>'💰','criptoativo'=>'₿','outro'=>'📦'];
                    $tipo_colors=['conta_bancaria'=>'#e3f2fd','veiculo'=>'#e8f5e9','imovel'=>'#fff3e0','quota_societaria'=>'#f3e5f5','credito'=>'#e8f5e9','criptoativo'=>'#e8eaf6','outro'=>'#f5f5f5'];
                    foreach($bens as $b): ?>
                <div class="bem-card">
                    <div class="bem-icon" style="background:<?php echo $tipo_colors[$b->tipo]??'#f5f5f5' ?>"><?php echo $tipo_icons[$b->tipo]??'📦' ?></div>
                    <div style="flex:1">
                        <strong><?php echo htmlspecialchars($b->descricao) ?></strong>
                        <?php if(!empty($b->instituicao)): ?><small class="text-muted"> — <?php echo htmlspecialchars($b->instituicao) ?></small><?php endif; ?>
                        <br>
                        <?php if($b->status==='bloqueado'||$b->status==='penhorado'): ?><span class="label label-success"><?php echo ucfirst($b->status) ?></span>
                        <?php elseif($b->status==='identificado'): ?><span class="label label-warning">Identificado</span>
                        <?php else: ?><span class="label label-default"><?php echo ucfirst($b->status) ?></span><?php endif; ?>
                        <?php if($b->valor_fipe>0): ?><small class="text-muted"> · FIPE: R$ <?php echo number_format($b->valor_fipe,2,',','.') ?></small><?php endif; ?>
                    </div>
                    <div style="text-align:right">
                        <strong style="color:#2e7d32;font-size:14px">R$ <?php echo number_format($b->valor_estimado,2,',','.') ?></strong>
                        <br>
                        <a href="<?php echo site_url('admin/patrimonio/bem_delete/'.$b->id) ?>" class="btn btn-xs btn-danger" onclick="return confirm('Remover bem?')" style="margin-top:4px"><i class="fa fa-trash"></i></a>
                    </div>
                </div>
                <?php endforeach; endif; ?>
                <div style="border-top:2px solid #e2e6ea;padding-top:10px;margin-top:6px;text-align:right">
                    <strong>Total: R$ <?php echo number_format($exp->valor_encontrado,2,',','.') ?></strong>
                    <span class="text-muted" style="margin-left:10px"><?php echo number_format($exp->valor_execucao>0?($exp->valor_encontrado/$exp->valor_execucao)*100:0,1) ?>% do débito</span>
                </div>
            </div>

            <!-- ── TAB CHECKLIST ── -->
            <div class="tab-pane" id="tab-check">
                <div style="margin-bottom:12px">
                    <div class="prog-wrap"><div class="prog-bar" style="width:<?php echo $pct_check ?>%"></div></div>
                    <small class="text-muted"><?php echo $pct_check ?>% das diligências extrajudiciais realizadas</small>
                </div>
                <p class="text-muted" style="font-size:12px;margin-bottom:12px">
                    <i class="fa fa-info-circle"></i> O STJ exige comprovação de esgotamento das buscas extrajudiciais antes de deferir INFOJUD e RENAJUD (REsp 1.786.608/SP). Registre todas as diligências realizadas.
                </p>
                <?php
                $tipo_labels=[
                    'serasa_spc'=>'Consulta Serasa/SPC','cnpj_socios'=>'Quadro Societário (CNPJ)','cartorio_imoveis'=>'Certidão Cartório de Imóveis',
                    'redes_sociais'=>'Busca em Redes Sociais','datajud'=>'DataJud — Outros processos','detran_manual'=>'Consulta DETRAN (manual)',
                    'receita_federal_manual'=>'Receita Federal (manual)','outro'=>'Outra diligência'
                ];
                foreach($checklist as $item): ?>
                <div class="check-item">
                    <div class="check-circle <?php echo $item->realizado?'ok':'no' ?>" onclick="toggleCheck(<?php echo $item->id ?>, this)"><?php echo $item->realizado?'✓':'○' ?></div>
                    <div style="flex:1">
                        <strong style="font-size:13px"><?php echo $tipo_labels[$item->tipo]??$item->tipo ?></strong>
                        <?php if($item->via_api): ?><span style="font-size:10px;background:#e8f5e9;color:#2e7d32;padding:1px 6px;border-radius:4px;margin-left:5px;font-weight:700">API</span><?php endif; ?>
                        <?php if(!empty($item->resultado)): ?><br><small class="text-muted"><?php echo htmlspecialchars($item->resultado) ?></small><?php endif; ?>
                        <?php if($item->data_realizacao): ?><br><small class="text-muted"><?php echo date('d/m/Y',strtotime($item->data_realizacao)) ?></small><?php endif; ?>
                    </div>
                    <button class="btn btn-xs btn-default" data-toggle="modal" data-target="#modal-check-<?php echo $item->id ?>"><i class="fa fa-edit"></i></button>
                    <!-- Modal checklist item -->
                    <div class="modal fade" id="modal-check-<?php echo $item->id ?>" tabindex="-1">
                        <div class="modal-dialog"><div class="modal-content" style="border-radius:10px;overflow:hidden">
                            <div class="modal-header modal-header-dark"><h4 class="modal-title"><?php echo $tipo_labels[$item->tipo]??$item->tipo ?></h4><button class="close" data-dismiss="modal">&times;</button></div>
                            <form method="post" action="<?php echo site_url('admin/patrimonio/checklist_update/'.$item->id) ?>">
                            <div class="modal-body">
                                <div class="form-group"><label>Realizado?</label>
                                    <select name="realizado" class="form-control">
                                        <option value="0" <?php echo !$item->realizado?'selected':'' ?>>Não</option>
                                        <option value="1" <?php echo $item->realizado?'selected':'' ?>>Sim</option>
                                    </select>
                                </div>
                                <div class="form-group"><label>Data de Realização</label><input type="date" name="data_realizacao" value="<?php echo $item->data_realizacao??'' ?>" class="form-control"></div>
                                <div class="form-group"><label>Resultado / Descrição</label><textarea name="resultado" class="form-control" rows="2"><?php echo htmlspecialchars($item->resultado??'') ?></textarea></div>
                                <div class="form-group"><label><input type="checkbox" name="via_api" value="1" <?php echo $item->via_api?'checked':'' ?>> Realizado via API do sistema</label></div>
                            </div>
                            <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button><button type="submit" class="btn btn-primary">Salvar</button></div>
                            </form>
                        </div></div>
                    </div>
                </div>
                <?php endforeach; ?>
                <div style="margin-top:14px">
                    <a href="<?php echo site_url('admin/patrimonio/relatorio_checklist/'.$exp->id) ?>" class="btn btn-default btn-sm"><i class="fa fa-file-pdf-o"></i> Gerar Relatório de Esgotamento</a>
                </div>
            </div>

            <!-- ── TAB API ── -->
            <div class="tab-pane" id="tab-api">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>CPF / CNPJ para consultar</label>
                            <input type="text" id="api-doc" value="<?php echo htmlspecialchars($exp->devedor_doc) ?>" class="form-control">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button class="btn btn-primary btn-block" id="btn-api-consultar"><i class="fa fa-search"></i> Consultar CNPJá + DataJud</button>
                        </div>
                    </div>
                </div>
                <div id="api-loading" style="display:none;text-align:center;padding:20px;color:#888"><i class="fa fa-spin fa-spinner" style="font-size:24px"></i><br>Consultando APIs...</div>
                <div id="api-res"></div>
            </div>

            <!-- ── TAB PETIÇÕES ── -->
            <div class="tab-pane" id="tab-pet">
                <form method="post" action="<?php echo site_url('admin/patrimonio/gerar_peticao/'.$exp->id) ?>" id="form-peticao">
                    <div class="form-group">
                        <label>Selecione os sistemas para a petição:</label>
                        <div class="row">
                            <?php foreach(['sisbajud'=>'SISBAJUD','renajud'=>'RENAJUD','infojud'=>'INFOJUD','sniper'=>'SNIPER','cnib'=>'CNIB','censec'=>'CENSEC','criptojud'=>'CRIPTOJUD'] as $val=>$label): ?>
                            <div class="col-md-3">
                                <label style="font-weight:normal;font-size:13px">
                                    <input type="checkbox" name="sistemas[]" value="<?php echo $val ?>"> <?php echo $label ?>
                                </label>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary btn-sm"><i class="fa fa-magic"></i> Gerar Petição Automática</button>
                </form>
                <hr>
                <?php if(empty($peticoes)): ?>
                <div class="text-center text-muted" style="padding:20px">Nenhuma petição gerada ainda.</div>
                <?php else: foreach($peticoes as $p): ?>
                <div class="pet-row">
                    <div>
                        <strong style="font-size:13px">Petição — <?php echo strtoupper(str_replace(',',', ',$p->sistemas)) ?></strong>
                        <br><small class="text-muted"><?php echo date('d/m/Y H:i',strtotime($p->created_at)) ?> · <?php echo $p->created_by_name ?></small>
                    </div>
                    <div style="display:flex;gap:6px;flex-shrink:0">
                        <?php if($p->status==='gerada'): ?><span class="label label-warning">Gerada</span>
                        <?php elseif($p->status==='protocolada'): ?><span class="label label-success">Protocolada</span>
                        <?php else: ?><span class="label label-info">Revisada</span><?php endif; ?>
                        <a href="<?php echo site_url('admin/patrimonio/peticao/'.$p->id) ?>" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> Ver</a>
                    </div>
                </div>
                <?php endforeach; endif; ?>
            </div>

        </div><!-- /tab-content -->
    </div><!-- /nav-tabs-custom -->

</div><!-- /col-md-8 -->

<!-- Painel lateral -->
<div class="col-md-4">
    <div class="box" style="border-top:3px solid #1e3a5f">
        <div class="box-header with-border"><h3 class="box-title"><i class="fa fa-bolt"></i> Ações Rápidas</h3></div>
        <div class="box-body" style="padding:10px">
            <button class="btn btn-primary btn-block btn-sm" style="margin-bottom:6px" data-toggle="modal" data-target="#modal-nova-dilig"><i class="fa fa-plus"></i> Nova Diligência</button>
            <button class="btn btn-success btn-block btn-sm" style="margin-bottom:6px" data-toggle="modal" data-target="#modal-novo-bem"><i class="fa fa-home"></i> Registrar Bem Encontrado</button>
            <button class="btn btn-info btn-block btn-sm" style="margin-bottom:6px" onclick="$('[href=\'#tab-api\']').tab('show')"><i class="fa fa-plug"></i> Consultar APIs</button>
            <a href="<?php echo site_url('admin/patrimonio/arsenal/'.$exp->id) ?>" class="btn btn-warning btn-block btn-sm" style="margin-bottom:6px"><i class="fa fa-binoculars"></i> Arsenal de Investigação</a>
            <a href="<?php echo site_url('admin/patrimonio/dossie_ia/'.$exp->id) ?>" class="btn btn-danger btn-block btn-sm" style="margin-bottom:6px;background:#7b1fa2;border-color:#6a1b9a"><i class="fa fa-robot"></i> Dossiê com IA</a>
            <a href="<?php echo site_url('admin/patrimonio/veiculos/'.$exp->id) ?>" class="btn btn-default btn-block btn-sm" style="margin-bottom:6px"><i class="fa fa-car"></i> FIPE & RENAJUD</a>
            <a href="<?php echo site_url('admin/patrimonio/diligencias_externas/'.$exp->id) ?>" class="btn btn-default btn-block btn-sm" style="margin-bottom:6px"><i class="fa fa-search-plus"></i> Diligências Externas</a>
            <button class="btn btn-default btn-block btn-sm" onclick="$('[href=\'#tab-pet\']').tab('show')"><i class="fa fa-file-text-o"></i> Gerar Petição</button>
        </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-bar-chart"></i> Progresso</h3></div>
        <div class="box-body" style="padding:12px 14px">
            <div style="font-size:12px;color:#888;margin-bottom:4px">Valor recuperado vs executado</div>
            <div class="prog-wrap" style="height:10px;margin-bottom:8px">
                <div class="prog-bar" style="width:<?php echo min(100,($exp->valor_execucao>0?($exp->valor_encontrado/$exp->valor_execucao)*100:0)) ?>%;background:#2e7d32"></div>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:12px">
                <span class="text-success">R$ <?php echo number_format($exp->valor_encontrado,2,',','.') ?></span>
                <span class="text-danger">R$ <?php echo number_format($exp->valor_execucao,2,',','.') ?></span>
            </div>
            <hr style="margin:10px 0">
            <div style="font-size:12px;color:#888;margin-bottom:4px">Checklist extrajudicial</div>
            <div class="prog-wrap" style="margin-bottom:4px"><div class="prog-bar" style="width:<?php echo $pct_check ?>%"></div></div>
            <small class="text-muted"><?php echo $pct_check ?>% completo</small>
        </div>
    </div>

    <?php if(!empty($exp->obs)): ?>
    <div class="box" style="border-top:3px solid #888">
        <div class="box-header with-border"><h3 class="box-title"><i class="fa fa-sticky-note-o"></i> Observações</h3></div>
        <div class="box-body"><small><?php echo nl2br(htmlspecialchars($exp->obs)) ?></small></div>
    </div>
    <?php endif; ?>
</div>

</div><!-- /row -->
</section>

<!-- ── MODAL: Nova Diligência ── -->
<div class="modal fade" id="modal-nova-dilig" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content" style="border-radius:10px;overflow:hidden">
        <div class="modal-header modal-header-dark"><h4 class="modal-title"><i class="fa fa-plus"></i> Nova Diligência</h4><button class="close" data-dismiss="modal">&times;</button></div>
        <form method="post" action="<?php echo site_url('admin/patrimonio/diligencia_add/'.$exp->id) ?>">
        <div class="modal-body">
            <div class="form-group"><label>Sistema</label>
                <select name="sistema" class="form-control" required>
                    <option value="">-- Selecione --</option>
                    <?php foreach(['sisbajud'=>'SISBAJUD — Busca bancária','renajud'=>'RENAJUD — Busca veicular','infojud'=>'INFOJUD — Receita Federal','sniper'=>'SNIPER — Busca geral CNJ','cnib'=>'CNIB — Indisponibilidade de bens','censec'=>'CENSEC — Cartórios','criptojud'=>'CRIPTOJUD — Criptoativos','manual'=>'Manual / Extrajudicial'] as $v=>$l): ?>
                    <option value="<?php echo $v ?>"><?php echo $l ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="row">
                <div class="col-md-6"><div class="form-group"><label>Data do Requerimento</label><input type="date" name="data_requerimento" value="<?php echo date('Y-m-d') ?>" class="form-control" required></div></div>
                <div class="col-md-6"><div class="form-group"><label>Nº da Petição</label><input type="text" name="num_peticao" class="form-control" placeholder="Pet. 0000/2025"></div></div>
            </div>
            <div class="row">
                <div class="col-md-4"><div class="form-group"><label>Validade</label>
                    <select name="validade_meses" class="form-control">
                        <option value="12" selected>12 meses (STJ)</option>
                        <option value="6">6 meses</option>
                        <option value="24">24 meses</option>
                    </select>
                </div></div>
                <div class="col-md-4"><div class="form-group"><label>Resultado</label>
                    <select name="resultado" class="form-control">
                        <option value="aguardando" selected>Aguardando</option>
                        <option value="positivo">Positivo</option>
                        <option value="negativo">Negativo</option>
                    </select>
                </div></div>
                <div class="col-md-4"><div class="form-group"><label>Data Resultado</label><input type="date" name="data_resultado" class="form-control"></div></div>
            </div>
            <div class="form-group"><label>Observações</label><textarea name="obs" class="form-control" rows="2"></textarea></div>
            <div class="alert alert-info" style="font-size:12px;padding:8px 12px;border-radius:6px"><i class="fa fa-bell"></i> Um alerta será criado automaticamente 30 dias antes do vencimento.</div>
        </div>
        <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button><button type="submit" name="ok" value="ok" class="btn btn-primary"><i class="fa fa-save"></i> Salvar</button></div>
        </form>
    </div></div>
</div>

<!-- ── MODAL: Novo Bem ── -->
<div class="modal fade" id="modal-novo-bem" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content" style="border-radius:10px;overflow:hidden">
        <div class="modal-header modal-header-dark" style="background:linear-gradient(135deg,#2e7d32,#27ae60)"><h4 class="modal-title"><i class="fa fa-home"></i> Registrar Bem Encontrado</h4><button class="close" data-dismiss="modal">&times;</button></div>
        <form method="post" action="<?php echo site_url('admin/patrimonio/bem_add/'.$exp->id) ?>">
        <div class="modal-body">
            <div class="row">
                <div class="col-md-6"><div class="form-group"><label>Tipo de Bem</label>
                    <select name="tipo" class="form-control" id="bem-tipo" required>
                        <option value="">-- Selecione --</option>
                        <option value="conta_bancaria">Conta Bancária</option>
                        <option value="veiculo">Veículo</option>
                        <option value="imovel">Imóvel</option>
                        <option value="quota_societaria">Quota Societária</option>
                        <option value="credito">Crédito / Recebível</option>
                        <option value="criptoativo">Criptoativo</option>
                        <option value="outro">Outro</option>
                    </select>
                </div></div>
                <div class="col-md-6"><div class="form-group"><label>Diligência Origem</label>
                    <select name="diligencia_id" class="form-control">
                        <option value="">-- Nenhuma --</option>
                        <?php foreach($diligencias as $d): ?>
                        <option value="<?php echo $d->id ?>"><?php echo strtoupper($d->sistema) ?> — <?php echo date('d/m/Y',strtotime($d->data_requerimento)) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div></div>
            </div>
            <div class="form-group"><label>Descrição</label><input type="text" name="descricao" class="form-control" required placeholder="Ex: Conta corrente Bradesco, Fiat Uno placa ABC-1234..."></div>
            <div class="row">
                <div class="col-md-6"><div class="form-group"><label>Instituição / Local</label><input type="text" name="instituicao" class="form-control" placeholder="Ex: Banco Bradesco, DETRAN/PE"></div></div>
                <div class="col-md-6"><div class="form-group"><label>Valor Estimado (R$)</label><input type="text" name="valor_estimado" class="form-control" placeholder="0,00"></div></div>
            </div>
            <!-- Consulta FIPE para veículos -->
            <div id="fipe-area" style="display:none;background:#f8f9fb;border:1px solid #e2e6ea;border-radius:8px;padding:12px;margin-bottom:10px">
                <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase">Consultar Valor FIPE</label>
                <div class="row">
                    <div class="col-md-4"><select id="fipe-tipo" class="form-control input-sm"><option value="carros">Carro</option><option value="motos">Moto</option><option value="caminhoes">Caminhão</option></select></div>
                    <div class="col-md-4"><select id="fipe-marca" class="form-control input-sm"><option>-- Carregando --</option></select></div>
                    <div class="col-md-4"><button type="button" class="btn btn-default btn-sm btn-block" id="btn-fipe">Buscar FIPE</button></div>
                </div>
                <div id="fipe-resultado" style="margin-top:8px;font-size:13px;font-weight:600;color:#2e7d32"></div>
                <input type="hidden" name="valor_fipe" id="valor_fipe_hidden" value="0">
            </div>
            <div class="form-group"><label>Status</label>
                <select name="status" class="form-control">
                    <option value="identificado">Identificado</option>
                    <option value="bloqueado">Bloqueado</option>
                    <option value="penhorado">Penhorado</option>
                </select>
            </div>
            <div class="form-group"><label>Observações</label><textarea name="obs" class="form-control" rows="2"></textarea></div>
        </div>
        <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button><button type="submit" name="ok" value="ok" class="btn btn-success"><i class="fa fa-save"></i> Registrar Bem</button></div>
        </form>
    </div></div>
</div>

<script>
$(function(){
    // Mostra FIPE quando tipo = veículo
    $('#bem-tipo').on('change', function(){
        if($(this).val()==='veiculo'){
            $('#fipe-area').show();
            carregarMarcasFipe();
        } else {
            $('#fipe-area').hide();
        }
    });

    function carregarMarcasFipe(){
        $.get('<?php echo site_url('admin/patrimonio/api_fipe') ?>?action=marcas&tipo='+$('#fipe-tipo').val(), function(r){
            var opts='<option>-- Marca --</option>';
            $.each(r||[], function(i,m){ opts+='<option value="'+m.codigo+'">'+m.nome+'</option>'; });
            $('#fipe-marca').html(opts);
        });
    }
    $('#fipe-tipo').on('change', carregarMarcasFipe);

    // Consulta API
    $('#btn-api-consultar').on('click', function(){
        var doc = $('#api-doc').val();
        if(!doc) return;
        $(this).html('<i class="fa fa-spin fa-spinner"></i>').prop('disabled',true);
        $('#api-loading').show(); $('#api-res').empty();
        $.ajax({
            url:'<?php echo site_url('admin/patrimonio/api_consultar') ?>',
            type:'POST',
            data:{documento:doc, expediente_id:<?php echo $exp->id ?>},
            success:function(r){
                $('#api-loading').hide();
                var html='';
                if(r.cnpj && !r.cnpj.erro){
                    html+='<div class="well well-sm" style="border-radius:8px;margin-bottom:10px">';
                    html+='<strong>'+r.cnpj.razao_social+'</strong> <small class="text-muted">('+r.cnpj.fonte+')</small><br>';
                    html+='Situação: <strong>'+(r.cnpj.situacao||'—')+'</strong> | '+r.cnpj.municipio+'<br>';
                    if(r.cnpj.socios && r.cnpj.socios.length){
                        html+='<br><strong>Sócios:</strong><ul style="margin:4px 0;padding-left:16px">';
                        $.each(r.cnpj.socios,function(i,s){ html+='<li style="font-size:12px">'+s.nome+' — '+s.qual+(s.cpf?' (CPF: '+s.cpf+')':'')+'</li>'; });
                        html+='</ul>';
                    }
                    html+='</div>';
                } else if(r.cnpj && r.cnpj.erro){
                    html+='<div class="alert alert-warning" style="font-size:12px">CPF/CNPJ: '+r.cnpj.erro+'</div>';
                }
                if(r.datajud){
                    html+='<div class="well well-sm" style="border-radius:8px">';
                    html+='<strong><i class="fa fa-balance-scale"></i> DataJud:</strong> ';
                    if(r.datajud.total>0){
                        html+=r.datajud.total+' processo(s) localizado(s)<ul style="margin:6px 0;padding-left:16px">';
                        $.each(r.datajud.processos||[],function(i,p){
                            html+='<li style="font-size:12px"><code>'+p.numero+'</code> — '+p.tribunal+' — '+p.classe+'</li>';
                        });
                        html+='</ul>';
                    } else {
                        html+='Nenhum processo encontrado no DataJud.';
                    }
                    html+='</div>';
                }
                if(!html) html='<div class="alert alert-info">Nenhum dado encontrado.</div>';
                $('#api-res').html(html);
                $('#btn-api-consultar').html('<i class="fa fa-search"></i> Consultar CNPJá + DataJud').prop('disabled',false);
            },
            error:function(){$('#api-loading').hide();$('#btn-api-consultar').html('<i class="fa fa-search"></i> Consultar CNPJá + DataJud').prop('disabled',false);}
        });
    });

    // Toggle checklist via AJAX
    window.toggleCheck = function(id, el){
        var atual = $(el).hasClass('ok') ? 1 : 0;
        var novo  = atual ? 0 : 1;
        $.post('<?php echo site_url('admin/patrimonio/checklist_update') ?>/'+id, {realizado:novo}, function(){
            if(novo){$(el).addClass('ok').removeClass('no').html('✓');}
            else {$(el).removeClass('ok').addClass('no').html('○');}
        });
    };

    // Gera petição com sistema pré-selecionado
    window.gerarPeticaoSistema = function(s){
        $('[href="#tab-pet"]').tab('show');
        $('input[name="sistemas[]"][value="'+s+'"]').prop('checked',true);
    };
});
</script>
