<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<link href="<?php echo base_url('assets/css/chosen.css') ?>" rel="stylesheet">
<link href="<?php echo base_url('assets/css/jquery.datetimepicker.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; }
.section-title { font-size:13px; font-weight:700; color:#1e3a5f; margin:20px 0 14px; padding-bottom:6px; border-bottom:2px solid #e8f0fb; }
.section-title .fa { margin-right:6px; }
.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-folder-open"></i> <?php echo lang('case') ?> <small><?php echo lang('add') ?></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') ?>"><?php echo lang('cases') ?></a></li>
        <li class="active"><?php echo lang('add') ?></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; ?>

<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-plus"></i> Novo Processo</h3>
    </div>
    <?php echo form_open_multipart('admin/cases/add/') ?>
    <div class="box-body">

        <!-- CNJ AUTOCADASTRO -->
        <div id="cnj-banner" style="background:#eaf3fb;border-left:4px solid #2e75b6;padding:12px 16px;border-radius:6px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;">
            <span><i class="fa fa-magic" style="color:#2e75b6;margin-right:6px;"></i>
            <strong>Novo:</strong> Preencha automaticamente com o número CNJ do processo.</span>
            <button type="button" onclick="cnjAbrirModal()" class="btn btn-primary btn-sm" style="white-space:nowrap;margin-left:12px;">
                <i class="fa fa-search"></i> Buscar por número CNJ
            </button>
        </div>

        <!-- MODAL CNJ (sem dependência do Bootstrap para abrir) -->
        <div id="cnj-overlay" onclick="cnjFecharModal()" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9998;"></div>
        <div id="cnj-modal" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);width:90%;max-width:820px;max-height:90vh;overflow-y:auto;background:#fff;border-radius:10px;z-index:9999;box-shadow:0 10px 40px rgba(0,0,0,0.3);">
            <div style="background:linear-gradient(135deg,#1e3a5f,#2e75b6);color:#fff;padding:14px 20px;border-radius:10px 10px 0 0;display:flex;align-items:center;justify-content:space-between;">
                <div>
                    <h4 style="margin:0;color:#fff;font-weight:700;"><i class="fa fa-search"></i> Busca Automática de Processo</h4>
                    <small style="opacity:.8;">Consulta DataJud (CNJ)</small>
                </div>
                <button onclick="cnjFecharModal()" style="background:none;border:none;color:#fff;font-size:24px;cursor:pointer;line-height:1;">&times;</button>
            </div>
            <div style="padding:20px;">
                <!-- Campo de busca -->
                <div style="display:flex;gap:8px;margin-bottom:4px;">
                    <input type="text" id="cnj-input" placeholder="0000000-00.0000.0.00.0000" maxlength="25" autocomplete="off"
                        style="flex:1;padding:10px 14px;font-size:18px;font-family:monospace;letter-spacing:1px;border:2px solid #d8dce2;border-radius:6px;"
                        onkeypress="if(event.which===13) cnjBuscar()">
                    <button onclick="cnjBuscar()" id="cnj-btn-buscar" class="btn btn-primary btn-lg">
                        <i class="fa fa-search"></i> Buscar
                    </button>
                </div>
                <small style="color:#999;">Formato: NNNNNNN-DD.AAAA.J.TT.OOOO &nbsp;|&nbsp; Ex: 0029368-51.2017.8.17.8201</small>

                <!-- Loading -->
                <div id="cnj-loading" style="display:none;text-align:center;padding:30px;">
                    <i class="fa fa-spinner fa-spin fa-3x" style="color:#2e75b6;"></i>
                    <p style="margin-top:12px;color:#888;">Consultando DataJud...</p>
                </div>

                <!-- Erro -->
                <div id="cnj-erro" style="display:none;margin-top:16px;" class="alert alert-danger">
                    <i class="fa fa-exclamation-triangle"></i> <strong id="cnj-erro-msg"></strong>
                </div>

                <!-- Resultado -->
                <div id="cnj-resultado" style="display:none;margin-top:16px;">
                    <div style="margin-bottom:10px;">
                        <span id="cnj-badge-fonte" class="label label-success" style="font-size:12px;padding:4px 10px;"></span>
                        <span id="cnj-badge-grau" class="label label-info" style="font-size:12px;padding:4px 10px;display:none;"></span>
                        <span id="cnj-badge-sigilo" class="label label-warning" style="font-size:12px;padding:4px 10px;display:none;">Sigilo</span>
                    </div>
                    <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                        <div style="grid-column:1/-1;">
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Classe / Tipo do Processo</label>
                            <input type="text" id="cnj-titulo" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div>
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Data de Ajuizamento</label>
                            <input type="text" id="cnj-data" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div>
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Valor da Causa</label>
                            <input type="text" id="cnj-valor" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div>
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Tribunal</label>
                            <input type="text" id="cnj-tribunal" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div>
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Órgão Julgador / Vara</label>
                            <input type="text" id="cnj-orgao" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div>
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;"><i class="fa fa-user text-success"></i> Polo Ativo</label>
                            <textarea id="cnj-polo-ativo" class="form-control" readonly rows="2" style="background:#f9f9f9;resize:none;"></textarea>
                        </div>
                        <div>
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;"><i class="fa fa-user text-danger"></i> Polo Passivo</label>
                            <textarea id="cnj-polo-passivo" class="form-control" readonly rows="2" style="background:#f9f9f9;resize:none;"></textarea>
                        </div>
                        <div style="grid-column:1/-1;" id="cnj-row-advogados" style="display:none;">
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;"><i class="fa fa-briefcase"></i> Advogados</label>
                            <input type="text" id="cnj-advogados" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div style="grid-column:1/-1;">
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Assunto(s) Processual(is)</label>
                            <input type="text" id="cnj-assunto" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div id="cnj-row-audiencia" style="display:none;">
                            <label style="font-size:10px;color:#2e7d32;font-weight:700;text-transform:uppercase;"><i class="fa fa-calendar text-success"></i> Próxima Audiência</label>
                            <input type="text" id="cnj-audiencia" class="form-control" readonly style="background:#f0fff4;border-color:#2e7d32;">
                        </div>
                        <div id="cnj-row-audiencia-tipo" style="display:none;">
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Tipo da Audiência</label>
                            <input type="text" id="cnj-audiencia-tipo" class="form-control" readonly style="background:#f9f9f9;">
                        </div>
                        <div style="grid-column:1/-1;" id="cnj-row-movimentos">
                            <label style="font-size:10px;color:#888;font-weight:700;text-transform:uppercase;">Últimas Movimentações</label>
                            <textarea id="cnj-movimentos" class="form-control" readonly rows="5" style="background:#f9f9f9;font-size:11px;resize:none;"></textarea>
                        </div>
                    </div>
                </div>
            </div>
            <div style="padding:12px 20px;background:#f8f9fb;border-top:1px solid #e2e6ea;border-radius:0 0 10px 10px;display:flex;justify-content:flex-end;gap:8px;">
                <button onclick="cnjFecharModal()" class="btn btn-default">
                    <i class="fa fa-times"></i> Fechar
                </button>
                <button onclick="cnjImportar()" id="cnj-btn-importar" class="btn btn-success btn-lg" style="display:none;">
                    <i class="fa fa-check"></i> Preencher formulário com estes dados
                </button>
            </div>
        </div>


        <!-- BLOCO 1: Identificação -->
        <div class="section-title"><i class="fa fa-info-circle"></i> Identificação</div>
        <div class="row">
            <div class="col-md-8">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('title') ?></label>
                    <input type="text" name="title" value="<?php echo set_value('title') ?>" class="form-control" required>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('number') ?></label>
                    <input type="text" name="case_no" value="<?php echo set_value('case_no') ?>" class="form-control">
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('client') ?> <?php echo lang('name') ?></label>
                    <div style="display:flex;gap:8px">
                        <select name="client_id" class="form-control chzn" style="flex:1">
                            <option value="">-- <?php echo lang('select') ?> <?php echo lang('client') ?> --</option>
                            <?php foreach($clients as $new):
                                $sel = set_select('client_id', $new->id) ? 'selected' : '';
                            ?>
                            <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <a href="#myModal" data-toggle="modal" class="btn btn-default" title="Novo cliente"><i class="fa fa-user-plus"></i></a>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('stage') ?></label>
                    <select name="case_stage_id" class="form-control chzn">
                        <option value="">-- <?php echo lang('select') ?> <?php echo lang('stage') ?> --</option>
                        <?php foreach($stages as $new):
                            $sel = set_select('case_stage_id', $new->id) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- BLOCO 2: Tribunal -->
        <div class="section-title"><i class="fa fa-university"></i> Tribunal</div>
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <label><?php echo lang('location') ?></label>
                    <select name="location_id" id="location_id" class="form-control chzn">
                        <option value="">-- <?php echo lang('select') ?> <?php echo lang('location') ?> --</option>
                        <?php foreach($locations as $new):
                            $sel = set_select('location_id', $new->id) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-4" id="court_category_result">
                <div class="form-group">
                    <label><?php echo lang('court') ?> <?php echo lang('category') ?></label>
                    <select name="court_category_id" id="court_category_id" class="form-control chzn" disabled>
                        <option value="">-- <?php echo lang('select') ?> <?php echo lang('court') ?> <?php echo lang('category') ?> --</option>
                        <?php foreach($court_categories as $new):
                            $sel = set_select('court_category_id', $new->id) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-4" id="court_result">
                <div class="form-group">
                    <label><?php echo lang('court') ?></label>
                    <select name="court_id" id="court_id" class="form-control chzn" disabled>
                        <option value="">-- <?php echo lang('select') ?> <?php echo lang('court') ?> --</option>
                        <?php foreach($courts as $new):
                            $sel = set_select('court_id', $new->id) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- BLOCO 3: Classificação -->
        <div class="section-title"><i class="fa fa-tags"></i> Classificação</div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('category') ?></label>
                    <select name="case_category_id[]" class="form-control chzn" multiple="multiple" data-placeholder="Selecione categorias...">
                        <?php foreach($case_categories as $new):
                            $sel = set_select('case_category_id', $new->id) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('act') ?></label>
                    <select name="act_id[]" class="form-control chzn" multiple="multiple" data-placeholder="Selecione legislações...">
                        <?php foreach($acts as $new):
                            $sel = set_select('act_id', $new->id) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->title) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- BLOCO 4: Datas e Valores -->
        <div class="section-title"><i class="fa fa-calendar"></i> Datas e Valores</div>
        <div class="row">
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('filling_date') ?></label>
                    <input type="text" name="start_date" value="<?php echo set_value('start_date') ?>" class="form-control datepicker" placeholder="AAAA-MM-DD">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('hearing_date') ?></label>
                    <input type="text" name="hearing_date" value="<?php echo set_value('hearing_date') ?>" class="form-control datepicker" placeholder="AAAA-MM-DD">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('opposite_lawyer') ?></label>
                    <input type="text" name="o_lawyer" value="<?php echo set_value('o_lawyer') ?>" class="form-control">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('total_fees') ?></label>
                    <input type="text" name="fees" value="<?php echo set_value('fees') ?>" class="form-control">
                </div>
            </div>
        </div>

        <!-- BLOCO 5: Descrição -->
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label><?php echo lang('description') ?></label>
                    <textarea name="description" class="form-control" rows="4"><?php echo set_value('description') ?></textarea>
                </div>
            </div>
        </div>

        <!-- BLOCO 6: Campos personalizados -->
        <?php if(!empty($fields)): ?>
        <div class="section-title"><i class="fa fa-list-alt"></i> Informações Adicionais</div>
        <div class="row">
        <?php foreach($fields as $doc):
            $values = explode(',', $doc->values ?? '');
        ?>
            <div class="col-md-4">
                <div class="form-group">
                    <label><?php echo htmlspecialchars($doc->name) ?></label>
                    <?php if($doc->field_type==1): ?>
                    <input type="text" class="form-control" name="reply[<?php echo $doc->id ?>]">
                    <?php elseif($doc->field_type==2): ?>
                    <select name="reply[<?php echo $doc->id ?>]" class="form-control">
                        <?php foreach($values as $val): ?>
                        <option value="<?php echo trim($val) ?>"><?php echo trim($val) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php elseif($doc->field_type==3): ?>
                    <div style="padding-top:6px"><?php foreach($values as $val): ?><label class="gender-opt"><input type="radio" name="reply[<?php echo $doc->id ?>]" value="<?php echo trim($val) ?>"> <?php echo trim($val) ?></label><?php endforeach; ?></div>
                    <?php elseif($doc->field_type==4): ?>
                    <div style="padding-top:6px"><?php foreach($values as $val): ?><label class="gender-opt"><input type="checkbox" name="reply[<?php echo $doc->id ?>][]" value="<?php echo trim($val) ?>"> <?php echo trim($val) ?></label><?php endforeach; ?></div>
                    <?php elseif($doc->field_type==5): ?>
                    <textarea class="form-control" name="reply[<?php echo $doc->id ?>]" rows="2"></textarea>
                    <?php elseif($doc->field_type==6): ?>
                    <input type="url" class="form-control" name="reply[<?php echo $doc->id ?>]">
                    <?php elseif($doc->field_type==7): ?>
                    <input type="email" class="form-control" name="reply[<?php echo $doc->id ?>]">
                    <?php elseif($doc->field_type==8): ?>
                    <input type="number" class="form-control" name="reply[<?php echo $doc->id ?>]">
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>

    </div>
    <div class="box-footer">
        <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> <?php echo lang('save') ?></button>
        <a href="<?php echo site_url('admin/cases') ?>" class="btn btn-default"><i class="fa fa-arrow-left"></i> Cancelar</a>
    </div>
    <?php echo form_close() ?>
