<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<section class="content-header">
    <h1><i class="fa fa-balance-scale"></i> Processos encontrados via OAB <small>Aguardando importação</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/cases') ?>">Processos</a></li>
        <li class="active">Processos OAB Pendentes</li>
    </ol>
</section>

<section class="content">

<?php if (isset($pendentes) && count($pendentes) > 0): ?>
<div class="box box-primary">
    <div class="box-header with-border" style="background:linear-gradient(135deg,#1e3a5f,#2e75b6);border-radius:10px 10px 0 0">
        <h3 class="box-title" style="color:#fff"><i class="fa fa-list"></i> <?php echo count($pendentes) ?> processo(s) encontrado(s) via OAB</h3>
        <div class="box-tools pull-right">
            <span style="color:rgba(255,255,255,.7);font-size:12px;">Selecione os processos que deseja importar</span>
        </div>
    </div>
    <div class="box-body no-padding">
        <table class="table table-hover" style="margin:0">
            <thead>
                <tr>
                    <th style="width:30px"><input type="checkbox" id="check-all"></th>
                    <th>Número CNJ</th>
                    <th>Classe</th>
                    <th>Assunto</th>
                    <th>Polo Ativo</th>
                    <th>Polo Passivo</th>
                    <th>Ajuizamento</th>
                    <th>Tribunal</th>
                    <th>Valor</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($pendentes as $p): ?>
            <tr id="row-<?php echo $p->id ?>">
                <td><input type="checkbox" class="chk-processo" value="<?php echo $p->id ?>"></td>
                <td><code style="font-size:11px"><?php echo htmlspecialchars($p->numero_cnj) ?></code></td>
                <td style="font-size:12px"><?php echo htmlspecialchars($p->classe ?: '—') ?></td>
                <td style="font-size:12px"><?php echo htmlspecialchars($p->assunto ?: '—') ?></td>
                <td style="font-size:12px"><?php echo htmlspecialchars($p->polo_ativo ?: '—') ?></td>
                <td style="font-size:12px"><?php echo htmlspecialchars($p->polo_passivo ?: '—') ?></td>
                <td style="font-size:12px"><?php echo $p->data_inicio ? date('d/m/Y', strtotime($p->data_inicio)) : '—' ?></td>
                <td><span class="label label-info"><?php echo htmlspecialchars($p->tribunal ?: '?') ?></span></td>
                <td style="font-size:12px"><?php echo $p->valor_causa > 0 ? 'R$ '.number_format($p->valor_causa,2,',','.') : '—' ?></td>
                <td>
                    <button onclick="importarPendente(<?php echo $p->id ?>)" class="btn btn-success btn-xs">
                        <i class="fa fa-download"></i> Importar
                    </button>
                    <a href="<?php echo site_url('admin/cases/ignorar_pendente/'.$p->id) ?>"
                       onclick="return confirm('Ignorar este processo?')"
                       class="btn btn-default btn-xs">
                        <i class="fa fa-times"></i> Ignorar
                    </a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="box-footer">
        <select id="client-importar" class="form-control" style="display:inline-block;width:280px;margin-right:8px">
            <option value="">— Selecione o cliente para os selecionados —</option>
            <?php foreach ($clients as $c): ?>
            <option value="<?php echo $c->id ?>"><?php echo htmlspecialchars($c->name) ?></option>
            <?php endforeach; ?>
        </select>
        <button onclick="importarSelecionados()" class="btn btn-success">
            <i class="fa fa-download"></i> Importar Selecionados
        </button>
        <a href="<?php echo site_url('admin/cases') ?>" class="btn btn-default pull-right">
            <i class="fa fa-arrow-left"></i> Voltar
        </a>
    </div>
</div>

<!-- Modal de seleção de cliente para importação individual -->
<div id="modal-importar" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);z-index:9998;">
    <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);background:#fff;border-radius:10px;padding:24px;width:420px;box-shadow:0 8px 30px rgba(0,0,0,.2)">
        <h4 style="margin-top:0"><i class="fa fa-download"></i> Importar Processo</h4>
        <p style="font-size:12px;color:#666">Selecione o cliente que este processo pertence:</p>
        <input type="hidden" id="importar-id">
        <select id="importar-client" class="form-control" style="margin-bottom:14px">
            <option value="">— Selecione o cliente —</option>
            <?php foreach ($clients as $c): ?>
            <option value="<?php echo $c->id ?>"><?php echo htmlspecialchars($c->name) ?></option>
            <?php endforeach; ?>
        </select>
        <div style="display:flex;gap:8px;justify-content:flex-end">
            <button onclick="fecharModalImportar()" class="btn btn-default">Cancelar</button>
            <button onclick="confirmarImportar()" class="btn btn-success"><i class="fa fa-check"></i> Confirmar</button>
        </div>
    </div>
</div>

<?php else: ?>
<div class="box box-default">
    <div class="box-body text-center" style="padding:40px">
        <i class="fa fa-check-circle fa-4x text-success" style="margin-bottom:16px;display:block"></i>
        <h3>Nenhum processo pendente</h3>
        <p class="text-muted">Todos os processos encontrados via OAB já foram importados ou ignorados.</p>
        <a href="<?php echo site_url('admin/cases') ?>" class="btn btn-primary">
            <i class="fa fa-folder-open"></i> Ver todos os processos
        </a>
    </div>
</div>
<?php endif; ?>

</section>

<script>
// Selecionar todos
document.getElementById('check-all') && document.getElementById('check-all').addEventListener('change', function() {
    document.querySelectorAll('.chk-processo').forEach(function(c){ c.checked = this.checked; }.bind(this));
});

function importarPendente(id) {
    document.getElementById('importar-id').value = id;
    document.getElementById('modal-importar').style.display = 'block';
}
function fecharModalImportar() {
    document.getElementById('modal-importar').style.display = 'none';
}
function confirmarImportar() {
    var id       = document.getElementById('importar-id').value;
    var clientId = document.getElementById('importar-client').value;
    if (!clientId) { alert('Selecione o cliente.'); return; }
    executarImportacao([id], clientId);
}
function importarSelecionados() {
    var ids      = Array.from(document.querySelectorAll('.chk-processo:checked')).map(function(c){ return c.value; });
    var clientId = document.getElementById('client-importar').value;
    if (!ids.length) { alert('Selecione ao menos um processo.'); return; }
    if (!clientId)   { alert('Selecione o cliente.'); return; }
    executarImportacao(ids, clientId);
}
function executarImportacao(ids, clientId) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '<?php echo site_url("admin/cases/importar_processos_oab") ?>', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try {
            var r = JSON.parse(xhr.responseText);
            if (r.success) {
                alert(r.msg);
                ids.forEach(function(id){ var row = document.getElementById('row-'+id); if(row) row.remove(); });
                fecharModalImportar();
            } else {
                alert('Erro: ' + r.msg);
            }
        } catch(e) { alert('Erro ao processar resposta.'); }
    };
    xhr.send('ids=' + ids.join(',') + '&client_id=' + clientId);
}
</script>
