<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
.detail-grid { display:grid; grid-template-columns:1fr 1fr; gap:0; }
.detail-item { padding:10px 16px; border-bottom:1px solid #f0f2f5; }
.detail-item.full { grid-column:1/-1; }
.detail-item .dl { font-size:10px; font-weight:700; color:#aaa; text-transform:uppercase; letter-spacing:.5px; display:block; margin-bottom:3px; }
.detail-item .dv { font-size:13px; color:#222; }
.case-num { font-family:monospace; font-size:14px; font-weight:700; color:#1e3a5f; }
@media(max-width:767px){
    .detail-grid{ grid-template-columns:1fr; }
    .detail-item.full{ grid-column:1; }
    .col-md-8,.col-md-4{ width:100%!important;float:none!important; }
}
</style>

<section class="content-header">
    <h1><i class="fa fa-folder-open"></i> <?php echo lang('case') ?> <small><?php echo lang('view') ?></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('view') ?></li>
    </ol>
</section>

<section class="content">
<?php
// Suporte a case_id ou id
$cid = isset($case->case_id) ? $case->case_id : (isset($case->id) ? $case->id : 0);
?>
<div class="row">

<!-- Coluna principal -->
<div class="col-md-8">
    <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-folder-open"></i> <?php echo htmlspecialchars($case->title ?? '') ?></h3>
            <div class="box-tools pull-right">
                <?php if(check_user_role(6)==1): ?>
                <a href="<?php echo site_url('admin/cases/edit/'.$cid) ?>" class="btn btn-xs" style="background:rgba(255,255,255,.2);color:#fff">
                    <i class="fa fa-pencil"></i> Editar
                </a>
                <?php endif; ?>
            </div>
        </div>
        <div class="box-body no-padding">
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="dl">Número do Processo</span>
                    <span class="dv case-num"><?php echo $case->case_no ?? '—' ?></span>
                </div>
                <div class="detail-item">
                    <span class="dl">Cliente</span>
                    <span class="dv">
                        <?php if(isset($clients)): foreach($clients as $c): if($c->id == ($case->client_id ?? 0)): ?>
                        <a href="<?php echo site_url('admin/clients/view_client/'.$c->id) ?>"><?php echo htmlspecialchars($c->name) ?></a>
                        <?php endif; endforeach; endif; ?>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="dl">Local / Foro</span>
                    <span class="dv">
                        <?php if(isset($locations)): foreach($locations as $l): if($l->id == ($case->location_id ?? 0)): echo htmlspecialchars($l->name); endif; endforeach; endif; ?>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="dl">Tribunal</span>
                    <span class="dv">
                        <?php if(isset($courts)): foreach($courts as $c): if($c->id == ($case->court_id ?? 0)): echo htmlspecialchars($c->name); endif; endforeach; endif; ?>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="dl">Categoria do Tribunal</span>
                    <span class="dv">
                        <?php if(isset($court_categories)): foreach($court_categories as $c): if($c->id == ($case->court_category_id ?? 0)): echo htmlspecialchars($c->name); endif; endforeach; endif; ?>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="dl">Fase Processual</span>
                    <span class="dv">
                        <?php if(isset($stages)): foreach($stages as $s): if($s->id == ($case->case_stage_id ?? 0)): echo htmlspecialchars($s->name); endif; endforeach; endif; ?>
                    </span>
                </div>
                <div class="detail-item">
                    <span class="dl">Data de Distribuição</span>
                    <span class="dv"><?php echo date_convert($case->start_date ?? '') ?></span>
                </div>
                <div class="detail-item">
                    <span class="dl">Data de Audiência</span>
                    <span class="dv"><?php echo date_convert($case->hearing_date ?? '') ?></span>
                </div>
                <div class="detail-item">
                    <span class="dl">Advogado Contrário</span>
                    <span class="dv"><?php echo htmlspecialchars($case->o_lawyer ?? '—') ?></span>
                </div>
                <div class="detail-item">
                    <span class="dl">Honorários</span>
                    <span class="dv">R$ <?php echo number_format($case->fees ?? 0, 2, ',', '.') ?></span>
                </div>
                <?php if(isset($case_categories) && !empty($case->case_category_id)): ?>
                <div class="detail-item full">
                    <span class="dl">Categoria do Processo</span>
                    <span class="dv">
                        <?php
                        $cats = @json_decode($case->case_category_id, true);
                        if($cats) foreach($case_categories as $c): if(in_array($c->id, $cats)):
                        ?><span class="label label-info" style="margin-right:3px"><?php echo htmlspecialchars($c->name) ?></span><?php
                        endif; endforeach; ?>
                    </span>
                </div>
                <?php endif; ?>
                <?php if(isset($acts) && !empty($case->act_id)): ?>
                <div class="detail-item full">
                    <span class="dl">Legislação Aplicável</span>
                    <span class="dv">
                        <?php
                        $act_ids = @json_decode($case->act_id, true);
                        if($act_ids) foreach($acts as $a): if(in_array($a->id, $act_ids)):
                        ?><span class="label label-default" style="margin-right:3px"><?php echo htmlspecialchars($a->title) ?></span><?php
                        endif; endforeach; ?>
                    </span>
                </div>
                <?php endif; ?>
                <?php if(!empty($case->description)): ?>
                <div class="detail-item full">
                    <span class="dl">Descrição</span>
                    <span class="dv" style="white-space:pre-wrap"><?php echo htmlspecialchars($case->description) ?></span>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <div class="box-footer">
            <a href="<?php echo site_url('admin/cases') ?>" class="btn btn-default btn-sm"><i class="fa fa-arrow-left"></i> Voltar</a>
            <?php if(check_user_role(6)==1): ?>
            <a href="<?php echo site_url('admin/cases/edit/'.$cid) ?>" class="btn btn-warning btn-sm"><i class="fa fa-pencil"></i> Editar</a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Histórico de Pagamentos -->
    <?php if(isset($fees_all) && count((array)$fees_all) > 0): ?>
    <div class="box box-success">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-money"></i> Histórico de Pagamentos</h3>
        </div>
        <div class="box-body no-padding">
            <table class="table table-hover" style="margin:0">
                <thead><tr><th>#</th><th>Data</th><th>Valor</th><th>Forma</th><th></th></tr></thead>
                <tbody>
                <?php $i=1; foreach($fees_all as $f): ?>
                <tr>
                    <td><?php echo $i++ ?></td>
                    <td><?php echo date_convert($f->date ?? '') ?></td>
                    <td><strong>R$ <?php echo number_format($f->amount ?? 0, 2, ',', '.') ?></strong></td>
                    <td><?php echo htmlspecialchars($f->mode ?? '—') ?></td>
                    <td><a href="<?php echo site_url('admin/invoice/index/'.$f->id) ?>" class="btn btn-xs btn-default"><i class="fa fa-file-text-o"></i> Recibo</a></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- Histórico Processual -->
    <?php if(isset($cases) && count((array)$cases) > 0): ?>
    <div class="box box-info">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-history"></i> Histórico Processual</h3>
        </div>
        <div class="box-body no-padding">
            <table class="table table-hover" style="margin:0">
                <thead><tr><th>#</th><th>Próxima Data</th><th>Última Data</th><th>Notas</th><th>Anexo</th></tr></thead>
                <tbody>
                <?php $i=1; foreach($cases as $h): ?>
                <tr>
                    <td><?php echo $i++ ?></td>
                    <td><?php echo date_convert($h->next_date ?? '') ?></td>
                    <td><?php echo date_convert($h->last_date ?? '') ?></td>
                    <td><?php echo htmlspecialchars(mb_substr($h->note ?? '', 0, 80)) ?><?php echo mb_strlen($h->note ?? '') > 80 ? '...' : '' ?></td>
                    <td>
                        <?php if(!empty($h->document)): ?>
                        <a href="<?php echo base_url('assets/uploads/files/'.$h->document) ?>" target="_blank" class="btn btn-xs btn-default"><i class="fa fa-download"></i></a>
                        <?php else: ?><span class="text-muted">—</span><?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- 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">
            <?php if(check_user_role(6)==1): ?>
            <a href="<?php echo site_url('admin/cases/edit/'.$cid) ?>" class="btn btn-warning btn-block btn-sm" style="margin-bottom:6px"><i class="fa fa-pencil"></i> Editar Processo</a>
            <?php endif; ?>
            <a href="<?php echo site_url('admin/cases/notes/'.$cid) ?>" class="btn btn-info btn-block btn-sm" style="margin-bottom:6px"><i class="fa fa-sticky-note-o"></i> Adicionar Movimentação</a>
            <?php if(!empty($case->case_no)): ?>
            <button onclick="sincronizarMovimentacoes(<?php echo $cid ?>)" id="btn-sync" class="btn btn-primary btn-block btn-sm" style="margin-bottom:6px">
                <i class="fa fa-refresh"></i> Sincronizar com DataJud
            </button>
            <div id="sync-status" style="font-size:11px;color:#888;text-align:center;margin-bottom:6px;display:none;padding:4px 8px;background:#f8f9fb;border-radius:4px;"></div>
            <?php endif; ?>
            <a href="<?php echo site_url('admin/cases/fees/'.$cid) ?>" class="btn btn-success btn-block btn-sm" style="margin-bottom:6px"><i class="fa fa-money"></i> Registrar Honorário</a>
            <a href="<?php echo site_url('admin/cases/archive/'.$cid) ?>" class="btn btn-default btn-block btn-sm"><i class="fa fa-archive"></i> Arquivar Processo</a>
        </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-calendar"></i> Datas Importantes</h3></div>
        <div class="box-body" style="padding:0">
            <table class="table" style="margin:0;font-size:12px">
                <tr><td class="text-muted" style="width:50%">Distribuição</td><td><strong><?php echo date_convert($case->start_date ?? '') ?></strong></td></tr>
                <tr><td class="text-muted">Audiência</td><td><strong><?php echo date_convert($case->hearing_date ?? '') ?></strong></td></tr>
            </table>
        </div>
    </div>
</div>

</div>
</section>

<script>
function sincronizarMovimentacoes(caseId) {
    var btn    = document.getElementById('btn-sync');
    var status = document.getElementById('sync-status');
    if (!btn) return;

    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Sincronizando...';
    if (status) status.style.display = 'none';

    var xhr = new XMLHttpRequest();
    xhr.open('GET', '<?php echo site_url("admin/cases/sincronizar_movimentacoes/") ?>' + caseId, true);
    xhr.timeout = 35000;

    xhr.onload = function() {
        btn.disabled = false;
        try {
            var r = JSON.parse(xhr.responseText);
            if (r.success) {
                btn.className = 'btn btn-success btn-block btn-sm';
                btn.innerHTML = '<i class="fa fa-check"></i> Sincronizado!';
                if (status) {
                    status.textContent = r.msg;
                    status.style.color  = r.inseridos > 0 ? '#2e7d32' : '#888';
                    status.style.display = 'block';
                }
                if (r.inseridos > 0) {
                    setTimeout(function(){ location.reload(); }, 2000);
                }
            } else {
                btn.className = 'btn btn-danger btn-block btn-sm';
                btn.innerHTML = '<i class="fa fa-exclamation-triangle"></i> Erro';
                if (status) {
                    status.textContent  = r.msg;
                    status.style.color  = '#c0392b';
                    status.style.display = 'block';
                }
                setTimeout(function(){
                    btn.className = 'btn btn-primary btn-block btn-sm';
                    btn.innerHTML = '<i class="fa fa-refresh"></i> Sincronizar com DataJud';
                }, 4000);
            }
        } catch(e) {
            btn.disabled = false;
            btn.className = 'btn btn-primary btn-block btn-sm';
            btn.innerHTML = '<i class="fa fa-refresh"></i> Sincronizar com DataJud';
            if (status) { status.textContent = 'Erro ao processar resposta.'; status.style.display = 'block'; }
        }
    };

    xhr.onerror = xhr.ontimeout = function() {
        btn.disabled = false;
        btn.className = 'btn btn-warning btn-block btn-sm';
        btn.innerHTML = '<i class="fa fa-refresh"></i> Sincronizar com DataJud';
        if (status) {
            status.textContent = 'Timeout — tente novamente.';
            status.style.color = '#d35400';
            status.style.display = 'block';
        }
    };

    xhr.send();
}
</script>