</div>

</section>

<!-- Modal Novo Cliente -->
<div class="modal fade" id="myModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content" style="border-radius:10px;overflow:hidden">
            <div class="modal-header modal-header-dark">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title"><i class="fa fa-user-plus"></i> Novo Cliente</h4>
            </div>
            <form id="my_form">
                <div class="modal-body">
                    <div id="err" style="color:#c0392b;margin-bottom:10px"></div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><?php echo lang('name') ?></label>
                                <input type="text" id="name" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><?php echo lang('gender') ?></label>
                                <div style="padding-top:6px">
                                    <label class="gender-opt"><input type="radio" id="gender" name="gender" value="Male"> <?php echo lang('male') ?></label>
                                    <label class="gender-opt"><input type="radio" name="gender" value="Female"> <?php echo lang('female') ?></label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label><?php echo lang('date_of_birth') ?></label>
                                <input type="text" id="dob" class="form-control datepicker" placeholder="AAAA-MM-DD">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label><?php echo lang('email') ?></label>
                                <input type="text" id="email" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label><?php echo lang('phone') ?></label>
                                <input type="text" id="contact" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><?php echo lang('username') ?></label>
                                <input type="text" id="username" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label><?php echo lang('password') ?></label>
                                <input type="password" id="password" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label><?php echo lang('confirm') ?> <?php echo lang('password') ?></label>
                        <input type="password" id="confirm" class="form-control">
                    </div>
                    <div class="form-group">
                        <label><?php echo lang('address') ?></label>
                        <textarea id="address" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo lang('close') ?></button>
                    <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> <?php echo lang('save') ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// CNJ AUTOCADASTRO — vanilla JS + jQuery (sem Bootstrap)
