<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<link href="<?php echo base_url('assets/css/chosen.css') ?>" rel="stylesheet">
<style>
.form-group label { font-size:11px; font-weight:700; color:#888; text-transform:uppercase; letter-spacing:.5px; margin-bottom:5px; display:block; }
.gender-opt { display:inline-flex; align-items:center; gap:5px; margin-right:18px; font-weight:400; font-size:13px; }
.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:12px 18px; 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:20px; border-radius:0 0 10px 10px; }
.section-block { background:#f8f9fb; border:1px solid #e2e6ea; border-radius:8px; padding:16px 18px; margin-bottom:16px; }
.section-block h5 { font-size:13px; font-weight:700; color:#1e3a5f; margin:0 0 14px; display:flex; align-items:center; gap:7px; }
</style>

<section class="content-header">
    <h1><i class="fa fa-cog"></i> <?php echo lang('general_settings') ?></h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li class="active"><?php echo lang('general_settings') ?></li>
    </ol>
</section>

<section class="content">

<?php if(validation_errors()): ?>
<div class="alert alert-danger alert-dismissible">
    <button class="close" data-dismiss="alert">&times;</button>
    <i class="fa fa-ban"></i> <?php echo validation_errors() ?>
</div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data" action="<?php echo site_url('admin/settings/') ?>">
<div class="nav-tabs-custom">
    <ul class="nav nav-tabs">
        <li class="active"><a href="#tab-detalhes" data-toggle="tab"><i class="fa fa-building-o"></i> <?php echo lang('details') ?></a></li>
        <li><a href="#tab-cnj" data-toggle="tab"><i class="fa fa-balance-scale" style="color:#00539B"></i> DataJud / CNJ</a></li>
        <li><a href="#tab-oab" data-toggle="tab"><i class="fa fa-id-card" style="color:#2e7d32"></i> OAB / Monitoramento</a></li>
        <li><a href="#tab-rh" data-toggle="tab"><i class="fa fa-users"></i> <?php echo lang('hr_settings') ?></a></li>
        <li><a href="#tab-smtp" data-toggle="tab"><i class="fa fa-envelope"></i> <?php echo lang('smtp_settings') ?></a></li>
        <li><a href="#tab-seguranca" data-toggle="tab"><i class="fa fa-shield"></i> Segurança</a></li>
    </ul>
    <div class="tab-content">

        <!-- ================================================ -->
        <!-- ABA: Detalhes                                    -->
        <!-- ================================================ -->
        <div class="tab-pane active" id="tab-detalhes">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('company_name') ?></label>
                        <input type="text" name="name" value="<?php echo $settings->name ?? '' ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('logo') ?></label>
                        <div style="display:flex;align-items:center;gap:10px">
                            <input type="file" name="img" class="form-control" style="flex:1">
                            <?php if(!empty($settings->image)): ?>
                            <img src="<?php echo base_url('assets/uploads/images/'.$settings->image) ?>" style="height:44px;max-width:120px;object-fit:contain;border:1px solid #e2e6ea;border-radius:6px;padding:4px">
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('header_logo_image') ?></label>
                        <div style="padding-top:6px">
                            <label class="gender-opt"><input type="radio" name="header_setting" value="0" <?php echo ($settings->header_setting??0)==0?'checked':'' ?>> <?php echo lang('company_name') ?></label>
                            <label class="gender-opt"><input type="radio" name="header_setting" value="1" <?php echo ($settings->header_setting??0)==1?'checked':'' ?>> <?php echo lang('logo') ?></label>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('phone') ?></label>
                        <input type="text" name="contact" value="<?php echo $settings->contact ?? '' ?>" class="form-control">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('email') ?></label>
                        <input type="text" name="email" value="<?php echo $settings->email ?? '' ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('address') ?></label>
                        <textarea name="address" class="form-control" rows="2"><?php echo $settings->address ?? '' ?></textarea>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label><?php echo lang('default_date_format') ?></label>
                        <select name="date_format" class="form-control chzn">
                            <option value="">-- <?php echo lang('select') ?> --</option>
                            <?php
                            $formats = ['d-m-Y'=>'DD-MM-YYYY','Y-m-d'=>'YYYY-MM-DD','m-d-Y'=>'MM-DD-YYYY'];
                            foreach($formats as $val=>$label):
                                $sel = ($settings->date_format??'')==$val?'selected':'';
                            ?>
                            <option value="<?php echo $val ?>" <?php echo $sel ?>><?php echo $label ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label><?php echo lang('timezone') ?></label>
                        <select name="timezone" class="form-control chzn">
                            <option value="">-- <?php echo lang('select') ?> --</option>
                            <?php foreach(DateTimeZone::listIdentifiers(DateTimeZone::ALL) as $tz):
                                $sel = ($settings->timezone??'')==$tz?'selected':'';
                            ?>
                            <option value="<?php echo $tz ?>" <?php echo $sel ?>><?php echo $tz ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label><?php echo lang('invoice_start') ?></label>
                        <input type="text" name="invoice_no" value="<?php echo $settings->invoice_no ?? '' ?>" class="form-control">
                    </div>
                </div>
            </div>
        </div><!-- /tab-detalhes -->

        <!-- ================================================ -->
        <!-- ABA: DataJud / CNJ                               -->
        <!-- ================================================ -->
        <div class="tab-pane" id="tab-cnj">
            <div class="section-block">
                <h5><i class="fa fa-balance-scale" style="color:#00539B"></i> API DataJud – CNJ</h5>
                <p style="font-size:12px; color:#666; margin-bottom:14px;">
                    A API Pública do DataJud é fornecida pelo CNJ para consulta de processos judiciais.
                    A chave pode ser alterada pelo CNJ a qualquer momento — consulte a chave vigente em:
                    <a href="https://datajud-wiki.cnj.jus.br/api-publica/acesso" target="_blank">datajud-wiki.cnj.jus.br/api-publica/acesso</a>
                </p>
                <div class="row">
                    <div class="col-md-10">
                        <div class="form-group">
                            <label>API Key (Authorization: APIKey ...)</label>
                            <div style="display:flex; gap:8px; align-items:center;">
                                <input type="text"
                                       name="datajud_api_key"
                                       id="datajud_api_key"
                                       value="<?php echo htmlspecialchars($settings->datajud_api_key ?? 'cDZHYzlZa0JadVREZDJCendQbXY6SkJlTzNjLV9TRENyQk1RdnFKZGRQdw==') ?>"
                                       class="form-control"
                                       placeholder="cDZHYzlZa0JadVREZDJCendQbXY6..."
                                       style="font-family:monospace; font-size:12px;">
                                <button type="button" class="btn btn-default btn-sm" id="btn-testar-cnj" style="white-space:nowrap;">
                                    <i class="fa fa-plug"></i> Testar
                                </button>
                            </div>
                            <small class="text-muted">Cole a chave exatamente como aparece na documentação do CNJ, sem espaços.</small>
                        </div>
                    </div>
                </div>
                <div id="cnj-teste-resultado" style="display:none; margin-top:8px;"></div>
            </div>

            <div class="section-block">
                <h5><i class="fa fa-info-circle" style="color:#2e75b6"></i> Informações do módulo</h5>
                <table class="table table-condensed" style="font-size:12px; margin:0;">
                    <tr>
                        <td style="width:220px; color:#888;">Endpoint base</td>
                        <td><code>https://api-publica.datajud.cnj.jus.br/</code></td>
                    </tr>
                    <tr>
                        <td style="color:#888;">Tribunais suportados</td>
                        <td>Todos os TJs, TRTs, TRFs (identificação automática pelo número CNJ)</td>
                    </tr>
                    <tr>
                        <td style="color:#888;">Fallback</td>
                        <td>Worker PJe Cloudflare (quando DataJud não encontrar o processo)</td>
                    </tr>
                    <tr>
                        <td style="color:#888;">Documentação CNJ</td>
                        <td><a href="https://datajud-wiki.cnj.jus.br" target="_blank">datajud-wiki.cnj.jus.br</a></td>
                    </tr>
                </table>
            </div>
        </div><!-- /tab-cnj -->

        <!-- ================================================ -->
        <!-- ABA: RH                                          -->
        <!-- ================================================ -->
        <div class="tab-pane" id="tab-rh">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label><?php echo lang('mark_out_time') ?></label>
                        <input type="time" name="mark_out_time" value="<?php echo $settings->mark_out_time ?? '' ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label><?php echo lang('employee_id_start_from') ?></label>
                        <input type="text" name="employee_id" value="<?php echo $settings->employee_id ?? '' ?>" class="form-control">
                    </div>
                </div>
            </div>
            <h4 style="font-size:13px;font-weight:700;color:#1e3a5f;margin:16px 0 12px"><?php echo lang('working_days') ?></h4>
            <div class="row">
            <?php foreach($days as $new): ?>
                <div class="col-md-3">
                    <div class="form-group">
                        <label><?php echo $new->name ?></label>
                        <input type="hidden" name="days[<?php echo $new->id ?>]" value="0">
                        <div style="padding-top:4px">
                            <label class="gender-opt">
                                <input type="checkbox" name="days[<?php echo $new->id ?>]" value="1" <?php echo $new->working_day==1?'checked':'' ?>>
                                <?php echo lang('working_day') ?>
                            </label>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            </div>
        </div><!-- /tab-rh -->

        <!-- ================================================ -->
        <!-- ABA: SMTP                                        -->
        <!-- ================================================ -->
        <div class="tab-pane" id="tab-smtp">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('smtp_host') ?></label>
                        <input type="text" name="smtp_host" value="<?php echo $settings->smtp_host ?? '' ?>" class="form-control" placeholder="smtp.gmail.com">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label><?php echo lang('smtp_port') ?></label>
                        <input type="text" name="smtp_port" value="<?php echo $settings->smtp_port ?? '' ?>" class="form-control" placeholder="587">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('smtp_username') ?></label>
                        <input type="text" name="smtp_user" value="<?php echo $settings->smtp_user ?? '' ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label><?php echo lang('smtp_password') ?></label>
                        <input type="text" name="smtp_pass" value="<?php echo $settings->smtp_pass ?? '' ?>" class="form-control">
                    </div>
                </div>
            </div>
        </div><!-- /tab-smtp -->

        <!-- ================================================ -->
        <!-- ABA: Segurança                                   -->
        <!-- ================================================ -->
        <div class="tab-pane" id="tab-seguranca">

            <div class="section-block">
                <h5><i class="fa fa-cloud" style="color:#e67e22"></i> Cloudflare Turnstile (CAPTCHA)</h5>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Chave do Site (Site Key)</label>
                            <input type="text" name="turnstile_site_key" value="<?php echo $settings->turnstile_site_key ?? '' ?>" class="form-control" placeholder="0x4AAAAAAA...">
                            <small class="text-muted">Obtenha em: <a href="https://dash.cloudflare.com/?to=/:account/turnstile" target="_blank">dash.cloudflare.com → Turnstile</a></small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Chave Secreta (Secret Key)</label>
                            <input type="password" name="turnstile_secret_key" value="<?php echo $settings->turnstile_secret_key ?? '' ?>" class="form-control">
                        </div>
                    </div>
                </div>
            </div>

            <div class="section-block">
                <h5><i class="fa fa-lock" style="color:#c0392b"></i> Controle de Tentativas de Login</h5>
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Máximo de Tentativas</label>
                            <input type="number" name="login_max_attempts" value="<?php echo $settings->login_max_attempts ?? 5 ?>" class="form-control" min="3" max="20">
                            <small class="text-muted">Tentativas antes de bloquear</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Bloqueio (minutos)</label>
                            <input type="number" name="login_lockout_minutes" value="<?php echo $settings->login_lockout_minutes ?? 15 ?>" class="form-control" min="5" max="1440">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Timeout por Inatividade (horas)</label>
                            <input type="number" name="session_timeout_hours" value="<?php echo $settings->session_timeout_hours ?? 2 ?>" class="form-control" min="1" max="24">
                        </div>
                    </div>
                </div>
            </div>

            <div class="section-block">
                <h5><i class="fa fa-key" style="color:#2e7d32"></i> Requisitos de Senha</h5>
                <div class="row">
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Tamanho mínimo</label>
                            <input type="number" name="password_min_length" value="<?php echo $settings->password_min_length ?? 8 ?>" class="form-control" min="6" max="30">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Exigir maiúscula</label>
                            <select name="password_require_upper" class="form-control">
                                <option value="1" <?php echo ($settings->password_require_upper??1)==1?'selected':'' ?>>Sim</option>
                                <option value="0" <?php echo ($settings->password_require_upper??1)==0?'selected':'' ?>>Não</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Exigir número</label>
                            <select name="password_require_number" class="form-control">
                                <option value="1" <?php echo ($settings->password_require_number??1)==1?'selected':'' ?>>Sim</option>
                                <option value="0" <?php echo ($settings->password_require_number??1)==0?'selected':'' ?>>Não</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Exigir símbolo</label>
                            <select name="password_require_symbol" class="form-control">
                                <option value="1" <?php echo ($settings->password_require_symbol??0)==1?'selected':'' ?>>Sim</option>
                                <option value="0" <?php echo ($settings->password_require_symbol??0)==0?'selected':'' ?>>Não</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

        </div><!-- /tab-seguranca -->


        <!-- ================================================ -->
        <!-- ABA: OAB / Monitoramento                         -->
        <!-- ================================================ -->
        <div class="tab-pane" id="tab-oab">

            <div class="section-block">
                <h5><i class="fa fa-id-card" style="color:#2e7d32"></i> Dados da OAB — Busca Automática de Processos</h5>
                <p style="font-size:12px; color:#666; margin-bottom:14px;">
                    O sistema buscará automaticamente no DataJud todos os processos onde o advogado cadastrado abaixo aparece como representante.
                </p>
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Número OAB</label>
                            <input type="text" name="oab_numero" value="<?php echo htmlspecialchars($settings->oab_numero ?? '') ?>" class="form-control" placeholder="Ex: 12345">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>UF da OAB</label>
                            <select name="oab_uf" class="form-control">
                                <?php
                                $ufs = ['AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA','PB','PR','PE','PI','RJ','RN','RS','RO','RR','SC','SE','SP','TO'];
                                foreach($ufs as $uf):
                                    $sel = ($settings->oab_uf ?? 'PE') == $uf ? 'selected' : '';
                                ?>
                                <option value="<?php echo $uf ?>" <?php echo $sel ?>><?php echo $uf ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-5">
                        <div class="form-group">
                            <label>Nome do Advogado (confirmação)</label>
                            <input type="text" name="oab_nome" value="<?php echo htmlspecialchars($settings->oab_nome ?? '') ?>" class="form-control" placeholder="Ex: Breno Augusto Wanderley de Paiva">
                        </div>
                    </div>
                </div>
            </div>

            <div class="section-block">
                <h5><i class="fa fa-clock-o" style="color:#d35400"></i> Configuração do Monitoramento Automático</h5>
                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Intervalo de sincronização (horas)</label>
                            <select name="oab_sync_horas" class="form-control">
                                <?php foreach([6,12,24,48] as $h): $sel = ($settings->oab_sync_horas ?? 12) == $h ? 'selected' : ''; ?>
                                <option value="<?php echo $h ?>" <?php echo $sel ?>><?php echo $h ?>h</option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Frequência com que o cron atualiza os processos</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Monitoramento automático</label>
                            <select name="oab_sync_ativo" class="form-control">
                                <option value="1" <?php echo ($settings->oab_sync_ativo ?? 1) == 1 ? 'selected' : '' ?>>Ativo</option>
                                <option value="0" <?php echo ($settings->oab_sync_ativo ?? 1) == 0 ? 'selected' : '' ?>>Pausado</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <div class="section-block">
                <h5><i class="fa fa-terminal" style="color:#666"></i> Configuração do Cron Job</h5>
                <p style="font-size:12px; color:#666;">Configure no cPanel → Cron Jobs com o comando abaixo:</p>
                <div style="background:#1e1e1e; color:#d4d4d4; padding:12px 16px; border-radius:6px; font-family:monospace; font-size:12px; margin-bottom:8px;">
                    0 */<?php echo $settings->oab_sync_horas ?? 12 ?> * * *&nbsp;&nbsp;
                    /usr/bin/php <?php echo FCPATH ?>oab_cron.php >> /tmp/oab_cron.log 2>&1
                </div>
                <small class="text-muted">
                    <i class="fa fa-info-circle"></i>
                    O arquivo <code>oab_cron.php</code> deve estar na raiz do sistema: <code><?php echo FCPATH ?>oab_cron.php</code>
                </small>
                <br><br>
                <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                    <button type="button" onclick="buscarOABAgora()" id="btn-buscar-oab" class="btn btn-primary btn-sm">
                        <i class="fa fa-search"></i> Buscar processos agora
                    </button>
                    <a href="<?php echo site_url('admin/cases/processos_oab_pendentes') ?>" class="btn btn-success btn-sm">
                        <i class="fa fa-list"></i> Ver fila de importação
                    </a>
                </div>
                <div id="oab-busca-resultado" style="display:none;margin-top:12px;"></div>
                <hr>
                <h5 style="font-size:12px;font-weight:700;color:#888;text-transform:uppercase;">Últimas sincronizações</h5>
                <div id="oab-log-container">
                    <p style="font-size:12px;color:#aaa;">Carregando...</p>
                </div>
            </div>

        </div><!-- /tab-oab -->

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

<div style="margin-top:16px">
    <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> <?php echo lang('save') ?></button>
</div>
</form>

</section>

<script src="<?php echo base_url('assets/js/chosen.jquery.min.js') ?>"></script>
<script>
$(function() {
    $('.chzn').chosen({ width:'100%' });

    $('#btn-testar-cnj').on('click', function() {
        var key = $.trim($('#datajud_api_key').val());
        if (!key) { alert('Informe a API Key.'); return; }

        var $btn = $(this);
        var $res = $('#cnj-teste-resultado');
        $btn.html('<i class="fa fa-spinner fa-spin"></i> Testando...').prop('disabled', true);
        $res.hide();

        $.ajax({
            url: '<?php echo site_url("admin/settings/testar_datajud") ?>',
            type: 'POST',
            data: { api_key: key },
            dataType: 'json',
            timeout: 15000,
            success: function(r) {
                $btn.html('<i class="fa fa-plug"></i> Testar').prop('disabled', false);
                if (r.autenticado) {
                    $res.html('<div class="alert alert-success" style="margin:0;padding:8px 12px;font-size:12px;"><i class="fa fa-check"></i> <strong>Chave válida!</strong> A API respondeu corretamente (HTTP 200).</div>').show();
                } else {
                    $res.html('<div class="alert alert-danger" style="margin:0;padding:8px 12px;font-size:12px;"><i class="fa fa-times"></i> <strong>Chave inválida (HTTP ' + (r.http_code||'?') + ').</strong> Verifique a chave na documentação do CNJ.</div>').show();
                }
            },
            error: function() {
                $btn.html('<i class="fa fa-plug"></i> Testar').prop('disabled', false);
                $res.html('<div class="alert alert-warning" style="margin:0;padding:8px 12px;font-size:12px;"><i class="fa fa-warning"></i> Não foi possível conectar ao DataJud.</div>').show();
            }
        });
    });
    // === OAB ===
    function carregarLogOAB() {
        var container = document.getElementById('oab-log-container');
        if (!container) return;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', '<?php echo site_url("admin/cases/log_sincronizacoes") ?>', true);
        xhr.onload = function() {
            try {
                var r = JSON.parse(xhr.responseText);
                if (!r.success || !r.logs.length) {
                    container.innerHTML = '<p style="font-size:12px;color:#aaa;">Nenhuma sincronização registrada ainda.</p>';
                    return;
                }
                var html = '<table class="table table-condensed" style="font-size:11px;margin:0"><thead><tr><th>Data</th><th>Tipo</th><th>Status</th><th>Resultado</th><th>Origem</th></tr></thead><tbody>';
                r.logs.forEach(function(l) {
                    var cor = l.status === 'ok' ? '#2e7d32' : '#c0392b';
                    var tipo = l.tipo === 'oab_busca' ? '<span class="label label-success">OAB</span>' : '<span class="label label-info">Movimentações</span>';
                    var res = l.tipo === 'oab_busca'
                        ? (l.processos_novos + ' processo(s) novos')
                        : (l.movs_novas + ' movimentação(ões) | ' + (l.case_no || ''));
                    html += '<tr><td>' + (l.created_at||'').substring(0,16) + '</td><td>' + tipo + '</td>'
                          + '<td style="color:'+cor+'">' + l.status + '</td>'
                          + '<td>' + res + '</td>'
                          + '<td>' + (l.origem||'') + '</td></tr>';
                });
                html += '</tbody></table>';
                container.innerHTML = html;
            } catch(e) {
                container.innerHTML = '<p style="font-size:12px;color:#c0392b;">Erro ao carregar log.</p>';
            }
        };
        xhr.send();
    }

    function buscarOABAgora() {
        var btn = document.getElementById('btn-buscar-oab');
        var res = document.getElementById('oab-busca-resultado');
        if (!btn) return;
        btn.disabled = true;
        btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Buscando...';
        res.style.display = 'none';

        var xhr = new XMLHttpRequest();
        xhr.open('GET', '<?php echo site_url("admin/cases/buscar_oab_agora") ?>', true);
        xhr.timeout = 60000;
        xhr.onload = function() {
            btn.disabled = false;
            btn.innerHTML = '<i class="fa fa-search"></i> Buscar processos agora';
            try {
                var r = JSON.parse(xhr.responseText);
                var cor = r.novos > 0 ? '#2e7d32' : '#888';
                var icone = r.novos > 0 ? 'check-circle' : 'info-circle';
                var det = r.detalhes ? '<br><small style="color:#aaa">' + r.detalhes.join(' | ') + '</small>' : '';
                res.innerHTML = '<div class="alert alert-' + (r.novos > 0 ? 'success' : 'info') + '" style="padding:10px 14px;font-size:12px;">'
                    + '<i class="fa fa-' + icone + '"></i> ' + r.msg + det + '</div>';
                res.style.display = 'block';
                carregarLogOAB();
            } catch(e) {
                res.innerHTML = '<div class="alert alert-danger" style="padding:10px 14px;font-size:12px;">Erro ao processar resposta.</div>';
                res.style.display = 'block';
            }
        };
        xhr.onerror = xhr.ontimeout = function() {
            btn.disabled = false;
            btn.innerHTML = '<i class="fa fa-search"></i> Buscar processos agora';
            res.innerHTML = '<div class="alert alert-warning" style="padding:10px 14px;font-size:12px;">Timeout — o servidor demorou. Tente novamente.</div>';
            res.style.display = 'block';
        };
        xhr.send();
    }

    // Carrega log quando estiver na aba OAB
    document.addEventListener('DOMContentLoaded', function() {
        var tabOAB = document.querySelector('[href="#tab-oab"]');
        if (tabOAB) {
            tabOAB.addEventListener('click', carregarLogOAB);
        }
    });

});
</script>
