<style>
.table > tbody > tr:hover { background-color: #f8fffe !important; }
.table > tbody > tr       { border-color: #f1f3f5; }
.btn:focus { box-shadow: none; }

/* ─── PAGE HEADER ─────────────────── */
.ar-page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 14px;
  margin-bottom: 24px;
}
.ar-header-left h4 {
  font-size: 1.25rem;
  font-weight: 800;
  color: #0b5a52;
  margin: 0 0 5px;
  display: flex;
  align-items: center;
  gap: 11px;
  letter-spacing: -.3px;
}
.ar-header-left h4 .hi {
  width: 40px; height: 40px;
  border-radius: 11px;
  background: linear-gradient(135deg, #0d9488, #14b8a6);
  display: flex; align-items: center; justify-content: center;
  color: #fff; font-size: 1.05rem;
  box-shadow: 0 4px 12px rgba(13,148,136,0.32);
  flex-shrink: 0;
}
.ar-breadcrumb {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.77rem;
  color: #94a3b8;
  padding-left: 51px;
}
.ar-breadcrumb a { color: #0d9488; text-decoration: none; font-weight: 600; }
.ar-breadcrumb a:hover { text-decoration: underline; }
.ar-breadcrumb .sep { color: #e2e8f0; }

.btn-tambah {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 10px 24px;
  border-radius: 50px;
  border: none;
  background: #0d9488;
  color: #fff;
  font-size: 0.85rem;
  font-weight: 700;
  text-decoration: none;
  box-shadow: 0 3px 12px rgba(13,148,136,0.28);
  transition: all .2s;
  white-space: nowrap;
  cursor: pointer;
}
.btn-tambah:hover {
  background: #0b7a6e;
  box-shadow: 0 5px 16px rgba(13,148,136,0.38);
  transform: translateY(-1px);
  color: #fff;
}

@media (max-width: 767.98px) {
  .ar-page-header { flex-direction: column; align-items: flex-start; }
  .btn-tambah { width: 100%; justify-content: center; }
}
</style>

<?php
/**
 * Helper: ubah HTML dari Quill menjadi plain text bersih
 */
function quill_to_plain($html, $limit = 0) {
    $plain = preg_replace('/<\/(p|div|li|h[1-6]|blockquote|tr|td|th)>/i', ' ', $html);
    $plain = preg_replace('/<br\s*\/?>/i', ' ', $plain);
    $plain = strip_tags($plain);
    $plain = html_entity_decode($plain, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $plain = preg_replace('/\s+/', ' ', trim($plain));

    if ($limit > 0 && mb_strlen($plain) > $limit) {
        return mb_substr($plain, 0, $limit) . '...';
    }
    return $plain;
}
?>

<!-- Header -->
<div class="ar-page-header">
    <div class="ar-header-left">
        <h4>
            <span class="hi"><i class="bi bi-megaphone-fill"></i></span>
            Pengumuman
        </h4>
        <div class="ar-breadcrumb">
            <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
            <span class="sep">/</span>
            <span>Pengumuman</span>
        </div>
    </div>
    <?php if($is_admin): ?>
    <a href="<?php echo base_url('pengumuman/tambah'); ?>" class="btn-tambah">
        <i class="bi bi-plus-lg"></i> Buat Pengumuman
    </a>
    <?php endif; ?>
</div>

<!-- Filter -->
<div class="card border-0 shadow-sm mb-4" style="border-radius:12px;">
    <div class="card-body py-3">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-md-3">
                <label class="form-label small fw-semibold text-muted mb-1">Kategori</label>
                <select name="kategori" class="form-select form-select-sm" style="border-radius:8px;">
                    <option value="">Semua Kategori</option>
                    <option value="umum"       <?php echo ($kategori_filter=='umum')       ? 'selected' : ''; ?>>📢 Umum</option>
                    <option value="kegiatan"   <?php echo ($kategori_filter=='kegiatan')   ? 'selected' : ''; ?>>🎉 Kegiatan</option>
                    <option value="darurat"    <?php echo ($kategori_filter=='darurat')    ? 'selected' : ''; ?>>🚨 Darurat</option>
                    <option value="pembayaran" <?php echo ($kategori_filter=='pembayaran') ? 'selected' : ''; ?>>💰 Pembayaran</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-semibold text-muted mb-1">Bulan</label>
                <select name="bulan" class="form-select form-select-sm" style="border-radius:8px;">
                    <option value="">Semua</option>
                    <?php for($i=1; $i<=12; $i++): ?>
                    <option value="<?php echo $i; ?>" <?php echo ($bulan_filter==$i) ? 'selected' : ''; ?>>
                        <?php echo date('F', mktime(0,0,0,$i,1)); ?>
                    </option>
                    <?php endfor; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-semibold text-muted mb-1">Tahun</label>
                <select name="tahun" class="form-select form-select-sm" style="border-radius:8px;">
                    <option value="">Semua</option>
                    <?php foreach($tahun_list as $thn): ?>
                    <option value="<?php echo $thn; ?>" <?php echo ($tahun_filter==$thn) ? 'selected' : ''; ?>><?php echo $thn; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-sm w-100 fw-semibold text-white" style="background:#20c997; border:none; border-radius:8px; padding:7px;">
                    <i class="bi bi-funnel me-1"></i>Filter
                </button>
            </div>
            <?php if($kategori_filter || $bulan_filter || $tahun_filter): ?>
            <div class="col-md-2">
                <a href="<?php echo base_url('pengumuman'); ?>" class="btn btn-sm w-100 btn-outline-secondary fw-semibold" style="border-radius:8px; padding:7px;">
                    <i class="bi bi-x-circle me-1"></i>Reset
                </a>
            </div>
            <?php endif; ?>
        </form>
    </div>
</div>

<?php if(!empty($pengumuman)): 
    $badge_map = [
        'umum'       => ['📢', '#20c997'],
        'kegiatan'   => ['🎉', '#198754'],
        'darurat'    => ['🚨', '#dc3545'],
        'pembayaran' => ['💰', '#ffc107'],
    ];

    // TOP 2 sebagai card penuh, sisanya tabel
    $top2    = array_slice($pengumuman, 0, 2);
    $therest = array_slice($pengumuman, 2);
    $cols    = count($top2) == 1 ? '12' : '6';
?>

<!-- ===== TOP 2 FULL CARDS ===== -->
<?php if(!empty($top2)): ?>
<div class="row g-3 mb-4">
    <?php foreach($top2 as $p):
        $badge = $badge_map[$p->kategori] ?? ['📌','#6c757d'];
        $hex   = $badge[1];
    ?>
    <div class="col-md-<?php echo $cols; ?>">
        <div class="card border-0 shadow-sm h-100" style="border-radius:14px; overflow:hidden; border-top:4px solid <?php echo $hex; ?> !important;">
            <div class="card-body p-4">

                <!-- Badge + Status -->
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <span class="badge rounded-pill px-3 py-1 fw-semibold" style="background:<?php echo $hex; ?>20; color:<?php echo $hex; ?>; border:1px solid <?php echo $hex; ?>40; font-size:0.8em;">
                        <?php echo $badge[0]; ?> <?php echo ucfirst($p->kategori); ?>
                    </span>
                    <?php if($is_admin): ?>
                    <?php
                    $s_bg  = $p->status == 'publish' ? '#19875420' : '#6c757d20';
                    $s_col = $p->status == 'publish' ? '#198754'   : '#6c757d';
                    $s_bdr = $p->status == 'publish' ? '#19875440' : '#6c757d40';
                    ?>
                    <span class="badge rounded-pill px-2 py-1 small"
                          style="background:<?php echo $s_bg; ?>; color:<?php echo $s_col; ?>; border:1px solid <?php echo $s_bdr; ?>;">
                        <?php echo ucfirst($p->status); ?>
                    </span>
                    <?php endif; ?>
                </div>

                <!-- Judul -->
                <h5 class="fw-bold text-dark mb-2"><?php echo htmlspecialchars($p->judul); ?></h5>

                <!-- Preview Isi (plain text, maks 200 karakter) -->
                <div class="text-muted small mb-3" style="line-height:1.75;">
                    <?php echo quill_to_plain($p->isi, 200); ?>
                </div>

                <?php if($p->lampiran): ?>
                <div class="mb-3">
                    <a href="<?php echo base_url('uploads/pengumuman/'.$p->lampiran); ?>" target="_blank"
                       class="badge bg-light text-dark border text-decoration-none" style="font-size:0.8em;">
                        <i class="bi bi-paperclip me-1"></i>Lihat Lampiran
                    </a>
                </div>
                <?php endif; ?>

                <!-- Footer Card -->
                <div class="d-flex align-items-center justify-content-between pt-3" style="border-top:1px solid #f1f3f5;">
                    <div class="text-muted small">
                        <i class="bi bi-calendar3 me-1"></i><?php echo date('d M Y', strtotime($p->tanggal_publish)); ?>
                        <span class="mx-1">·</span>
                        <i class="bi bi-person me-1"></i><?php echo htmlspecialchars($p->pembuat); ?>
                    </div>
                    <div class="d-flex gap-1">
                        <a href="<?php echo base_url('pengumuman/detail/'.$p->id); ?>"
                           class="btn btn-sm px-3 fw-semibold text-white"
                           style="background:<?php echo $hex; ?>; border:none; border-radius:7px; font-size:0.8em;">
                            <i class="bi bi-eye me-1"></i>Detail
                        </a>
                        <?php if($is_admin): ?>
                        <a href="<?php echo base_url('pengumuman/edit/'.$p->id); ?>"
                           class="btn btn-sm btn-outline-warning px-2"
                           style="border-radius:7px; font-size:0.8em;">
                            <i class="bi bi-pencil"></i>
                        </a>

                        <button class="btn btn-sm btn-outline-danger px-2"
   style="border-radius:7px; font-size:0.8em;"
   onclick="konfirmasiHapusPengumuman('<?php echo base_url('pengumuman/hapus/'.$p->id); ?>','<?php echo addslashes($p->judul); ?>')">
    <i class="bi bi-trash"></i>
</button>
                        <!-- Tombol Sebar WA (WAHA) -->
                        <button class="btn btn-sm px-2 btn-sebar-wa"
                                style="background:#25d366;color:#fff;border:none;border-radius:7px;font-size:0.8em;"
                                data-id="<?php echo $p->id; ?>"
                                data-judul="<?php echo htmlspecialchars(addslashes($p->judul)); ?>"
                                title="Sebar via WhatsApp WAHA">
                            <i class="bi bi-whatsapp"></i> Sebar WA
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<!-- ===== SISANYA: TABEL ===== -->
<?php if(!empty($therest)): ?>
<div class="d-flex align-items-center mb-3">
    <span class="fw-semibold text-muted small text-uppercase" style="letter-spacing:.05em;">Pengumuman Lainnya</span>
    <div class="flex-grow-1 ms-3" style="height:1px; background:#e9ecef;"></div>
</div>

<div class="card border-0 shadow-sm" style="border-radius:12px; overflow:hidden;">
    <div class="card-body p-0">
        <table class="table table-hover align-middle mb-0">
            <thead>
                <tr style="background:#f8fffe; border-bottom:2px solid #e9ecef;">
                    <th class="ps-4 py-3 text-muted small fw-semibold" style="width:40px;">#</th>
                    <th class="py-3 text-muted small fw-semibold">JUDUL</th>
                    <th class="py-3 text-muted small fw-semibold">KATEGORI</th>
                    <th class="py-3 text-muted small fw-semibold">TANGGAL</th>
                    <th class="py-3 text-muted small fw-semibold">PEMBUAT</th>
                    <?php if($is_admin): ?>
                    <th class="py-3 text-muted small fw-semibold">STATUS</th>
                    <?php endif; ?>
                    <th class="py-3 text-muted small fw-semibold text-center" style="width:130px;">AKSI</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach($therest as $idx => $p):
                $badge = $badge_map[$p->kategori] ?? ['📌','#6c757d'];
                $hex   = $badge[1];
                $s_bg  = $p->status == 'publish' ? '#19875420' : '#6c757d20';
                $s_col = $p->status == 'publish' ? '#198754'   : '#6c757d';
                $s_bdr = $p->status == 'publish' ? '#19875440' : '#6c757d40';
            ?>
            <tr>
                <td class="ps-4 text-muted small"><?php echo $idx + 3; ?></td>
                <td>
                    <div class="fw-semibold text-dark" style="max-width:340px;">
                        <?php echo htmlspecialchars($p->judul); ?>
                    </div>
                    <small class="text-muted">
                        <?php echo quill_to_plain($p->isi, 75); ?>
                    </small>
                    <?php if($p->lampiran): ?>
                    <span class="badge bg-light text-dark border ms-1" style="font-size:0.7em;">
                        <i class="bi bi-paperclip"></i> Lampiran
                    </span>
                    <?php endif; ?>
                </td>
                <td>
                    <span class="badge rounded-pill px-3 py-1 fw-semibold"
                          style="background:<?php echo $hex; ?>20; color:<?php echo $hex; ?>; border:1px solid <?php echo $hex; ?>40; font-size:0.78em;">
                        <?php echo $badge[0]; ?> <?php echo ucfirst($p->kategori); ?>
                    </span>
                </td>
                <td class="text-muted small">
                    <i class="bi bi-calendar3 me-1"></i><?php echo date('d M Y', strtotime($p->tanggal_publish)); ?>
                </td>
                <td class="text-muted small">
                    <i class="bi bi-person me-1"></i><?php echo htmlspecialchars($p->pembuat); ?>
                </td>
                <?php if($is_admin): ?>
                <td>
                    <span class="badge rounded-pill px-2 py-1 small"
                          style="background:<?php echo $s_bg; ?>; color:<?php echo $s_col; ?>; border:1px solid <?php echo $s_bdr; ?>;">
                        <?php echo ucfirst($p->status); ?>
                    </span>
                </td>
                <?php endif; ?>
                <td class="text-center">
                    <a href="<?php echo base_url('pengumuman/detail/'.$p->id); ?>"
                       class="btn btn-sm px-2 text-white me-1"
                       style="background:<?php echo $hex; ?>; border:none; border-radius:7px; font-size:0.8em;">
                        <i class="bi bi-eye"></i>
                    </a>
                    <?php if($is_admin): ?>
                    <a href="<?php echo base_url('pengumuman/edit/'.$p->id); ?>"
                       class="btn btn-sm btn-outline-warning px-2"
                       style="border-radius:7px; font-size:0.8em;">
                        <i class="bi bi-pencil"></i>
                    </a>
                    <button class="btn btn-sm btn-outline-danger px-2"
   style="border-radius:7px; font-size:0.8em;"
   onclick="konfirmasiHapusPengumuman('<?php echo base_url('pengumuman/hapus/'.$p->id); ?>','<?php echo addslashes($p->judul); ?>')">
    <i class="bi bi-trash"></i>
</button>
                    <!-- Tombol Sebar WA (WAHA) -->
                    <button class="btn btn-sm px-2 btn-sebar-wa"
                            style="background:#25d366;color:#fff;border:none;border-radius:7px;font-size:0.8em;"
                            data-id="<?php echo $p->id; ?>"
                            data-judul="<?php echo htmlspecialchars(addslashes($p->judul)); ?>"
                            title="Sebar via WhatsApp WAHA">
                        <i class="bi bi-whatsapp"></i>
                    </button>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php else: ?>
<!-- Empty State -->
<div class="card border-0 shadow-sm text-center py-5" style="border-radius:12px;">
    <div class="card-body">
        <div class="rounded-circle d-inline-flex align-items-center justify-content-center mb-3"
             style="width:80px; height:80px; background:#f0fdf9;">
            <i class="bi bi-megaphone fs-2" style="color:#20c997;"></i>
        </div>
        <h6 class="text-muted fw-semibold">Belum ada pengumuman</h6>
        <p class="text-muted small mb-0">Pengumuman baru akan muncul di sini</p>
    </div>
</div>
<?php endif; ?>

<!-- Modal Konfirmasi Hapus Pengumuman -->
<div class="modal fade" id="modalHapusPengumuman" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" style="max-width:400px;">
    <div class="modal-content" style="border-radius:16px;border:none;overflow:hidden;">
      <div class="modal-header" style="background:#fef2f2;border-bottom:1.5px solid #fecaca;padding:18px 20px;">
        <div class="d-flex align-items-center gap-2">
          <div style="width:36px;height:36px;background:#fee2e2;border-radius:10px;display:flex;align-items:center;justify-content:center;">
            <i class="bi bi-trash-fill" style="color:#dc2626;font-size:1rem;"></i>
          </div>
          <h6 class="modal-title mb-0 fw-bold" style="color:#991b1b;font-size:.95rem;">Hapus Pengumuman</h6>
        </div>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body" style="padding:20px;">
        <p style="font-size:.85rem;color:#334155;margin-bottom:10px;">Anda akan menghapus pengumuman:</p>
        <div style="background:#fef2f2;border:1.5px solid #fecaca;border-radius:10px;padding:12px 16px;display:flex;align-items:center;gap:10px;">
          <div style="width:34px;height:34px;border-radius:9px;background:#fee2e2;color:#dc2626;display:flex;align-items:center;justify-content:center;font-size:1.1rem;flex-shrink:0;">
            <i class="bi bi-megaphone-fill"></i>
          </div>
          <div style="font-weight:700;font-size:.88rem;color:#991b1b;line-height:1.3;" id="hapusPengumumanJudul">-</div>
        </div>
        <div style="background:#fffbeb;border:1.5px solid #fde68a;border-radius:8px;padding:9px 14px;margin-top:12px;font-size:.78rem;color:#92400e;">
          <i class="bi bi-exclamation-triangle-fill me-1"></i>
          Data akan <strong>terhapus permanen</strong> dan tidak dapat dikembalikan.
        </div>
      </div>
      <div class="modal-footer" style="border:none;padding:0 20px 18px;gap:8px;">
        <button type="button" class="btn" data-bs-dismiss="modal"
          style="border-radius:8px;border:1.5px solid #e5e7eb;font-size:.82rem;font-weight:600;color:#64748b;padding:7px 18px;flex:1;">
          <i class="bi bi-x-lg me-1"></i>Batal
        </button>
        <a href="#" id="btnKonfirmasiHapusPengumuman"
          style="border-radius:8px;border:none;font-size:.82rem;font-weight:700;color:#fff;padding:7px 18px;flex:1;background:linear-gradient(135deg,#dc2626,#ef4444);box-shadow:0 4px 12px rgba(220,38,38,.28);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:6px;text-decoration:none;">
          <i class="bi bi-trash-fill"></i>Ya, Hapus
        </a>
      </div>
    </div>
  </div>
</div>

<script>
var _bsModalHapusPengumuman = null;

function konfirmasiHapusPengumuman(url, judul) {
  var elJudul = document.getElementById('hapusPengumumanJudul');
  var elBtn   = document.getElementById('btnKonfirmasiHapusPengumuman');
  if(elJudul) elJudul.textContent = judul || '-';
  if(elBtn)   elBtn.href          = url;

  var modalEl = document.getElementById('modalHapusPengumuman');
  if(!modalEl) return;
  if(!_bsModalHapusPengumuman) _bsModalHapusPengumuman = new bootstrap.Modal(modalEl);
  _bsModalHapusPengumuman.show();
}

// ── Sebar Pengumuman via WAHA ──────────────────────────────────
document.querySelectorAll('.btn-sebar-wa').forEach(function(btn) {
    btn.addEventListener('click', function() {
        const id    = this.dataset.id;
        const judul = this.dataset.judul;
        const self  = this;

        if (!confirm('Sebar pengumuman "' + judul + '" ke semua warga via WhatsApp?')) return;

        self.disabled = true;
        const orig = self.innerHTML;
        self.innerHTML = '<i class="bi bi-hourglass-split"></i> Mengirim...';

        const fd = new FormData();
        fd.append('pengumuman_id', id);

        fetch('<?php echo base_url("pengumuman/sebar_wa"); ?>', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd,
        })
        .then(r => r.json())
        .then(data => {
            const tipe = data.kirim > 0 ? 'success' : 'warning';
            tampilToastWa(data.msg || 'Selesai', tipe);
            if (data.errors && data.errors.length) {
                console.warn('WAHA errors:', data.errors);
            }
        })
        .catch(e => tampilToastWa('Error: ' + e.message, 'danger'))
        .finally(() => {
            self.disabled = false;
            self.innerHTML = orig;
        });
    });
});

function tampilToastWa(msg, tipe) {
    const div = document.createElement('div');
    div.className = 'alert alert-' + tipe + ' alert-dismissible fade show';
    div.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;min-width:280px;border-radius:12px;font-size:.85rem;box-shadow:0 4px 20px rgba(0,0,0,.15);';
    div.innerHTML = '<i class="bi bi-whatsapp me-2"></i>' + msg +
        '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
    document.body.appendChild(div);
    setTimeout(() => { div.classList.remove('show'); setTimeout(() => div.remove(), 400); }, 5000);
}
</script>