var _cnjDados = null;

function cnjAbrirModal() {
    document.getElementById('cnj-overlay').style.display = 'block';
    document.getElementById('cnj-modal').style.display = 'block';
    document.body.style.overflow = 'hidden';
    setTimeout(function(){ document.getElementById('cnj-input').focus(); }, 100);
}

function cnjFecharModal() {
    document.getElementById('cnj-overlay').style.display = 'none';
    document.getElementById('cnj-modal').style.display = 'none';
    document.body.style.overflow = '';
}

// Máscara do número CNJ
document.getElementById('cnj-input') && document.getElementById('cnj-input').addEventListener('input', function() {
    var v = this.value.replace(/[^0-9]/g, '');
    var f = '';
    if (v.length >  0) f  = v.substr(0,7);
    if (v.length >  7) f += '-' + v.substr(7,2);
    if (v.length >  9) f += '.' + v.substr(9,4);
    if (v.length > 13) f += '.' + v.substr(13,1);
    if (v.length > 14) f += '.' + v.substr(14,2);
    if (v.length > 16) f += '.' + v.substr(16,4);
    this.value = f;
});

function cnjBuscar() {
    var numero = (document.getElementById('cnj-input').value || '').trim();
    if (!numero) { alert('Informe o número do processo.'); return; }

    _cnjDados = null;
    document.getElementById('cnj-resultado').style.display = 'none';
    document.getElementById('cnj-erro').style.display = 'none';
    document.getElementById('cnj-btn-importar').style.display = 'none';
    document.getElementById('cnj-loading').style.display = 'block';
    document.getElementById('cnj-btn-buscar').disabled = true;
    document.getElementById('cnj-btn-buscar').innerHTML = '<i class="fa fa-spinner fa-spin"></i> Aguarde...';

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '<?php echo site_url("admin/cases/buscar_processo_cnj"); ?>', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.timeout = 35000;
    xhr.onload = function() {
        document.getElementById('cnj-loading').style.display = 'none';
    document.getElementById('cnj-btn-buscar').disabled = false;
    document.getElementById('cnj-btn-buscar').innerHTML = '<i class="fa fa-search"></i> Buscar';
        try {
            var r = JSON.parse(xhr.responseText);
            if (!r.success) {
                document.getElementById('cnj-erro-msg').textContent = r.msg || 'Processo não encontrado.';
                document.getElementById('cnj-erro').style.display = 'block';
                return;
            }
            _cnjDados = r;
            cnjExibirResultado(r);
        } catch(e) {
            document.getElementById('cnj-erro-msg').textContent = 'Erro ao processar resposta do servidor.';
            document.getElementById('cnj-erro').style.display = 'block';
        }
    };
    xhr.onerror = xhr.ontimeout = function() {
        document.getElementById('cnj-loading').style.display = 'none';
    document.getElementById('cnj-btn-buscar').disabled = false;
    document.getElementById('cnj-btn-buscar').innerHTML = '<i class="fa fa-search"></i> Buscar';
        document.getElementById('cnj-erro-msg').textContent = 'Erro de comunicação com o servidor.';
        document.getElementById('cnj-erro').style.display = 'block';
    };
    xhr.send('numero_cnj=' + encodeURIComponent(numero));
}

