<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
/* ── Base ───────────────────────────────────────── */
.content-header {
    background:linear-gradient(135deg,#0f2027,#203a43,#2c5364);
    padding:18px 20px !important; margin-bottom:0;
}
.content-header h1 { color:#fff !important; margin:0; font-size:20px; font-weight:700; }
.content-header h1 small { color:rgba(255,255,255,.6) !important; font-size:12px; }
.content-header .breadcrumb { background:transparent !important; margin:5px 0 0; padding:0; }
.content-header .breadcrumb li,
.content-header .breadcrumb li a { color:rgba(255,255,255,.6); font-size:12px; }
.content-header .breadcrumb li.active { color:rgba(255,255,255,.9); }
.content-header .breadcrumb > li+li:before { color:rgba(255,255,255,.3); }

/* ── Barra ações ────────────────────────────────── */
.action-bar {
    background:linear-gradient(135deg,#2c5364,#203a43);
    padding:10px 20px; display:flex; align-items:center;
    flex-wrap:wrap; gap:8px; margin-bottom:0;
}
.action-bar .btn-sync {
    background:rgba(255,255,255,.15); color:#fff;
    border:1px solid rgba(255,255,255,.3); border-radius:20px;
    padding:5px 16px; font-size:12px; font-weight:600; cursor:pointer;
    transition:background .2s;
}
.action-bar .btn-sync:hover { background:rgba(255,255,255,.25); }
.action-bar .btn-link-sm {
    color:rgba(255,255,255,.75); font-size:12px; text-decoration:none;
    padding:5px 12px; border:1px solid rgba(255,255,255,.2); border-radius:20px;
    transition:all .2s;
}
.action-bar .btn-link-sm:hover { background:rgba(255,255,255,.15); color:#fff; }

/* ── KPI cards ──────────────────────────────────── */
.kpi-row { display:flex; gap:12px; padding:16px 20px; flex-wrap:wrap; background:#f0f2f5; }
.kpi-card {
    flex:1; min-width:120px; border-radius:12px; padding:14px 16px;
    color:#fff; position:relative; overflow:hidden;
    box-shadow:0 3px 12px rgba(0,0,0,.15); transition:transform .2s;
}
.kpi-card:hover { transform:translateY(-2px); }
.kpi-card .kn { font-size:26px; font-weight:700; line-height:1; }
.kpi-card .kl { font-size:10px; opacity:.8; text-transform:uppercase; letter-spacing:.8px; margin-top:4px; }
.kpi-card .ki { position:absolute; right:10px; top:50%; transform:translateY(-50%); font-size:40px; opacity:.12; }

/* ── Filter bar ─────────────────────────────────── */
.filter-wrap { background:#fff; border-bottom:1px solid #e8ecf0; padding:12px 20px; }
.filter-wrap .filter-grid {
    display:grid;
    grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
    gap:8px; align-items:end;
}
.filter-wrap label { font-size:10px; font-weight:700; color:#888; text-transform:uppercase; letter-spacing:.6px; display:block; margin-bottom:3px; }
.filter-wrap .form-control { height:32px; font-size:12px; border-radius:6px; border:1px solid #dde1e7; }
.filter-wrap .btn-filtrar { background:#1F4E79; color:#fff; border:none; border-radius:6px; height:32px; padding:0 16px; font-size:12px; font-weight:600; white-space:nowrap; }
.filter-wrap .btn-clear { background:#f0f2f5; color:#666; border:1px solid #dde1e7; border-radius:6px; height:32px; padding:0 12px; font-size:12px; white-space:nowrap; text-decoration:none; display:inline-flex; align-items:center; }

/* ── Alerta sync ────────────────────────────────── */
#alertaSync { margin:0 20px 0; border-radius:8px; }

/* ── Tabela ─────────────────────────────────────── */
.pub-table-wrap { background:#fff; border-radius:0 0 12px 12px; overflow:hidden; }
.pub-table { width:100%; border-collapse:collapse; }
.pub-table thead th {
    background:#f5f7fa; font-size:10px; font-weight:700; color:#888;
    padding:10px 14px; text-transform:uppercase; letter-spacing:.6px;
    border-bottom:2px solid #e8ecf0; white-space:nowrap;
}
.pub-table tbody tr { border-bottom:1px solid #f0f2f5; transition:background .1s; }
.pub-table tbody tr:hover { background:#f8f9ff; }
.pub-table tbody td { padding:10px 14px; vertical-align:middle; }
.pub-table tbody tr.unread { border-left:3px solid #C55A11; background:#fffbf5; }
.pub-table tbody tr.unread td:first-child { padding-left:11px; }

/* ── Badges ─────────────────────────────────────── */
.tribunal-badge { display:inline-block; padding:2px 8px; border-radius:4px; font-size:10px; font-weight:800; background:#1F4E79; color:#fff; letter-spacing:.5px; }
.tipo-badge { display:inline-block; padding:2px 7px; border-radius:10px; font-size:10px; font-weight:600; background:#e8f0fe; color:#1F4E79; }
.unread-dot { width:8px; height:8px; border-radius:50%; background:#C00000; display:inline-block; }
.read-dot   { width:8px; height:8px; border-radius:50%; background:#ddd; display:inline-block; }

/* ── Processo mono ──────────────────────────────── */
.proc-code { font-family:monospace; font-size:12px; color:#333; font-weight:600; }

/* ── Preview texto ──────────────────────────────── */
.pub-preview { font-size:12px; color:#666; overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; max-width:350px; }
.pub-title { font-size:13px; font-weight:600; color:#222; margin-bottom:2px; }
.pub-title.read { font-weight:400; color:#555; }

/* ── Data publicação ────────────────────────────── */
.data-pub { font-size:12px; color:#555; white-space:nowrap; }
.data-disp { font-size:10px; color:#aaa; white-space:nowrap; }

/* ── Ações ──────────────────────────────────────── */
.act-btn { display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; border-radius:6px; font-size:13px; border:none; cursor:pointer; transition:all .15s; }
.act-btn.view   { background:#e8f0fe; color:#1F4E79; }
.act-btn.ext    { background:#f0f0f0; color:#555; }
.act-btn.check  { background:#e8f5e9; color:#1D6B3B; }
.act-btn:hover  { filter:brightness(.9); }

/* ── Empty state ────────────────────────────────── */
.empty-state { padding:50px 20px; text-align:center; color:#aaa; }
.empty-state i { font-size:48px; opacity:.25; display:block; margin-bottom:12px; }

/* ── Paginação ──────────────────────────────────── */
.pag-footer { padding:12px 20px; display:flex; justify-content:space-between; align-items:center; background:#fafafa; border-top:1px solid #f0f0f0; flex-wrap:wrap; gap:8px; }
.pagination { margin:0; }
.pagination li a, .pagination li span { border-radius:6px !important; margin:0 2px; font-size:12px; }

/* ── MOBILE ─────────────────────────────────────── */
@media (max-width: 768px) {
    .content-header { padding:14px 14px !important; }
    .content-header h1 { font-size:17px; }
    .kpi-row { padding:12px; gap:8px; }
    .kpi-card { min-width:calc(50% - 4px); padding:12px; }
    .kpi-card .kn { font-size:22px; }
    .filter-wrap { padding:10px 14px; }
    .filter-wrap .filter-grid { grid-template-columns:1fr 1fr; }
    .action-bar { padding:8px 14px; }

    /* Tabela vira cards no mobile */
    .pub-table thead { display:none; }
    .pub-table tbody tr { display:block; margin:8px 14px; border-radius:10px; border:1px solid #e8ecf0; border-left:3px solid #ddd; box-shadow:0 1px 6px rgba(0,0,0,.06); }
    .pub-table tbody tr.unread { border-left:3px solid #C55A11; }
    .pub-table tbody td { display:block; padding:6px 12px; border:none; font-size:13px; }
    .pub-table tbody td:before { content:attr(data-label); font-size:10px; font-weight:700; color:#aaa; text-transform:uppercase; display:block; margin-bottom:2px; }
    .pub-table tbody td[data-label=""] { padding-top:10px; }
    .pub-table tbody td:last-child { padding-bottom:10px; }
    .pub-preview { max-width:100%; -webkit-line-clamp:3; }
    .col-hide-mobile { display:none; }
    .pag-footer { justify-content:center; }
}
</style>

<!-- HEADER -->
<section class="content-header">
    <h1>
        <i class="fa fa-newspaper-o"></i> Diário Oficial PJe
        <?php if (isset($nao_lidas) && $nao_lidas > 0): ?>
        <span style="background:#C00000;color:#fff;font-size:11px;border-radius:10px;padding:2px 8px;margin-left:6px;vertical-align:middle"><?php echo $nao_lidas ?> não lidas</span>
        <?php endif; ?>
    </h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li class="active">Diário PJe</li>
    </ol>
</section>

<!-- BARRA DE AÇÕES -->
<div class="action-bar">
    <button id="btnSync" class="btn-sync" onclick="sincronizar(); return false;">
        <i class="fa fa-refresh" id="iconSync"></i> Sincronizar Agora
    </button>
    <?php if ($access == 1): ?>
    <a href="<?php echo site_url('admin/diario_oficial/advogados') ?>" class="btn-link-sm">
        <i class="fa fa-users"></i> Advogados
    </a>
    <?php endif; ?>
    <?php if ($nao_lidas > 0): ?>
    <form style="display:inline;margin:0" method="post" action="<?php echo site_url('admin/diario_oficial/marcar_todas_lidas') ?>">
        <input type="hidden" name="adv_id" value="<?php echo $filters['f_adv'] ?>">
        <button type="submit" class="btn-link-sm" style="border:1px solid rgba(255,255,255,.2)">
            <i class="fa fa-check-square-o"></i> Marcar todas lidas
        </button>
    </form>
    <?php endif; ?>
    <span style="color:rgba(255,255,255,.4);font-size:11px;margin-left:auto"><?php echo $total ?> publicação(ões) no período</span>
</div>

<!-- ALERTA SYNC -->
<div id="alertaSync" class="alert" style="display:none;margin:10px 20px 0;border-radius:8px"></div>

<!-- KPIs -->
<div class="kpi-row">
    <div class="kpi-card" style="background:linear-gradient(135deg,#1F4E79,#2E75B6)">
        <div class="kn"><?php echo $total ?></div>
        <div class="kl">Total período</div>
        <i class="fa fa-newspaper-o ki"></i>
    </div>
    <div class="kpi-card" style="background:linear-gradient(135deg,#C00000,#e74c3c)">
        <div class="kn"><?php echo $nao_lidas ?></div>
        <div class="kl">Não lidas</div>
        <i class="fa fa-envelope ki"></i>
    </div>
    <div class="kpi-card" style="background:linear-gradient(135deg,#1D6B3B,#27ae60)">
        <div class="kn"><?php echo $total - $nao_lidas ?></div>
        <div class="kl">Lidas</div>
        <i class="fa fa-check-circle ki"></i>
    </div>
    <div class="kpi-card" style="background:linear-gradient(135deg,#7F6000,#C55A11)">
        <div class="kn"><?php echo count($advogados) ?></div>
        <div class="kl">Advogados</div>
        <i class="fa fa-users ki"></i>
    </div>
</div>

<!-- FILTROS -->
<div class="filter-wrap">
    <form method="get" action="<?php echo site_url('admin/diario_oficial') ?>">
    <div class="filter-grid">
        <div>
            <label>De</label>
            <input type="date" name="dt_ini" class="form-control" value="<?php echo $filters['f_dt_ini'] ?>">
        </div>
        <div>
            <label>Até</label>
            <input type="date" name="dt_fim" class="form-control" value="<?php echo $filters['f_dt_fim'] ?>">
        </div>
        <?php if ($access == 1): ?>
        <div>
            <label>Advogado</label>
            <select name="adv_id" class="form-control">
                <option value="">Todos</option>
                <?php foreach ($advogados as $adv): ?>
                <option value="<?php echo $adv->id ?>" <?php echo $filters['f_adv'] == $adv->id ? 'selected' : '' ?>>
                    <?php echo $adv->nome ?> (<?php echo $adv->oab ?>/<?php echo $adv->uf_oab ?>)
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        <div>
            <label>Tribunal</label>
            <select name="tribunal" class="form-control">
                <option value="">Todos</option>
                <?php foreach ($tribunais as $t): ?>
                <option value="<?php echo $t ?>" <?php echo $filters['f_tribunal'] == $t ? 'selected' : '' ?>><?php echo $t ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>Status</label>
            <select name="lida" class="form-control">
                <option value="">Todas</option>
                <option value="0" <?php echo $filters['f_lida'] === '0' ? 'selected' : '' ?>>Não lidas</option>
                <option value="1" <?php echo $filters['f_lida'] === '1' ? 'selected' : '' ?>>Lidas</option>
            </select>
        </div>
        <div style="grid-column:span 2">
            <label>Buscar processo ou texto</label>
            <input type="text" name="busca" class="form-control" placeholder="Número do processo ou palavra..." value="<?php echo htmlspecialchars($filters['f_busca'] ?: '') ?>">
        </div>
        <div style="display:flex;gap:6px;align-items:flex-end">
            <button type="submit" class="btn-filtrar"><i class="fa fa-search"></i> Filtrar</button>
            <a href="<?php echo site_url('admin/diario_oficial') ?>" class="btn-clear"><i class="fa fa-times"></i> Limpar</a>
        </div>
    </div>
    </form>
</div>

<section class="content" style="padding:16px">

<?php if ($this->session->flashdata('message')): ?>
<div class="alert alert-success alert-dismissible" style="border-radius:8px">
    <button class="close" data-dismiss="alert">&times;</button>
    <?php echo $this->session->flashdata('message') ?>
</div>
<?php endif; ?>

<!-- TABELA / CARDS -->
<div class="box" style="border-radius:12px;box-shadow:0 2px 14px rgba(0,0,0,.08);margin-bottom:0">
<div class="pub-table-wrap">
    <?php if (empty($publicacoes)): ?>
    <div class="empty-state">
        <i class="fa fa-newspaper-o"></i>
        Nenhuma publicação encontrada.<br>
        <small>Ajuste os filtros ou use <strong>Sincronizar Agora</strong>.</small>
    </div>
    <?php else: ?>
    <table class="pub-table">
        <thead>
            <tr>
                <th style="width:12px"></th>
                <th>Data Pub. / Disp.</th>
                <th>Tribunal</th>
                <?php if ($access == 1): ?><th class="col-hide-mobile">Advogado</th><?php endif; ?>
                <th>Processo</th>
                <th>Publicação</th>
                <th class="col-hide-mobile">Tipo</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($publicacoes as $p): ?>
        <tr class="<?php echo $p->lida ? '' : 'unread' ?>" id="row-<?php echo $p->id ?>">
            <td data-label="">
                <?php if (!$p->lida): ?>
                <span class="unread-dot" title="Não lida"></span>
                <?php else: ?>
                <span class="read-dot"></span>
                <?php endif; ?>
            </td>
            <td data-label="Data">
                <div class="data-pub">
                    <strong><?php echo $p->data_publicacao ? date('d/m/Y', strtotime($p->data_publicacao)) : '—' ?></strong>
                </div>
                <?php
                // Tenta pegar data de disponibilização do conteúdo
                $data_disp = '';
                if (!empty($p->conteudo)) {
                    preg_match('/Data de Disponibiliza[çc][ãa]o[:\s]+([0-9]{2}\/[0-9]{2}\/[0-9]{4})/i', $p->conteudo, $m);
                    if (!empty($m[1])) $data_disp = 'Disp.: ' . $m[1];
                }
                ?>
                <?php if ($data_disp): ?>
                <div class="data-disp"><?php echo $data_disp ?></div>
                <?php endif; ?>
            </td>
            <td data-label="Tribunal">
                <?php if ($p->tribunal): ?>
                <span class="tribunal-badge"><?php echo $p->tribunal ?></span>
                <?php endif; ?>
            </td>
            <?php if ($access == 1): ?>
            <td class="col-hide-mobile" data-label="Advogado">
                <small style="font-size:12px"><strong><?php echo $p->adv_nome ?></strong></small><br>
                <small class="text-muted">OAB <?php echo $p->oab ?>/<?php echo $p->uf_oab ?></small>
            </td>
            <?php endif; ?>
            <td data-label="Processo">
                <span class="proc-code"><?php echo $p->processo_mascara ?: $p->numero_processo ?: '—' ?></span>
                <?php if ($p->orgao): ?>
                <br><small style="font-size:10px;color:#aaa"><i class="fa fa-building-o"></i> <?php echo htmlspecialchars(mb_substr($p->orgao, 0, 40)) ?></small>
                <?php endif; ?>
            </td>
            <td data-label="Publicação">
                <div class="pub-title <?php echo $p->lida ? 'read' : '' ?>">
                    <?php echo htmlspecialchars($p->titulo ?: 'Publicação PJe') ?>
                </div>
                <div class="pub-preview"><?php echo htmlspecialchars(mb_substr(strip_tags($p->conteudo ?? ''), 0, 120)) ?></div>
            </td>
            <td class="col-hide-mobile" data-label="Tipo">
                <?php if ($p->tipo_comunicacao): ?>
                <span class="tipo-badge"><?php echo htmlspecialchars($p->tipo_comunicacao) ?></span>
                <?php endif; ?>
            </td>
            <td data-label="Ações" style="white-space:nowrap">
                <a href="<?php echo site_url('admin/diario_oficial/view/' . $p->id) ?>" class="act-btn view" title="Ver detalhes"><i class="fa fa-eye"></i></a>
                <?php if ($p->link): ?>
                <a href="<?php echo $p->link ?>" target="_blank" class="act-btn ext" title="Abrir no PJe"><i class="fa fa-external-link"></i></a>
                <?php endif; ?>
                <?php if (!$p->lida): ?>
                <button class="act-btn check btn-marcar-lida" data-id="<?php echo $p->id ?>" title="Marcar lida"><i class="fa fa-check"></i></button>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <?php if ($total > $per_page): ?>
    <div class="pag-footer">
        <?php
        $pages = ceil($total / $per_page);
        $base  = site_url('admin/diario_oficial') . '?' . http_build_query([
            'adv_id'   => $filters['f_adv'],
            'dt_ini'   => $filters['f_dt_ini'],
            'dt_fim'   => $filters['f_dt_fim'],
            'lida'     => $filters['f_lida'],
            'tribunal' => $filters['f_tribunal'],
            'busca'    => $filters['f_busca'],
        ]);
        ?>
        <ul class="pagination pagination-sm">
            <?php if ($page > 1): ?>
            <li><a href="<?php echo $base . '&page=' . ($page-1) ?>"><i class="fa fa-chevron-left"></i></a></li>
            <?php endif; ?>
            <?php for ($i = max(1,$page-2); $i <= min($pages,$page+2); $i++): ?>
            <li class="<?php echo $i == $page ? 'active' : '' ?>">
                <a href="<?php echo $base . '&page=' . $i ?>"><?php echo $i ?></a>
            </li>
            <?php endfor; ?>
            <?php if ($page < $pages): ?>
            <li><a href="<?php echo $base . '&page=' . ($page+1) ?>"><i class="fa fa-chevron-right"></i></a></li>
            <?php endif; ?>
        </ul>
        <small class="text-muted"><?php echo $total ?> publicações — página <?php echo $page ?> de <?php echo $pages ?></small>
    </div>
    <?php endif; ?>
</div>
</div>
</section>

<script>
$(document).on('click', '.btn-marcar-lida', function () {
    var btn = $(this), id = btn.data('id'), row = $('#row-' + id);
    $.post('<?php echo site_url("admin/diario_oficial/marcar_lida_ajax") ?>', {id: id}, function (r) {
        if (r.success) {
            row.removeClass('unread');
            row.find('.unread-dot').removeClass('unread-dot').addClass('read-dot');
            btn.remove();
        }
    }, 'json');
});

function sincronizar() {
    var btn = document.getElementById('btnSync');
    var icon = document.getElementById('iconSync');
    var alerta = document.getElementById('alertaSync');
    btn.disabled = true;
    icon.className = 'fa fa-refresh fa-spin';
    alerta.className = 'alert alert-info';
    alerta.textContent = 'Sincronizando com o e-mail... aguarde.';
    alerta.style.display = 'block';
    fetch('<?php echo site_url("admin/diario_oficial/sincronizar") ?>')
        .then(function(r){ return r.json(); })
        .then(function(d){
            btn.disabled = false;
            icon.className = 'fa fa-refresh';
            alerta.className = d.ok ? 'alert alert-success' : 'alert alert-danger';
            alerta.textContent = d.msg;
            if (d.ok && d.enviados > 0) setTimeout(function(){ location.reload(); }, 2000);
        })
        .catch(function(e){
            btn.disabled = false;
            icon.className = 'fa fa-refresh';
            alerta.className = 'alert alert-danger';
            alerta.textContent = 'Erro de conexão: ' + e;
        });
}
</script>