function cnjExibirResultado(r) {
    var lf = { datajud: '✓ DataJud (CNJ)', pje_worker: '✓ PJe Comunica' };
    var lbl = (lf[r.fonte] || r.fonte) + (r.sistema ? ' · ' + r.sistema : '');
    document.getElementById('cnj-badge-fonte').textContent = lbl;

    if (r.grau) { document.getElementById('cnj-badge-grau').textContent = r.grau; document.getElementById('cnj-badge-grau').style.display = ''; }
    if (r.nivel_sigilo > 0) document.getElementById('cnj-badge-sigilo').style.display = '';

    document.getElementById('cnj-titulo').value       = r.titulo || '';
    document.getElementById('cnj-data').value         = r.data_inicio ? r.data_inicio.split('-').reverse().join('/') : '';
    document.getElementById('cnj-valor').value        = r.valor_causa || '';
    document.getElementById('cnj-tribunal').value     = r.tribunal || '';
    document.getElementById('cnj-orgao').value        = r.orgao_julgador || '';
    document.getElementById('cnj-polo-ativo').value   = r.polo_ativo || '';
    document.getElementById('cnj-polo-passivo').value = r.polo_passivo || '';
    document.getElementById('cnj-assunto').value      = r.todos_assuntos || r.descricao || '';
    document.getElementById('cnj-movimentos').value   = r.movimentos || '';

    if (r.advogados) {
        document.getElementById('cnj-advogados').value = r.advogados;
        document.getElementById('cnj-row-advogados').style.display = '';
    }

    if (r.proxima_audiencia) {
        var partes = r.proxima_audiencia.split('-');
        document.getElementById('cnj-audiencia').value = partes[2]+'/'+partes[1]+'/'+partes[0];
        document.getElementById('cnj-row-audiencia').style.display = '';
        document.getElementById('cnj-audiencia-tipo').value = r.proxima_audiencia_tipo || '';
        document.getElementById('cnj-row-audiencia-tipo').style.display = '';
    }

    document.getElementById('cnj-resultado').style.display = 'block';
    document.getElementById('cnj-btn-importar').style.display = '';
}

function cnjImportar() {
    if (!_cnjDados) return;
    var r = _cnjDados;

    document.querySelector('[name="title"]').value    = r.titulo || '';
    document.querySelector('[name="case_no"]').value  = r.numero || '';
    document.querySelector('[name="o_lawyer"]').value = r.polo_passivo || '';

    if (r.data_inicio) document.querySelector('[name="start_date"]').value = r.data_inicio;
    if (r.proxima_audiencia) document.querySelector('[name="hearing_date"]') && (document.querySelector('[name="hearing_date"]').value = r.proxima_audiencia);

    // Campos personalizados: Autor, Réu, Valor da Causa
    var autor = document.querySelector('[name="reply[6]"]');
    var reu   = document.querySelector('[name="reply[7]"]');
    var valor = document.querySelector('[name="reply[16]"]');
    if (autor && r.polo_ativo)   autor.value = r.polo_ativo;
    if (reu   && r.polo_passivo) reu.value   = r.polo_passivo;
    if (valor && r.valor_causa)  valor.value = r.valor_causa;

    // Descrição
    var desc = [];
    if (r.todos_assuntos) desc.push('Assunto: '       + r.todos_assuntos);
    if (r.grau)           desc.push('Grau: '          + r.grau);
    if (r.orgao_julgador) desc.push('Vara/Órgão: '    + r.orgao_julgador);
    if (r.polo_ativo)     desc.push('Polo Ativo: '    + r.polo_ativo);
    if (r.polo_passivo)   desc.push('Polo Passivo: '  + r.polo_passivo);
    if (r.valor_causa)    desc.push('Valor da causa: '+ r.valor_causa);
    if (r.advogados)      desc.push('Advogados: '     + r.advogados);
    if (r.proxima_audiencia) desc.push('Próx. Audiência: ' + r.proxima_audiencia_tipo + ' em ' + r.proxima_audiencia.split('-').reverse().join('/'));
    document.querySelector('[name="description"]').value = desc.join('\n');

    // Salva movimentos para importar após salvar
    var existing = document.querySelector('[name="cnj_movimentos_raw"]');
    if (existing) existing.parentNode.removeChild(existing);
    if (r.movimentos_raw && r.movimentos_raw.length) {
        var inp = document.createElement('input');
        inp.type = 'hidden'; inp.name = 'cnj_movimentos_raw';
        inp.value = JSON.stringify(r.movimentos_raw);
        document.querySelector('form').appendChild(inp);
    }

    cnjFecharModal();

    // Banner informativo
    if (r.movimentos_raw && r.movimentos_raw.length) {
        var banner = document.createElement('div');
        banner.className = 'alert alert-success';
        banner.style.marginTop = '10px';
        banner.innerHTML = '<i class="fa fa-check-circle"></i> <strong>Formulário preenchido!</strong> ' + r.movimentos_raw.length + ' movimentações serão importadas para a agenda ao salvar.';
        document.querySelector('.box.box-primary').insertAdjacentElement('beforebegin', banner);
    }

    // Scroll para o formulário
    setTimeout(function(){
        var el = document.querySelector('[name="title"]');
        if (el) { var y = el.getBoundingClientRect().top + window.scrollY - 80; window.scrollTo({top:y, behavior:'smooth'}); }
    }, 200);
}
</script>

<script src="<?php echo base_url('assets/js/chosen.jquery.min.js') ?>"></script>
<script src="<?php echo base_url('assets/js/jquery.datetimepicker.js') ?>"></script>
<script>
$(function() {
    $('.chzn').chosen({ width:'100%' });
    $('.datepicker').datetimepicker({ timepicker:false, format:'Y-m-d' });

    // AJAX: localidade → categoria tribunal
    $(document).on('change', '#location_id', function() {
        var vch = $(this).val();
        var loader = '<img src="<?php echo base_url('assets/img/ajax-loader.gif') ?>" style="margin:8px 0">';
        $('#court_category_result').html(loader);
        $.ajax({
            url: '<?php echo site_url('admin/cases/get_court_categories') ?>',
            type: 'POST',
            data: { id: vch },
            success: function(result) {
                $('#court_category_result').html(result);
                $('.chzn').chosen({ width:'100%' });
            }
        });
    });

    // AJAX: categoria tribunal → tribunal
    $(document).on('change', '#court_category_id', function() {
        var location_id = $('#location_id').val();
        var c_c_id      = $(this).val();
        var loader      = '<img src="<?php echo base_url('assets/img/ajax-loader.gif') ?>" style="margin:8px 0">';
        $('#court_result').html(loader);
        $.ajax({
            url: '<?php echo site_url('admin/cases/get_courts') ?>',
            type: 'POST',
            data: { l_id: location_id, c_id: c_c_id },
            success: function(result) {
                $('#court_result').html(result);
                $('.chzn').chosen({ width:'100%' });
            }
        });
    });

    // Modal novo cliente via AJAX
    $('#my_form').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: '<?php echo site_url('admin/clients/add_client') ?>',
            type: 'POST',
            data: {
                name:     $('#name').val(),
                gender:   $('input[name="gender"]:checked').val(),
                dob:      $('#dob').val(),
                email:    $('#email').val(),
                username: $('#username').val(),
                password: $('#password').val(),
                confirm:  $('#confirm').val(),
                contact:  $('#contact').val(),
                address:  $('#address').val()
            },
            success: function(result) {
                if (result === 'Success') {
                    $('#myModal').modal('hide');
                    location.reload();
                } else {
                    $('#err').html(result);
                }
            }
        });
    });
});
</script>
