<?php defined('BASEPATH') OR exit('No direct script access allowed');

// ── Helper shortcut sebutan (agar kode view lebih ringkas) ───────────
$sbt_rt      = htmlspecialchars($pengaturan->sebutan_rt          ?? 'RT');
$sbt_rw      = htmlspecialchars($pengaturan->sebutan_rw          ?? 'RW');
$sbt_krt     = htmlspecialchars($pengaturan->sebutan_ketua_rt    ?? 'Ketua RT');
$sbt_sek     = htmlspecialchars($pengaturan->sebutan_sekretaris  ?? 'Sekretaris RT');
$sbt_ben     = htmlspecialchars($pengaturan->sebutan_bendahara   ?? 'Bendahara RT');
$sbt_krw     = htmlspecialchars($pengaturan->sebutan_ketua_rw   ?? 'Ketua RW');
$sbt_lurah   = htmlspecialchars($pengaturan->sebutan_lurah       ?? 'Lurah');
?>

<div>

    <!-- Header -->
    <div class="d-flex align-items-center justify-content-between mb-4">
        <div>
            <h4 class="mb-0 fw-bold text-dark">
                <i class="bi bi-gear-fill me-2" style="color:#20c997;"></i>Pengaturan
            </h4>
            <small class="text-muted">Kelola identitas <?php echo $sbt_rt; ?>, pengurus, peraturan, dan tampilan surat</small>
        </div>
    </div>

    <?php if($this->session->flashdata('success')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle me-2"></i><?php echo $this->session->flashdata('success'); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    <?php if($this->session->flashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle me-2"></i><?php echo $this->session->flashdata('error'); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- TAB NAVIGASI -->
    <ul class="nav nav-tabs mb-4" id="pengaturanTabs" role="tablist" style="border-bottom: 2px solid #e9ecef;">
        <li class="nav-item" role="presentation">
            <button class="nav-link <?php echo ($active_tab === 'pengaturan' || $active_tab !== 'peraturan' && $active_tab !== 'whatsapp') ? 'active' : ''; ?>"
                    id="tab-pengaturan" data-bs-toggle="tab" data-bs-target="#pane-pengaturan"
                    type="button" role="tab">
                <i class="bi bi-sliders me-1"></i>Pengaturan
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link <?php echo ($active_tab === 'struktur') ? 'active' : ''; ?>"
                    id="tab-struktur" data-bs-toggle="tab" data-bs-target="#pane-struktur"
                    type="button" role="tab">
                <i class="bi bi-diagram-3 me-1"></i>Struktur Organisasi
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link <?php echo ($active_tab === 'peraturan') ? 'active' : ''; ?>"
                    id="tab-peraturan" data-bs-toggle="tab" data-bs-target="#pane-peraturan"
                    type="button" role="tab">
                <i class="bi bi-file-text me-1"></i>Peraturan <?php echo $sbt_rt; ?>
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link <?php echo ($active_tab === 'whatsapp') ? 'active' : ''; ?>"
                    id="tab-whatsapp" data-bs-toggle="tab" data-bs-target="#pane-whatsapp"
                    type="button" role="tab">
                <i class="bi bi-whatsapp me-1" style="color:#25d366;"></i>WhatsApp
            </button>
        </li>
    </ul>

    <div class="tab-content" id="pengaturanTabsContent">

        <!-- ============================================================
             TAB 1 : PENGATURAN
        ============================================================ -->
        <div class="tab-pane fade <?php echo ($active_tab !== 'peraturan') ? 'show active' : ''; ?>"
             id="pane-pengaturan" role="tabpanel">

            <form action="<?php echo base_url('pengaturan/simpan'); ?>" method="post" enctype="multipart/form-data">
                <div class="row g-4">
                    <div class="col-lg-8">

                        <!-- ── IDENTITAS RT/RW ──────────────────────────────── -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-geo-alt-fill me-1" style="color:#20c997;"></i>
                                        Identitas <?php echo $sbt_rt; ?> / <?php echo $sbt_rw; ?>
                                    </span>
                                </div>
                                <div class="p-4">
                                    <div class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label small fw-semibold">Nama <?php echo $sbt_rt; ?> <span class="text-danger">*</span></label>
                                            <input type="text" name="nama_rt" class="form-control form-control-sm" value="<?php echo $pengaturan->nama_rt ?? 'RT 001'; ?>" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label small fw-semibold">Nama <?php echo $sbt_rw; ?> <span class="text-danger">*</span></label>
                                            <input type="text" name="nama_rw" class="form-control form-control-sm" value="<?php echo $pengaturan->nama_rw ?? 'RW 001'; ?>" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Kelurahan / Desa</label>
                                            <input type="text" name="nama_kelurahan" class="form-control form-control-sm" value="<?php echo $pengaturan->nama_kelurahan ?? ''; ?>">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Kecamatan</label>
                                            <input type="text" name="nama_kecamatan" class="form-control form-control-sm" value="<?php echo $pengaturan->nama_kecamatan ?? ''; ?>">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Kota / Kabupaten</label>
                                            <input type="text" name="nama_kota" class="form-control form-control-sm" value="<?php echo $pengaturan->nama_kota ?? ''; ?>">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Provinsi</label>
                                            <input type="text" name="nama_provinsi" class="form-control form-control-sm" value="<?php echo $pengaturan->nama_provinsi ?? ''; ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label small fw-semibold">Kode Pos</label>
                                            <input type="text" name="kode_pos" class="form-control form-control-sm" value="<?php echo $pengaturan->kode_pos ?? ''; ?>">
                                        </div>
                                        <div class="col-md-5">
                                            <label class="form-label small fw-semibold">No. Telepon</label>
                                            <input type="text" name="no_telp" class="form-control form-control-sm" value="<?php echo $pengaturan->no_telp ?? ''; ?>">
                                        </div>
                                        <div class="col-12">
                                            <label class="form-label small fw-semibold">Alamat Sekretariat</label>
                                            <textarea name="alamat_sekretariat" class="form-control form-control-sm" rows="2"><?php echo $pengaturan->alamat_sekretariat ?? ''; ?></textarea>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">
                                                <i class="bi bi-clock me-1" style="color:#20c997;"></i>
                                                Zona Waktu <span class="text-danger">*</span>
                                            </label>
                                            <select name="timezone" class="form-select form-select-sm">
                                                <?php foreach(indonesia_timezones() as $tz => $label): ?>
                                                <option value="<?php echo $tz; ?>" <?php echo (($pengaturan->timezone ?? 'Asia/Jakarta') == $tz) ? 'selected' : ''; ?>>
                                                    <?php echo $label; ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <small class="text-muted" style="font-size:.7rem;">
                                                <i class="bi bi-info-circle me-1"></i>Mempengaruhi semua pencatatan waktu di sistem
                                            </small>
                                        </div>
                                        <!-- Lokasi Cuaca -->
                                        <div class="col-md-7">
                                            <label class="form-label small fw-semibold">
                                                <i class="bi bi-cloud-sun-fill me-1" style="color:#0ea5e9;"></i>
                                                Lokasi Cuaca
                                            </label>
                                            <div class="input-group input-group-sm mb-1">
                                                <span class="input-group-text" style="background:#f0f9ff;border-color:#bae6fd;">
                                                    <i class="bi bi-search" style="color:#0ea5e9;"></i>
                                                </span>
                                                <input type="text" id="inputCariKota" class="form-control form-control-sm"
                                                       placeholder="Ketik nama kota/kecamatan..." autocomplete="off">
                                                <button class="btn btn-sm" type="button" id="btnCariKota"
                                                        style="background:#0ea5e9;color:#fff;border-color:#0ea5e9;">
                                                    <i class="bi bi-search me-1"></i>Cari
                                                </button>
                                            </div>
                                            <div id="hasilCariKota" style="display:none;border:1px solid #bae6fd;border-radius:8px;background:#fff;max-height:180px;overflow-y:auto;box-shadow:0 4px 12px rgba(0,0,0,.1);position:relative;z-index:999;"></div>
                                            <input type="hidden" name="cuaca_latitude"  id="cuaca_latitude"  value="<?php echo $pengaturan->cuaca_latitude  ?? ''; ?>">
                                            <input type="hidden" name="cuaca_longitude" id="cuaca_longitude" value="<?php echo $pengaturan->cuaca_longitude ?? ''; ?>">
                                            <input type="hidden" name="cuaca_kota"      id="cuaca_kota"      value="<?php echo $pengaturan->cuaca_kota      ?? ''; ?>">
                                            <div id="lokasiDipilih" class="mt-1" style="<?php echo empty($pengaturan->cuaca_kota) ? 'display:none;' : ''; ?>">
                                                <div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:6px 10px;font-size:.78rem;color:#166534;">
                                                    <i class="bi bi-geo-alt-fill me-1"></i>
                                                    <span id="namaLokasiDipilih"><?php echo $pengaturan->cuaca_kota ?? ''; ?></span>
                                                    &nbsp;|&nbsp;
                                                    <span style="font-family:monospace;font-size:.72rem;">
                                                        <?php echo $pengaturan->cuaca_latitude ?? ''; ?>, <?php echo $pengaturan->cuaca_longitude ?? ''; ?>
                                                    </span>
                                                    <button type="button" id="btnGantiLokasi" class="btn btn-sm btn-link p-0 ms-2" style="font-size:.72rem;color:#dc2626;">Ganti</button>
                                                </div>
                                            </div>
                                            <small class="text-muted" style="font-size:.7rem;">
                                                <i class="bi bi-info-circle me-1"></i>
                                                Powered by <strong>Open-Meteo</strong> — gratis, tanpa API key
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ── SEBUTAN JABATAN (BARU) ───────────────────────── -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-translate me-1" style="color:#20c997;"></i>Sebutan Jabatan
                                    </span>
                                    <small class="text-muted d-block mt-1" style="font-size:.73rem;text-transform:none;letter-spacing:0;">
                                        Sesuaikan penyebutan jabatan dengan kultur daerah Anda.
                                        Contoh: <em>Kepala Desa</em>, <em>Pak RT</em>, <em>Kepala Dusun</em>, <em>Koordinator Lingkungan</em>
                                    </small>
                                </div>
                                <div class="p-4">
                                    <div class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label small fw-semibold">Sebutan "RT"</label>
                                            <input type="text" name="sebutan_rt"
                                                   class="form-control form-control-sm sebutan-preview"
                                                   data-targets="prev_sbt_rt,prev_sbt_rt2,mini_sbt_rt"
                                                   value="<?php echo $pengaturan->sebutan_rt ?? 'RT'; ?>"
                                                   placeholder="RT" maxlength="50">
                                            <small class="text-muted" style="font-size:.7rem;">cth: RT, Lingkungan, Blok</small>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label small fw-semibold">Sebutan "RW"</label>
                                            <input type="text" name="sebutan_rw"
                                                   class="form-control form-control-sm sebutan-preview"
                                                   data-targets="prev_sbt_rw,prev_sbt_rw2,mini_sbt_rw"
                                                   value="<?php echo $pengaturan->sebutan_rw ?? 'RW'; ?>"
                                                   placeholder="RW" maxlength="50">
                                            <small class="text-muted" style="font-size:.7rem;">cth: RW, Dusun, Kawasan</small>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Sebutan "Ketua RT"</label>
                                            <input type="text" name="sebutan_ketua_rt"
                                                   class="form-control form-control-sm sebutan-preview"
                                                   data-targets="prev_sbt_krt,prev_sbt_krt2,mini_sbt_krt"
                                                   value="<?php echo $pengaturan->sebutan_ketua_rt ?? 'Ketua RT'; ?>"
                                                   placeholder="Ketua RT" maxlength="50">
                                            <small class="text-muted" style="font-size:.7rem;">cth: Ketua RT, Pak RT, Koordinator Lingkungan</small>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">Sebutan "Sekretaris RT"</label>
                                            <input type="text" name="sebutan_sekretaris"
                                                   class="form-control form-control-sm"
                                                   value="<?php echo $pengaturan->sebutan_sekretaris ?? 'Sekretaris RT'; ?>"
                                                   placeholder="Sekretaris RT" maxlength="50">
                                            <small class="text-muted" style="font-size:.7rem;">cth: Sekretaris RT, Notulis</small>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">Sebutan "Bendahara RT"</label>
                                            <input type="text" name="sebutan_bendahara"
                                                   class="form-control form-control-sm"
                                                   value="<?php echo $pengaturan->sebutan_bendahara ?? 'Bendahara RT'; ?>"
                                                   placeholder="Bendahara RT" maxlength="50">
                                            <small class="text-muted" style="font-size:.7rem;">cth: Bendahara RT, Kasir RT</small>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">Sebutan "Ketua RW"</label>
                                            <input type="text" name="sebutan_ketua_rw"
                                                   class="form-control form-control-sm sebutan-preview"
                                                   data-targets="prev_sbt_krw,mini_sbt_krw"
                                                   value="<?php echo $pengaturan->sebutan_ketua_rw ?? 'Ketua RW'; ?>"
                                                   placeholder="Ketua RW" maxlength="50">
                                            <small class="text-muted" style="font-size:.7rem;">cth: Ketua RW, Kepala Dusun, Kadus</small>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label small fw-semibold">Sebutan "Lurah / Kepala Desa"</label>
                                            <input type="text" name="sebutan_lurah"
                                                   class="form-control form-control-sm sebutan-preview"
                                                   data-targets="prev_sbt_lurah,mini_sbt_lurah"
                                                   value="<?php echo $pengaturan->sebutan_lurah ?? 'Lurah'; ?>"
                                                   placeholder="Lurah" maxlength="50">
                                            <small class="text-muted" style="font-size:.7rem;">cth: Lurah, Kepala Desa, Kades, Pj. Lurah</small>
                                        </div>
                                    </div>

                                    <!-- Preview penyebutan surat (live) -->
                                    <div class="mt-3 p-3" style="background:#f0fdf9;border:1px solid #99f6e4;border-radius:10px;">
                                        <div class="small fw-semibold mb-2" style="color:#0d9488;">
                                            <i class="bi bi-eye me-1"></i>Preview Kalimat Surat
                                        </div>
                                        <div style="font-size:.82rem;color:#374151;line-height:2.1;">
                                            Yang bertanda tangan di bawah ini,
                                            <strong><span id="prev_sbt_krt"><?php echo $sbt_krt; ?></span></strong>
                                            <strong><span id="prev_sbt_rt"><?php echo $sbt_rt; ?></span>
                                            <?php echo $pengaturan->nama_rt ?? '001'; ?></strong>
                                            <strong><span id="prev_sbt_rw"><?php echo $sbt_rw; ?></span>
                                            <?php echo $pengaturan->nama_rw ?? '001'; ?></strong>
                                            Kelurahan <?php echo $pengaturan->nama_kelurahan ?? '...'; ?>,
                                            dengan ini menerangkan bahwa ...<br>

                                            <span class="text-muted">Mengetahui :</span>&nbsp;
                                            <strong><span id="prev_sbt_krw"><?php echo $sbt_krw; ?></span></strong>
                                            &amp;
                                            <strong><span id="prev_sbt_lurah"><?php echo $sbt_lurah; ?></span></strong>
                                        </div>
                                        <!-- Badge contoh label form -->
                                        <div class="mt-2 d-flex flex-wrap gap-2" style="font-size:.75rem;">
                                            <span class="badge" style="background:#e0fdf4;color:#065f46;font-weight:600;">
                                                Pengurus <span id="prev_sbt_rt2"><?php echo $sbt_rt; ?></span>:
                                                <span id="prev_sbt_krt2"><?php echo $sbt_krt; ?></span>
                                                · <span id="prev_sbt_rw2"><?php echo $sbt_rw; ?></span>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ── YOUTUBE API KEY ──────────────────────────────── -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-youtube me-1" style="color:#dc2626;"></i>Integrasi YouTube
                                    </span>
                                </div>
                                <div class="p-4">
                                    <div class="row g-3">
                                        <div class="col-12">
                                            <label class="form-label small fw-semibold">YouTube Data API Key</label>
                                            <div class="input-group input-group-sm">
                                                <span class="input-group-text" style="background:#fef2f2;border-color:#fecaca;">
                                                    <i class="bi bi-key-fill" style="color:#dc2626;"></i>
                                                </span>
                                                <input type="password" name="youtube_api_key" id="inputYoutubeKey"
                                                       class="form-control form-control-sm"
                                                       value="<?php echo htmlspecialchars($pengaturan->youtube_api_key ?? ''); ?>"
                                                       placeholder="AIzaSy...">
                                                <button class="btn btn-sm btn-outline-secondary" type="button"
                                                        onclick="toggleYtKey()" title="Tampilkan/sembunyikan">
                                                    <i class="bi bi-eye" id="iconYtKey"></i>
                                                </button>
                                            </div>
                                            <small class="text-muted mt-1 d-block">
                                                <i class="bi bi-info-circle me-1"></i>
                                                Dapatkan API Key gratis di
                                                <a href="https://console.cloud.google.com" target="_blank">Google Cloud Console</a>
                                                → aktifkan <strong>YouTube Data API v3</strong>.
                                            </small>
                                            <?php if (!empty($pengaturan->youtube_api_key)): ?>
                                            <div class="mt-2" style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;padding:7px 12px;font-size:.78rem;color:#166534;">
                                                <i class="bi bi-check-circle-fill me-1"></i>
                                                API Key sudah terkonfigurasi.
                                                <a href="<?php echo base_url('youtube'); ?>" style="color:#166534;font-weight:700;">Coba fitur cari video →</a>
                                            </div>
                                            <?php else: ?>
                                            <div class="mt-2" style="background:#fef3c7;border:1px solid #fde68a;border-radius:8px;padding:7px 12px;font-size:.78rem;color:#92400e;">
                                                <i class="bi bi-exclamation-triangle-fill me-1"></i>
                                                API Key belum diisi. Fitur pencarian video YouTube tidak akan berfungsi.
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ── INTEGRASI API RW ──────────────────────────────────────── -->
<div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
    <div class="card-body p-0">
        <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
            <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                <i class="bi bi-plug-fill me-1" style="color:#7c3aed;"></i>
                Integrasi API — Aplikasi RW
            </span>
            <small class="text-muted d-block mt-1" style="font-size:.72rem;text-transform:none;letter-spacing:0;">
                Berikan URL &amp; API Key ini ke administrator aplikasi RW agar data RT dapat ditampilkan di dasbor RW.
            </small>
        </div>
        <div class="p-4">
 
            <!-- URL API (auto-detect, read-only) -->
            <div class="mb-3">
                <label class="form-label small fw-semibold">
                    <i class="bi bi-link-45deg me-1" style="color:#7c3aed;"></i>
                    URL Dasar API RT
                </label>
                <div class="input-group input-group-sm">
                    <span class="input-group-text" style="background:#f5f3ff;border-color:#ddd6fe;">
                        <i class="bi bi-globe" style="color:#7c3aed;"></i>
                    </span>
                    <input type="text" id="inputApiUrl" class="form-control form-control-sm font-monospace"
                           value="<?php echo rtrim(base_url(), '/'); ?>"
                           readonly style="background:#fafafa;font-size:.8rem;">
                    <button class="btn btn-sm btn-outline-secondary" type="button"
                            onclick="salinTeks('inputApiUrl', this)" title="Salin URL">
                        <i class="bi bi-clipboard"></i>
                    </button>
                </div>
                <small class="text-muted" style="font-size:.7rem;">
                    <i class="bi bi-info-circle me-1"></i>
                    Endpoint lengkap contoh: <code><?php echo rtrim(base_url(), '/'); ?>/api/dashboard</code>
                </small>
            </div>
 
            <!-- API Key -->
            <div class="mb-3">
                <label class="form-label small fw-semibold">
                    <i class="bi bi-key-fill me-1" style="color:#7c3aed;"></i>
                    API Key
                </label>
                <div class="input-group input-group-sm">
                    <span class="input-group-text" style="background:#f5f3ff;border-color:#ddd6fe;">
                        <i class="bi bi-shield-lock" style="color:#7c3aed;"></i>
                    </span>
                    <input type="text" id="inputApiKey" class="form-control form-control-sm font-monospace"
                           value="<?php echo htmlspecialchars($pengaturan->api_key ?? ''); ?>"
                           readonly placeholder="Belum digenerate — klik tombol di bawah"
                           style="background:#fafafa;font-size:.8rem;letter-spacing:.05em;">
                    <button class="btn btn-sm btn-outline-secondary" type="button"
                            onclick="salinTeks('inputApiKey', this)" title="Salin API Key"
                            <?php echo empty($pengaturan->api_key) ? 'disabled' : ''; ?> id="btnSalinKey">
                        <i class="bi bi-clipboard"></i>
                    </button>
                </div>
            </div>
 
            <!-- Tombol aksi -->
            <div class="d-flex flex-wrap gap-2 align-items-center">
                <!-- Generate / Regenerate key -->
                <button type="button" class="btn btn-sm fw-semibold" id="btnGenerateKey"
                        style="background:linear-gradient(135deg,#7c3aed,#a855f7);color:#fff;border:none;border-radius:8px;padding:6px 16px;">
                    <i class="bi bi-arrow-clockwise me-1"></i>
                    <?php echo empty($pengaturan->api_key) ? 'Generate API Key' : 'Regenerate Key'; ?>
                </button>
 
                <!-- Test koneksi -->
                <button type="button" class="btn btn-sm btn-outline-secondary fw-semibold" id="btnTestApi"
                        style="border-radius:8px;" <?php echo empty($pengaturan->api_key) ? 'disabled' : ''; ?>>
                    <i class="bi bi-wifi me-1"></i>Test Koneksi
                </button>
 
                <!-- Status test -->
                <span id="statusTestApi" class="small" style="display:none;"></span>
            </div>
 
            <!-- Konfirmasi regenerate (tersembunyi, muncul saat klik) -->
            <div id="boxKonfirmasiGenerate" style="display:none;margin-top:12px;background:#fff7ed;border:1.5px solid #fed7aa;border-radius:10px;padding:12px 14px;">
                <div class="small fw-semibold mb-1" style="color:#c2410c;">
                    <i class="bi bi-exclamation-triangle-fill me-1"></i>
                    <?php if (!empty($pengaturan->api_key)): ?>
                    Regenerate akan <strong>membatalkan key lama</strong>. Aplikasi RW yang sudah dikonfigurasi harus diperbarui.
                    <?php else: ?>
                    Generate API Key baru untuk mengaktifkan integrasi dengan aplikasi RW.
                    <?php endif; ?>
                </div>
                <div class="d-flex gap-2 mt-2">
                    <button type="button" class="btn btn-sm btn-warning fw-semibold" id="btnKonfirmasiGenerate" style="border-radius:7px;">
                        <i class="bi bi-check-lg me-1"></i>Ya, <?php echo empty($pengaturan->api_key) ? 'Generate' : 'Regenerate'; ?>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" id="btnBatalGenerate" style="border-radius:7px;">
                        Batal
                    </button>
                </div>
            </div>
 
            <!-- Box instruksi untuk admin RW (muncul setelah key ada) -->
            <?php if (!empty($pengaturan->api_key)): ?>
           <div class="mt-3 p-3" id="boxInstruksiRW" style="background:#f5f3ff;border:1.5px solid #ddd6fe;border-radius:10px;">
    <div class="small fw-semibold mb-2" style="color:#6d28d9;">
        <i class="bi bi-book me-1"></i>Cara Pakai di Aplikasi RW (CI3)
                </div>
                <div style="font-size:.78rem;color:#4c1d95;line-height:1.9;">
                    1. Isi <code>config/rt_api.php</code> aplikasi RW:<br>
                    <code style="background:#ede9fe;padding:2px 6px;border-radius:4px;display:block;margin:4px 0;font-size:.75rem;">
                        $config['rt_api_url'] = '<?php echo rtrim(base_url(), '/'); ?>';<br>
                        $config['rt_api_key'] = '<?php echo htmlspecialchars($pengaturan->api_key); ?>';
                    </code>
                    2. Load helper &amp; panggil:<br>
                    <code style="background:#ede9fe;padding:2px 6px;border-radius:4px;display:block;margin:4px 0;font-size:.75rem;">
                        $data_rt = rt_api_dashboard();
                    </code>
                </div>
            </div>
            <?php endif; ?>
 
            <!-- Daftar endpoint tersedia -->
            <div class="mt-3">
                <div class="small fw-semibold mb-1" style="color:#6c757d;">
                    <i class="bi bi-list-ul me-1"></i>Endpoint Tersedia
                </div>
                <div class="d-flex flex-wrap gap-1">
                    <?php foreach(['dashboard','info','warga','keuangan','iuran','pinjaman','tabungan','inventaris','pengumuman','kegiatan'] as $ep): ?>
                    <span class="badge" style="background:#f0f0ff;color:#4c1d95;font-weight:500;font-size:.7rem;border:1px solid #ddd6fe;font-family:monospace;">
                        /api/<?php echo $ep; ?>
                    </span>
                    <?php endforeach; ?>
                </div>
            </div>
 
        </div>
    </div>
</div>
<!-- ── END INTEGRASI API RW ──────────────────────────────────── -->
 
 
<!-- ================================================================
     SCRIPT — tambahkan di bawah view SEBELUM tag </script> penutup
     atau di blok <script> yang sudah ada
================================================================ -->
<script>
// ── Salin teks ke clipboard ──────────────────────────────────────
function salinTeks(inputId, btn) {
    const el = document.getElementById(inputId);
    if (!el || !el.value) return;
    navigator.clipboard.writeText(el.value).then(function() {
        const orig = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check-lg text-success"></i>';
        setTimeout(() => btn.innerHTML = orig, 1800);
    });
}
 
// ── Generate / Regenerate API Key ───────────────────────────────
const btnGen     = document.getElementById('btnGenerateKey');
const boxKonfirm = document.getElementById('boxKonfirmasiGenerate');
const btnKonfirm = document.getElementById('btnKonfirmasiGenerate');
const btnBatal   = document.getElementById('btnBatalGenerate');
const btnTest    = document.getElementById('btnTestApi');
const statusTest = document.getElementById('statusTestApi');
 
btnGen?.addEventListener('click', function() {
    boxKonfirm.style.display = boxKonfirm.style.display === 'none' ? 'block' : 'none';
});
 
btnBatal?.addEventListener('click', function() {
    boxKonfirm.style.display = 'none';
});
 
btnKonfirm?.addEventListener('click', function() {
    btnKonfirm.disabled = true;
    btnKonfirm.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>Proses...';
 
    fetch('<?php echo base_url("pengaturan/generate_api_key"); ?>', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json',
        }
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'ok') {
            const inp = document.getElementById('inputApiKey');
            const btnSalin = document.getElementById('btnSalinKey');
            if (inp) inp.value = data.api_key;
            if (btnSalin) btnSalin.disabled = false;
            if (btnTest) btnTest.disabled = false;
            boxKonfirm.style.display = 'none';
            btnGen.innerHTML = '<i class="bi bi-arrow-clockwise me-1"></i>Regenerate Key';
 
            // Tampilkan instruksi konfigurasi RW
            tampilkanInstruksiRW(data.api_key);
 
            // Tampilkan notif sukses
            tampilNotif('API Key berhasil digenerate! Salin dan pasang di aplikasi RW.', 'success');
        } else {
            tampilNotif('Gagal generate key: ' + (data.message || 'Unknown error'), 'danger');
        }
    })
    .catch(e => tampilNotif('Error: ' + e.message, 'danger'))
    .finally(() => {
        btnKonfirm.disabled = false;
        btnKonfirm.innerHTML = '<i class="bi bi-check-lg me-1"></i>Ya, Generate';
    });
});
 
// ── Test Koneksi API ─────────────────────────────────────────────
btnTest?.addEventListener('click', function() {
    statusTest.style.display = 'inline';
    statusTest.innerHTML     = '<i class="bi bi-hourglass-split me-1"></i><em>Mengecek...</em>';
    btnTest.disabled         = true;
 
    fetch('<?php echo base_url("pengaturan/test_api"); ?>', {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'ok') {
            statusTest.innerHTML = '<i class="bi bi-check-circle-fill text-success me-1"></i><span class="text-success fw-semibold">API OK ✓</span>';
        } else {
            statusTest.innerHTML = '<i class="bi bi-x-circle-fill text-danger me-1"></i><span class="text-danger">' + (data.message || 'Gagal') + '</span>';
        }
    })
    .catch(e => { statusTest.innerHTML = '<span class="text-danger">Error: ' + e.message + '</span>'; })
    .finally(() => { btnTest.disabled = false; setTimeout(() => statusTest.style.display = 'none', 5000); });
});
 
// ── Helper: tampil instruksi konfigurasi RW setelah generate ────
function tampilkanInstruksiRW(apiKey) {
    const baseUrl = document.getElementById('inputApiUrl')?.value || '';
    const html = `<div class="mt-3 p-3" id="boxInstruksiRW" style="background:#f5f3ff;border:1.5px solid #ddd6fe;border-radius:10px;">
        <div class="small fw-semibold mb-2" style="color:#6d28d9;"><i class="bi bi-book me-1"></i>Cara Pakai di Aplikasi RW (CI3)</div>
        <div style="font-size:.78rem;color:#4c1d95;line-height:1.9;">
            1. Isi <code>config/rt_api.php</code> aplikasi RW:<br>
            <code style="background:#ede9fe;padding:2px 6px;border-radius:4px;display:block;margin:4px 0;font-size:.75rem;">
                $config['rt_api_url'] = '${baseUrl}';<br>
                $config['rt_api_key'] = '${apiKey}';
            </code>
            2. Load helper &amp; panggil:<br>
            <code style="background:#ede9fe;padding:2px 6px;border-radius:4px;display:block;margin:4px 0;font-size:.75rem;">
                $data_rt = rt_api_dashboard();
            </code>
        </div>
    </div>`;

    // Hapus semua duplikat
    document.querySelectorAll('#boxInstruksiRW').forEach(el => el.remove());

    // Sisipkan baru setelah box konfirmasi
    boxKonfirm.insertAdjacentHTML('afterend', html);
}

 
// ── Helper: notifikasi flash kecil ──────────────────────────────
function tampilNotif(pesan, tipe) {
    const div = document.createElement('div');
    div.className = 'alert alert-' + tipe + ' alert-dismissible fade show mt-3';
    div.style.cssText = 'border-radius:10px;font-size:.85rem;';
    div.innerHTML = '<i class="bi bi-' + (tipe === 'success' ? 'check-circle' : 'exclamation-triangle') + ' me-2"></i>' + pesan +
        '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
    // Sisipkan di atas card API
    const cardApi = btnGen?.closest('.card');
    if (cardApi) cardApi.insertAdjacentElement('beforebegin', div);
    setTimeout(() => div.remove(), 6000);
}
</script>
 

                        <!-- ── PENGURUS RT ──────────────────────────────────── -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-people-fill me-1" style="color:#20c997;"></i>
                                        Pengurus <?php echo $sbt_rt; ?>
                                    </span>
                                </div>
                                <div class="p-4">
                                    <div class="row g-4">
                                        <!-- Ketua RT -->
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">
                                                <i class="bi bi-person-badge me-1" style="color:#20c997;"></i>
                                                <?php echo $sbt_krt; ?>
                                            </label>
                                            <select name="ketua_rt_warga_id" class="form-select form-select-sm mb-2">
                                                <option value="">-- Pilih <?php echo $sbt_krt; ?> --</option>
                                                <?php foreach($warga_list as $w): ?>
                                                <option value="<?php echo $w->id; ?>" <?php echo (isset($pengaturan->ketua_rt_warga_id) && $pengaturan->ketua_rt_warga_id == $w->id) ? 'selected' : ''; ?>>
                                                    <?php echo $w->nama_lengkap; ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <?php echo foto_upload_widget('foto_ketua_rt', $pengaturan->foto_ketua_rt ?? null, 'Foto ' . $sbt_krt); ?>
                                        </div>
                                        <!-- Sekretaris -->
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">
                                                <i class="bi bi-person-badge me-1" style="color:#20c997;"></i>
                                                <?php echo $sbt_sek; ?>
                                            </label>
                                            <select name="sekretaris_rt_warga_id" class="form-select form-select-sm mb-2">
                                                <option value="">-- Pilih <?php echo $sbt_sek; ?> --</option>
                                                <?php foreach($warga_list as $w): ?>
                                                <option value="<?php echo $w->id; ?>" <?php echo (isset($pengaturan->sekretaris_rt_warga_id) && $pengaturan->sekretaris_rt_warga_id == $w->id) ? 'selected' : ''; ?>>
                                                    <?php echo $w->nama_lengkap; ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <?php echo foto_upload_widget('foto_sekretaris_rt', $pengaturan->foto_sekretaris_rt ?? null, 'Foto ' . $sbt_sek); ?>
                                        </div>
                                        <!-- Bendahara -->
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">
                                                <i class="bi bi-person-badge me-1" style="color:#20c997;"></i>
                                                <?php echo $sbt_ben; ?>
                                            </label>
                                            <select name="bendahara_rt_warga_id" class="form-select form-select-sm mb-2">
                                                <option value="">-- Pilih <?php echo $sbt_ben; ?> --</option>
                                                <?php foreach($warga_list as $w): ?>
                                                <option value="<?php echo $w->id; ?>" <?php echo (isset($pengaturan->bendahara_rt_warga_id) && $pengaturan->bendahara_rt_warga_id == $w->id) ? 'selected' : ''; ?>>
                                                    <?php echo $w->nama_lengkap; ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                            <?php echo foto_upload_widget('foto_bendahara_rt', $pengaturan->foto_bendahara_rt ?? null, 'Foto ' . $sbt_ben); ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ── KETUA RW ─────────────────────────────────────── -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-person-circle me-1" style="color:#20c997;"></i>
                                        <?php echo $sbt_krw; ?>
                                    </span>
                                </div>
                                <div class="p-4">
                                    <div class="row g-3 align-items-start">
                                        <div class="col-md-5">
                                            <label class="form-label small fw-semibold">Nama <?php echo $sbt_krw; ?></label>
                                            <input type="text" name="nama_ketua_rw" class="form-control form-control-sm"
                                                   value="<?php echo $pengaturan->nama_ketua_rw ?? ''; ?>">
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label small fw-semibold">NIK <?php echo $sbt_krw; ?></label>
                                            <input type="text" name="nik_ketua_rw" class="form-control form-control-sm"
                                                   value="<?php echo $pengaturan->nik_ketua_rw ?? ''; ?>" maxlength="16">
                                        </div>
                                        <div class="col-md-3">
                                            <?php echo foto_upload_widget('foto_ketua_rw', $pengaturan->foto_ketua_rw ?? null, 'Foto ' . $sbt_krw); ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ── LURAH / KEPALA DESA ──────────────────────────── -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-building me-1" style="color:#20c997;"></i>
                                        <?php echo $sbt_lurah; ?>
                                    </span>
                                </div>
                                <div class="p-4">
                                    <div class="row g-3 align-items-start">
                                        <div class="col-md-5">
                                            <label class="form-label small fw-semibold">Nama <?php echo $sbt_lurah; ?></label>
                                            <input type="text" name="nama_lurah" class="form-control form-control-sm"
                                                   value="<?php echo $pengaturan->nama_lurah ?? ''; ?>">
                                            <div class="mt-2">
                                                <label class="form-label small fw-semibold mb-1">NIP / NIK</label>
                                                <input type="text" name="nip_lurah" class="form-control form-control-sm"
                                                       value="<?php echo $pengaturan->nip_lurah ?? ''; ?>">
                                            </div>
                                        </div>
                                        <!-- Kolom jabatan_lurah tetap tersimpan (backward compat) tapi tersembunyi -->
                                        <input type="hidden" name="jabatan_lurah" value="<?php echo htmlspecialchars($pengaturan->jabatan_lurah ?? $pengaturan->sebutan_lurah ?? 'Lurah'); ?>">
                                        <div class="col-md-4">
                                            <?php echo foto_upload_widget('foto_lurah', $pengaturan->foto_lurah ?? null, 'Foto ' . $sbt_lurah); ?>
                                        </div>
                                        <div class="col-12">
                                            <small class="text-muted" style="font-size:.72rem;">
                                                <i class="bi bi-info-circle me-1"></i>
                                                Sebutan jabatan (<strong><?php echo $sbt_lurah; ?></strong>) diatur di bagian <strong>Sebutan Jabatan</strong> di atas.
                                            </small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- ── FOOTER SURAT ─────────────────────────────────── -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-text-paragraph me-1" style="color:#20c997;"></i>Footer Surat
                                    </span>
                                </div>
                                <div class="p-4">
                                    <textarea name="footer_surat" class="form-control form-control-sm" rows="2"><?php echo $pengaturan->footer_surat ?? ''; ?></textarea>
                                </div>
                            </div>
                        </div>

                    </div><!-- /col-lg-8 -->

                    <!-- ── KOLOM KANAN ──────────────────────────────────────── -->
                    <div class="col-lg-4">

                        <!-- Logo RT -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-image me-1" style="color:#20c997;"></i>Logo <?php echo $sbt_rt; ?>
                                    </span>
                                </div>
                                <div class="p-4 text-center">
                                    <div id="logoPreviewWrap" class="mb-3">
                                        <?php if(!empty($pengaturan->logo)): ?>
                                        <img id="logoPreview" src="<?php echo base_url('uploads/pengaturan/' . $pengaturan->logo); ?>" alt="Logo" class="rounded border" style="max-width:120px;max-height:120px;object-fit:contain;">
                                        <?php else: ?>
                                        <div id="logoPlaceholder" style="width:100px;height:100px;border:2px dashed #dee2e6;border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto;color:#adb5bd;font-size:11px;text-align:center;padding:10px;">
                                            <div><i class="bi bi-image d-block mb-1" style="font-size:1.5rem;"></i>Belum ada logo</div>
                                        </div>
                                        <img id="logoPreview" src="#" alt="" style="display:none;max-width:120px;max-height:120px;object-fit:contain;" class="rounded border">
                                        <?php endif; ?>
                                    </div>
                                    <label for="logoInput" class="btn btn-sm btn-outline-secondary w-100 mb-2" style="border-radius:8px;cursor:pointer;">
                                        <i class="bi bi-upload me-1"></i>Pilih Logo Baru
                                    </label>
                                    <input type="file" id="logoInput" name="logo" accept="image/*" class="d-none"
                                           onchange="previewFoto(this, 'logoPreview', 'logoPlaceholder')">
                                    <small class="text-muted d-block">Format: JPG, PNG, SVG. Maks 1MB</small>
                                </div>
                            </div>
                        </div>

                        <!-- Preview surat mini -->
                        <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                            <div class="card-body p-0">
                                <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                                    <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                        <i class="bi bi-eye me-1" style="color:#20c997;"></i>Preview Surat
                                    </span>
                                </div>
                                <div class="p-2">
                                    <div id="miniSurat" style="background:#fff;border:1px solid #dee2e6;border-radius:6px;padding:8px 10px 10px;font-family:'Times New Roman',serif;font-size:5.5pt;color:#000;line-height:1.4;overflow:hidden;">
                                        <!-- Kop surat -->
                                        <div style="display:flex;align-items:center;gap:5px;border-bottom:2px double #000;padding-bottom:5px;margin-bottom:5px;">
                                            <div style="flex-shrink:0;">
                                                <?php if(!empty($pengaturan->logo)): ?>
                                                <img id="kopLogo" src="<?php echo base_url('uploads/pengaturan/' . $pengaturan->logo); ?>" style="width:26px;height:26px;object-fit:contain;">
                                                <?php else: ?>
                                                <div id="kopLogoPlaceholder" style="width:26px;height:26px;border:1px solid #000;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:4px;text-align:center;line-height:1.2;">LOGO</div>
                                                <img id="kopLogo" src="#" style="display:none;width:26px;height:26px;object-fit:contain;">
                                                <?php endif; ?>
                                            </div>
                                            <div style="flex:1;text-align:center;">
                                                <div style="font-size:4.5pt;font-weight:bold;text-transform:uppercase;">PEMERINTAH <span id="prev_kota"><?php echo strtoupper($pengaturan->nama_kota ?? 'KOTA/KABUPATEN'); ?></span></div>
                                                <div style="font-size:4.5pt;font-weight:bold;text-transform:uppercase;">KECAMATAN <span id="prev_kec"><?php echo strtoupper($pengaturan->nama_kecamatan ?? '...'); ?></span></div>
                                                <div style="font-size:5.5pt;font-weight:bold;text-transform:uppercase;"><span id="prev_kel"><?php echo strtoupper($pengaturan->nama_kelurahan ?? '...'); ?></span></div>
                                            </div>
                                        </div>
                                        <!-- Judul surat -->
                                        <div style="text-align:center;margin:4px 0;">
                                            <div style="font-size:5pt;font-weight:bold;text-transform:uppercase;text-decoration:underline;">SURAT PENGANTAR</div>
                                            <div style="font-size:5pt;font-weight:bold;text-transform:uppercase;letter-spacing:0.5px;">KETERANGAN DOMISILI</div>
                                            <div style="font-size:4pt;">Nomor: ...... / ...... / <?php echo date('Y'); ?></div>
                                        </div>
                                        <!-- Isi -->
                                        <div style="font-size:4.5pt;text-align:justify;margin:3px 0;">
                                            Yang bertanda tangan di bawah ini,
                                            <span id="mini_sbt_krt"><?php echo $sbt_krt; ?></span>
                                            <span id="prev_rt2"><?php echo $pengaturan->nama_rt ?? 'RT 001'; ?></span>
                                            <span id="mini_sbt_rw"><?php echo $sbt_rw; ?></span>
                                            <span id="prev_rw2"><?php echo $pengaturan->nama_rw ?? 'RW 001'; ?></span>
                                            <span id="prev_kel2"><?php echo $pengaturan->nama_kelurahan ?? '...'; ?></span>,
                                            Kecamatan <span id="prev_kec2"><?php echo $pengaturan->nama_kecamatan ?? '...'; ?></span>,
                                            <span id="prev_kota2"><?php echo $pengaturan->nama_kota ?? '...'; ?></span>,
                                            dengan ini menerangkan bahwa :
                                        </div>
                                        <!-- Tabel data -->
                                        <table style="width:100%;border-collapse:collapse;margin:2px 0;font-size:4.5pt;">
                                            <?php foreach(['Nama Lengkap','Tempat / Tgl Lahir','Jenis Kelamin','Kewarganegaraan / Agama','Pekerjaan','Alamat','NIK','Keperluan'] as $r): ?>
                                            <tr>
                                                <td style="width:75px;padding:0.8px 2px;white-space:nowrap;"><?php echo $r; ?></td>
                                                <td style="width:7px;padding:0.8px 1px;">:</td>
                                                <td style="border-bottom:0.5px solid #aaa;padding:0.8px 2px;"><span style="color:#ccc;">.............................</span></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </table>
                                        <div style="font-size:4.5pt;margin:3px 0;text-align:justify;">Demikian surat keterangan ini dibuat untuk dapat dipergunakan sebagaimana mestinya.</div>
                                        <!-- Tanda tangan -->
                                        <div style="font-size:4.5pt;margin-top:5px;">
                                            <div style="display:flex;justify-content:space-between;margin-bottom:3px;">
                                                <div style="text-align:center;width:45%;">
                                                    <div>Pemegang Surat</div>
                                                    <div style="height:16px;"></div>
                                                    <div style="border-top:0.5px solid #000;padding-top:2px;"><strong>( .................. )</strong></div>
                                                </div>
                                                <div style="text-align:center;width:45%;">
                                                    <div style="font-weight:bold;">
                                                        <span id="mini_sbt_krt2"><?php echo $sbt_krt; ?></span>
                                                        <span id="prev_rt3"><?php echo $pengaturan->nama_rt ?? 'RT 001'; ?></span>
                                                    </div>
                                                    <div style="height:16px;"></div>
                                                    <div style="border-top:0.5px solid #000;padding-top:2px;">
                                                        <span id="prev_ketua_rt" style="font-weight:bold;"><?php echo !empty($pengaturan->nama_ketua_rt) ? $pengaturan->nama_ketua_rt : '..................'; ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div style="text-align:center;font-weight:bold;text-decoration:underline;text-transform:uppercase;margin:2px 0;font-size:5pt;letter-spacing:0.5px;">MENGETAHUI</div>
                                            <div id="prev_ttd_row2" style="display:flex;<?php echo !empty($pengaturan->nama_lurah) ? 'justify-content:space-between;' : 'justify-content:center;'; ?>">
                                                <div style="text-align:center;width:45%;">
                                                    <div style="font-weight:bold;">
                                                        <span id="mini_sbt_krw"><?php echo $sbt_krw; ?></span>
                                                        <span id="prev_rw3"><?php echo $pengaturan->nama_rw ?? 'RW 001'; ?></span>
                                                    </div>
                                                    <div style="height:16px;"></div>
                                                    <div style="border-top:0.5px solid #000;padding-top:2px;">
                                                        <span id="prev_ketua_rw" style="font-weight:bold;"><?php echo !empty($pengaturan->nama_ketua_rw) ? $pengaturan->nama_ketua_rw : '..................'; ?></span><br>
                                                        <span id="prev_nik_rw" style="font-size:4pt;color:#555;"><?php echo !empty($pengaturan->nik_ketua_rw) ? 'NIK: '.$pengaturan->nik_ketua_rw : ''; ?></span>
                                                    </div>
                                                </div>
                                                <div id="prev_box_lurah" style="text-align:center;width:45%;<?php echo !empty($pengaturan->nama_lurah) ? '' : 'display:none;'; ?>">
                                                    <div style="font-weight:bold;">
                                                        <span id="mini_sbt_lurah"><?php echo $sbt_lurah; ?></span>
                                                    </div>
                                                    <div style="height:16px;"></div>
                                                    <div style="border-top:0.5px solid #000;padding-top:2px;">
                                                        <span id="prev_nama_lurah" style="font-weight:bold;"><?php echo !empty($pengaturan->nama_lurah) ? $pengaturan->nama_lurah : '..................'; ?></span><br>
                                                        <span id="prev_nip_lurah" style="font-size:4pt;color:#555;"><?php echo !empty($pengaturan->nip_lurah) ? 'NIP: '.$pengaturan->nip_lurah : ''; ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- Footer -->
                                        <div style="border-top:0.5px solid #ccc;margin-top:5px;padding-top:2px;font-size:3.8pt;color:#777;text-align:center;">
                                            <span id="prev_footer_text"><?php echo !empty($pengaturan->footer_surat) ? $pengaturan->footer_surat : 'Diterbitkan oleh Sistem Informasi Manajemen '.($pengaturan->nama_rt ?? 'RT').' '.($pengaturan->nama_rw ?? 'RW'); ?></span>
                                            &bull; Dicetak pada: <?php echo date('d/m/Y'); ?>
                                        </div>
                                    </div>
                                    <p class="text-muted text-center mt-2 mb-0" style="font-size:10px;">
                                        <i class="bi bi-info-circle me-1"></i>Preview otomatis saat Anda mengetik
                                    </p>
                                </div>
                            </div>
                        </div>

                        <!-- Tombol simpan -->
                        <div class="card border-0 shadow-sm" style="border-radius:14px;">
                            <div class="card-body p-4">
                                <button type="submit" class="btn btn-success w-100 fw-semibold" style="border-radius:8px;">
                                    <i class="bi bi-save me-2"></i>Simpan Pengaturan
                                </button>
                                <p class="text-muted text-center mt-2 mb-0" style="font-size:11px;">
                                    <i class="bi bi-shield-check me-1"></i>Perubahan berlaku untuk semua surat yang dicetak
                                </p>
                            </div>
                        </div>

                    </div><!-- /col-lg-4 -->
                </div><!-- /row -->
            </form>
        </div><!-- /tab-pane pengaturan -->


        <!-- ============================================================
             TAB: STRUKTUR ORGANISASI (Master Jabatan & Pengurus)
        ============================================================ -->
        <div class="tab-pane fade <?php echo ($active_tab === 'struktur') ? 'show active' : ''; ?>"
             id="pane-struktur" role="tabpanel">

            <div class="row g-4">
                <!-- KIRI: Master Jabatan -->
                <div class="col-lg-5">
                    <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                        <div class="card-body p-0">
                            <div class="px-4 py-3 d-flex align-items-center justify-content-between" style="border-bottom:1px solid #f1f3f5;">
                                <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                    <i class="bi bi-tags-fill me-1" style="color:#20c997;"></i>
                                    Master Jabatan
                                </span>
                                <button type="button" class="btn btn-sm btn-primary" onclick="tambahJabatan()" style="border-radius:8px;">
                                    <i class="bi bi-plus-lg me-1"></i>Tambah
                                </button>
                            </div>
                            <div class="p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0" style="font-size:.85rem;">
                                        <thead class="bg-light">
                                            <tr>
                                                <th class="ps-4" style="width:50px;">#</th>
                                                <th>Nama Jabatan</th>
                                                <th>Kategori</th>
                                                <th class="text-center" style="width:100px;">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if(empty($master_jabatan)): ?>
                                            <tr>
                                                <td colspan="4" class="text-center py-4 text-muted">Belum ada data jabatan</td>
                                            </tr>
                                            <?php else: $no=1; foreach($master_jabatan as $mj): ?>
                                            <tr>
                                                <td class="ps-4 text-muted small"><?php echo $mj->urutan; ?></td>
                                                <td class="fw-semibold"><?php echo htmlspecialchars($mj->nama_jabatan ?? ''); ?></td>
                                                <td>
                                                    <span class="badge <?php echo $mj->kategori == 'pengurus' ? 'bg-info' : 'bg-secondary'; ?> opacity-75">
                                                        <?php echo ucfirst($mj->kategori); ?>
                                                    </span>
                                                </td>
                                                <td class="text-center pe-3">
                                                    <div class="btn-group btn-group-sm">
                                                        <button class="btn btn-link text-primary p-1" onclick='editJabatan(<?php echo json_encode($mj); ?>)' title="Edit">
                                                            <i class="bi bi-pencil-square"></i>
                                                        </button>
                                                        <button class="btn btn-link text-danger p-1" onclick="konfirmasiHapusJabatan(<?php echo $mj->id; ?>, '<?php echo $mj->nama_jabatan; ?>')" title="Hapus">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card border-0 shadow-sm" style="border-radius:14px; background: #fffbeb;">
                        <div class="card-body p-4">
                            <h6 class="fw-bold mb-2 text-warning-emphasis">
                                <i class="bi bi-info-circle-fill me-2"></i>Tentang Master Jabatan
                            </h6>
                            <p class="small text-muted mb-0" style="line-height:1.6;">
                                Master jabatan digunakan untuk menentukan sebutan jabatan yang akan tampil di halaman <strong>Struktur Organisasi</strong> publik.
                                Anda bisa menambah jabatan baru seperti <strong>Wakil RT</strong>, <strong>Humas</strong>, atau seksi-seksi lainnya secara bebas.
                            </p>
                        </div>
                    </div>
                </div>

                <!-- KANAN: Struktur / Mapping Pengurus -->
                <div class="col-lg-7">
                    <div class="card border-0 shadow-sm" style="border-radius:14px;">
                        <div class="card-body p-0">
                            <div class="px-4 py-3 d-flex align-items-center justify-content-between" style="border-bottom:1px solid #f1f3f5;">
                                <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                    <i class="bi bi-diagram-3-fill me-1" style="color:#20c997;"></i>
                                    Susunan Pengurus & Seksi
                                </span>
                                <button type="button" class="btn btn-sm btn-success" onclick="tambahStruktur()" style="border-radius:8px;">
                                    <i class="bi bi-person-plus-fill me-1"></i>Tetapkan Pengurus
                                </button>
                            </div>
                            <div class="p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0" style="font-size:.85rem;">
                                        <thead class="bg-light">
                                            <tr>
                                                <th class="ps-4">Jabatan</th>
                                                <th>Nama Pengurus</th>
                                                <th>Foto</th>
                                                <th class="text-center" style="width:100px;">Aksi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if(empty($struktur)): ?>
                                            <tr>
                                                <td colspan="4" class="text-center py-5">
                                                    <i class="bi bi-person-x d-block mb-2 text-muted" style="font-size:2rem;"></i>
                                                    <div class="text-muted small">Belum ada pengurus yang ditetapkan</div>
                                                    <button class="btn btn-sm btn-outline-success mt-3" onclick="tambahStruktur()">Mulai Menetapkan</button>
                                                </td>
                                            </tr>
                                            <?php else: foreach($struktur as $st): ?>
                                            <tr>
                                                <td class="ps-4">
                                                    <div class="fw-bold"><?php echo htmlspecialchars($st->nama_jabatan ?? ''); ?></div>
                                                    <small class="text-muted" style="font-size:.7rem;"><?php echo ucfirst($st->kategori); ?></small>
                                                </td>
                                                <td>
                                                    <?php if($st->warga_id): ?>
                                                        <div class="fw-semibold text-teal"><?php echo htmlspecialchars($st->nama_warga ?? ''); ?></div>
                                                        <small class="text-muted" style="font-size:.72rem;">NIK: <?php echo $st->nik_warga; ?></small>
                                                        <div class="mt-1"><span class="badge bg-success" style="font-size:10px;"><i class="bi bi-patch-check-fill me-1"></i>Warga RT</span></div>
                                                    <?php else: ?>
                                                        <div class="fw-semibold"><?php echo htmlspecialchars($st->nama_manual ?? '-'); ?></div>
                                                        <small class="text-muted" style="font-size:.72rem;">NIK: <?php echo $st->nik_manual ?: '-'; ?></small>
                                                        <div class="mt-1"><span class="badge bg-secondary" style="font-size:10px;"><i class="bi bi-keyboard me-1"></i>Input Manual</span></div>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if($st->foto): ?>
                                                        <img src="<?php echo base_url('uploads/pengaturan/' . $st->foto); ?>" class="rounded-circle border" style="width:40px;height:40px;object-fit:cover;">
                                                    <?php else: ?>
                                                        <div class="rounded-circle bg-light d-flex align-items-center justify-content-center text-muted border" style="width:40px;height:40px;font-size:1.2rem;">
                                                            <i class="bi bi-person"></i>
                                                        </div>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="text-center pe-3">
                                                    <div class="btn-group btn-group-sm">
                                                        <button class="btn btn-link text-primary p-1" onclick='editStruktur(<?php echo json_encode($st); ?>)' title="Edit">
                                                            <i class="bi bi-pencil-square"></i>
                                                        </button>
                                                        <button class="btn btn-link text-danger p-1" onclick="konfirmasiHapusStruktur(<?php echo $st->id; ?>, '<?php echo $st->nama_jabatan; ?>')" title="Hapus">
                                                            <i class="bi bi-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div><!-- /tab-pane struktur -->


        <!-- ============================================================
             TAB 2 : PERATURAN RT
        ============================================================ -->
        <div class="tab-pane fade <?php echo ($active_tab === 'peraturan') ? 'show active' : ''; ?>"
             id="pane-peraturan" role="tabpanel">

            <div class="row g-4">
                <div class="col-lg-8">
                    <div class="card border-0 shadow-sm" style="border-radius:14px;">
                        <div class="card-body p-0">
                            <div class="px-4 py-3 d-flex align-items-center justify-content-between" style="border-bottom:1px solid #f1f3f5;">
                                <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                    <i class="bi bi-file-richtext me-1" style="color:#20c997;"></i>
                                    Isi Peraturan <?php echo $sbt_rt; ?>
                                </span>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="btnIsiContoh" style="border-radius:8px;font-size:11px;">
                                    <i class="bi bi-lightning-fill me-1 text-warning"></i>Isi Contoh Peraturan
                                </button>
                            </div>
                            <div class="p-4">
                                <form action="<?php echo base_url('pengaturan/simpan_peraturan'); ?>" method="post" id="formPeraturan">

                                    <div id="quillToolbar" class="mb-2">
                                        <span class="ql-formats">
                                            <select class="ql-header">
                                                <option value="1">Judul Besar</option>
                                                <option value="2">Judul Pasal</option>
                                                <option value="3">Sub Judul</option>
                                                <option selected>Normal</option>
                                            </select>
                                        </span>
                                        <span class="ql-formats">
                                            <button class="ql-bold"></button>
                                            <button class="ql-italic"></button>
                                            <button class="ql-underline"></button>
                                        </span>
                                        <span class="ql-formats">
                                            <button class="ql-list" value="ordered"></button>
                                            <button class="ql-list" value="bullet"></button>
                                        </span>
                                        <span class="ql-formats">
                                            <select class="ql-align">
                                                <option selected></option>
                                                <option value="center"></option>
                                                <option value="right"></option>
                                                <option value="justify"></option>
                                            </select>
                                        </span>
                                        <span class="ql-formats">
                                            <button class="ql-clean"></button>
                                        </span>
                                    </div>

                                    <div id="alertDataRusak" style="display:none;align-items:flex-start;gap:12px;background:#fef3c7;border:1.5px solid #f59e0b;border-radius:10px;padding:14px 16px;margin-bottom:12px;">
                                        <i class="bi bi-exclamation-triangle-fill" style="color:#d97706;font-size:1.2rem;flex-shrink:0;margin-top:2px;"></i>
                                        <div style="flex:1;">
                                            <div style="font-weight:700;color:#92400e;font-size:.88rem;margin-bottom:4px;">Data peraturan sebelumnya tidak bisa dimuat</div>
                                            <div style="font-size:.82rem;color:#78350f;margin-bottom:10px;">Data lama tersimpan dalam format teks biasa. Klik tombol di bawah untuk mengisi ulang dengan contoh peraturan terformat.</div>
                                            <button type="button" id="btnResetIsiContoh" class="btn btn-sm btn-warning fw-semibold" style="border-radius:8px;font-size:.8rem;">
                                                <i class="bi bi-arrow-clockwise me-1"></i>Reset & Isi Contoh
                                            </button>
                                        </div>
                                    </div>

                                    <div id="quillEditor" style="min-height:480px;font-size:0.9rem;border-radius:0 0 8px 8px;"></div>
                                    <input type="hidden" name="peraturan_rt" id="peraturan_rt_input">

                                    <div class="d-flex justify-content-between align-items-center mt-3">
                                        <small class="text-muted">
                                            <i class="bi bi-type me-1"></i>
                                            <span id="charCount">0</span> karakter
                                        </small>
                                        <div class="d-flex gap-2">
                                            <button type="button" class="btn btn-sm btn-outline-secondary" id="btnPreview" style="border-radius:8px;">
                                                <i class="bi bi-eye me-1"></i>Preview
                                            </button>
                                            <button type="submit" class="btn btn-success fw-semibold" style="border-radius:8px;">
                                                <i class="bi bi-save me-1"></i>Simpan Peraturan <?php echo $sbt_rt; ?>
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div id="panelPreview" class="card border-0 shadow-sm mt-4 d-none" style="border-radius:14px;">
                        <div class="card-body p-0">
                            <div class="px-4 py-3 d-flex justify-content-between align-items-center" style="border-bottom:1px solid #f1f3f5;">
                                <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                                    <i class="bi bi-eye me-1" style="color:#20c997;"></i>Preview Tampilan
                                </span>
                                <button type="button" class="btn btn-sm btn-outline-secondary" id="btnTutupPreview" style="border-radius:8px;">
                                    <i class="bi bi-x-lg"></i>
                                </button>
                            </div>
                            <div class="p-4">
                                <div id="isiPreview" class="peraturan-preview-box"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Kolom kanan tips -->
                <div class="col-lg-4">
                    <div class="card border-0 shadow-sm mb-3" style="border-radius:14px;background:linear-gradient(135deg,#f0fdf9 0%,#f8f9fa 100%);">
                        <div class="card-body p-4">
                            <h6 class="fw-semibold mb-3" style="color:#20c997;">
                                <i class="bi bi-keyboard me-2"></i>Panduan Editor
                            </h6>
                            <ul class="list-unstyled mb-0" style="font-size:0.85rem;color:#6c757d;line-height:2;">
                                <li><kbd>Ctrl+B</kbd> → <strong>Tebal</strong></li>
                                <li><kbd>Ctrl+I</kbd> → <em>Miring</em></li>
                                <li><kbd>Ctrl+U</kbd> → <u>Garis bawah</u></li>
                                <li><i class="bi bi-list-ol me-2 text-success"></i>Daftar bernomor</li>
                                <li><i class="bi bi-list-ul me-2 text-success"></i>Daftar poin/bullet</li>
                            </ul>
                            <hr style="border-color:#dee2e6;">
                            <h6 class="fw-semibold mb-2" style="color:#20c997;font-size:.8rem;">
                                <i class="bi bi-lightbulb me-1"></i>Tips Penulisan
                            </h6>
                            <ul class="list-unstyled mb-0" style="font-size:0.82rem;color:#6c757d;line-height:1.9;">
                                <li><i class="bi bi-check2 me-2 text-success"></i>Gunakan <b>Judul Pasal</b> untuk tiap pasal</li>
                                <li><i class="bi bi-check2 me-2 text-success"></i>Gunakan <b>Daftar Nomor</b> untuk ayat</li>
                                <li><i class="bi bi-check2 me-2 text-success"></i>Tebalkan poin-poin penting</li>
                                <li><i class="bi bi-check2 me-2 text-success"></i>Tengahkan judul utama</li>
                            </ul>
                        </div>
                    </div>
                    <div class="card border-0 shadow-sm" style="border-radius:14px;">
                        <div class="card-body p-3">
                            <p class="mb-0 small text-muted text-center">
                                <i class="bi bi-info-circle me-1"></i>
                                Peraturan tersimpan sebagai HTML dan tampil berformat di halaman warga.
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- /tab-pane peraturan -->

    </div><!-- /tab-content -->
</div>

<?php
// ================================================================
// HELPER FUNCTION foto_upload_widget
// ================================================================
function foto_upload_widget($field_name, $current, $label = 'Foto') {
    $base_url  = function_exists('base_url') ? base_url('uploads/pengaturan/') : 'uploads/pengaturan/';
    $hapus_url = function_exists('base_url') ? base_url('pengaturan/hapus_foto/' . $field_name) : '#';
    $preview_id = 'prev_' . $field_name;
    $ph_id      = 'ph_'   . $field_name;
    ob_start(); ?>
    <div class="foto-upload-widget mt-1">
        <div class="d-flex align-items-center gap-2 mb-1">
            <?php if(!empty($current)): ?>
            <img id="<?php echo $preview_id; ?>" src="<?php echo $base_url . $current; ?>" alt="<?php echo $label; ?>" class="rounded border" style="width:48px;height:48px;object-fit:cover;">
            <?php else: ?>
            <div id="<?php echo $ph_id; ?>" style="width:48px;height:48px;border:2px dashed #dee2e6;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#adb5bd;flex-shrink:0;">
                <i class="bi bi-person" style="font-size:1.2rem;"></i>
            </div>
            <img id="<?php echo $preview_id; ?>" src="#" alt="" style="display:none;width:48px;height:48px;object-fit:cover;" class="rounded border">
            <?php endif; ?>
            <div style="flex:1;min-width:0;">
                <label for="input_<?php echo $field_name; ?>" class="btn btn-sm btn-outline-secondary w-100" style="border-radius:6px;cursor:pointer;font-size:11px;padding:3px 6px;">
                    <i class="bi bi-upload me-1"></i><?php echo $label; ?>
                </label>
                <input type="file" id="input_<?php echo $field_name; ?>" name="<?php echo $field_name; ?>" accept="image/*" class="d-none"
                       onchange="previewFoto(this, '<?php echo $preview_id; ?>', '<?php echo $ph_id; ?>')">
            </div>
        </div>
        <?php if(!empty($current)): ?>
        <button type="button" class="btn btn-outline-danger w-100 mt-1" style="border-radius:6px;font-size:10px;padding:2px 6px;"
                onclick="konfirmasiHapusFotoPengaturan('<?php echo $hapus_url; ?>','<?php echo $label; ?>')">
            <i class="bi bi-trash me-1"></i>Hapus Foto
        </button>
        <?php endif; ?>
    </div>
    <?php return ob_get_clean();
}
?>

<!-- Quill CSS -->
<link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">

<style>
/* Nav tabs */
.nav-tabs .nav-link { color:#6c757d;font-size:.875rem;font-weight:500;padding:.6rem 1.2rem;border:none;border-bottom:3px solid transparent;border-radius:0;transition:color .2s,border-color .2s; }
.nav-tabs .nav-link:hover { color:#20c997; }
.nav-tabs .nav-link.active { color:#20c997;border-bottom-color:#20c997;background:transparent;font-weight:600; }
.form-control:focus,.form-select:focus { border-color:#20c997;box-shadow:0 0 0 .2rem rgba(32,201,151,.15); }
.btn:focus { box-shadow:none; }

/* Quill editor */
#quillToolbar { border:1px solid #dee2e6;border-bottom:none;border-radius:8px 8px 0 0;background:#f8f9fa;padding:6px 8px; }
#quillEditor  { border:1px solid #dee2e6;border-radius:0 0 8px 8px;background:#fff; }
#quillEditor:focus-within { border-color:#20c997;box-shadow:0 0 0 .2rem rgba(32,201,151,.15); }
.ql-container { font-family:'Georgia',serif;font-size:0.9rem; }
.ql-editor { min-height:480px;padding:1.25rem;line-height:1.8; }
.ql-editor h1 { font-size:1.3rem;font-weight:800;text-align:center;margin:.5rem 0 .3rem;color:#0f1923; }
.ql-editor h2 { font-size:1.05rem;font-weight:700;color:#0d9488;margin:1rem 0 .3rem;border-bottom:1.5px solid #ccfbf1;padding-bottom:.2rem; }
.ql-editor h3 { font-size:.95rem;font-weight:700;color:#374151;margin:.8rem 0 .2rem; }
.ql-editor ol,.ql-editor ul { padding-left:1.5rem;margin:.3rem 0; }
.ql-editor li { margin-bottom:.2rem; }
.ql-editor p { margin-bottom:.4rem; }
.ql-snow .ql-picker.ql-header .ql-picker-label::before { content:'Format'; }
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before { content:'Judul Besar'; }
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before { content:'Judul Pasal'; }
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before { content:'Sub Judul'; }
.ql-snow .ql-picker.ql-header .ql-picker-item:not([data-value])::before { content:'Normal'; }
.ql-snow .ql-picker.ql-header[data-value="1"] .ql-picker-label::before { content:'Judul Besar'; }
.ql-snow .ql-picker.ql-header[data-value="2"] .ql-picker-label::before { content:'Judul Pasal'; }
.ql-snow .ql-picker.ql-header[data-value="3"] .ql-picker-label::before { content:'Sub Judul'; }

/* Preview peraturan */
.peraturan-preview-box { font-family:'Georgia',serif;font-size:.9rem;line-height:1.8;color:#374151;background:#fafafa;border:1px solid #e9ecef;border-radius:8px;padding:1.5rem;max-height:600px;overflow-y:auto; }
.peraturan-preview-box h1 { font-size:1.3rem;font-weight:800;text-align:center;color:#0f1923;margin-bottom:.5rem; }
.peraturan-preview-box h2 { font-size:1.05rem;font-weight:700;color:#0d9488;border-bottom:1.5px solid #ccfbf1;padding-bottom:.2rem;margin:1.2rem 0 .4rem; }
.peraturan-preview-box h3 { font-size:.95rem;font-weight:700;color:#374151;margin:.8rem 0 .2rem; }
.peraturan-preview-box ol,.peraturan-preview-box ul { padding-left:1.5rem; }
.peraturan-preview-box li { margin-bottom:.3rem; }
</style>

<!-- Quill JS -->
<script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
<script>
// ================================================================
// QUILL EDITOR
// ================================================================
const quill = new Quill('#quillEditor', {
    theme: 'snow',
    modules: { toolbar: '#quillToolbar' },
    placeholder: 'Tulis peraturan <?php echo addslashes($sbt_rt); ?> di sini...'
});

const savedContent = <?php echo json_encode($pengaturan->peraturan_rt ?? ''); ?>;

function isCorrupted(html) {
    if (!html || html.trim() === '') return false;
    const hasBlockTags = /<(h[1-6]|p|ol|ul|li|div|blockquote)\b/i.test(html);
    const isLong = html.replace(/<[^>]+>/g, '').trim().length > 100;
    return isLong && !hasBlockTags;
}

if (savedContent && !isCorrupted(savedContent)) {
    quill.root.innerHTML = savedContent;
} else if (isCorrupted(savedContent)) {
    document.getElementById('alertDataRusak').style.display = 'flex';
}

function updateCount() {
    document.getElementById('charCount').textContent = quill.getText().trim().length.toLocaleString('id-ID');
}
quill.on('text-change', updateCount);
updateCount();

document.getElementById('formPeraturan').addEventListener('submit', function() {
    document.getElementById('peraturan_rt_input').value = quill.root.innerHTML;
});

document.getElementById('btnPreview').addEventListener('click', function() {
    if (quill.getText().trim() === '') { alert('Belum ada isi peraturan.'); return; }
    document.getElementById('isiPreview').innerHTML = quill.root.innerHTML;
    const panel = document.getElementById('panelPreview');
    panel.classList.remove('d-none');
    panel.scrollIntoView({ behavior:'smooth', block:'start' });
});

document.getElementById('btnTutupPreview').addEventListener('click', function() {
    document.getElementById('panelPreview').classList.add('d-none');
});

document.getElementById('btnResetIsiContoh')?.addEventListener('click', function() {
    document.getElementById('alertDataRusak').style.display = 'none';
    loadContohPeraturan();
});

document.getElementById('btnIsiContoh').addEventListener('click', function() {
    if (quill.getText().trim() !== '' && !confirm('Editor sudah berisi teks. Timpa dengan contoh peraturan?')) return;
    loadContohPeraturan();
});

function loadContohPeraturan() {
    const namaRt    = document.querySelector('[name="nama_rt"]')?.value    || '<?php echo addslashes($pengaturan->nama_rt ?? "RT 001"); ?>';
    const namaRw    = document.querySelector('[name="nama_rw"]')?.value    || '<?php echo addslashes($pengaturan->nama_rw ?? "RW 001"); ?>';
    const namaKel   = document.querySelector('[name="nama_kelurahan"]')?.value || '<?php echo addslashes($pengaturan->nama_kelurahan ?? "..."); ?>';
    const namaKec   = document.querySelector('[name="nama_kecamatan"]')?.value || '<?php echo addslashes($pengaturan->nama_kecamatan ?? "..."); ?>';
    const sbtRt     = document.querySelector('[name="sebutan_rt"]')?.value  || '<?php echo addslashes($pengaturan->sebutan_rt ?? "RT"); ?>';
    const sbtRw     = document.querySelector('[name="sebutan_rw"]')?.value  || '<?php echo addslashes($pengaturan->sebutan_rw ?? "RW"); ?>';
    const sbtKrt    = document.querySelector('[name="sebutan_ketua_rt"]')?.value  || '<?php echo addslashes($pengaturan->sebutan_ketua_rt ?? "Ketua RT"); ?>';
    const sbtKrw    = document.querySelector('[name="sebutan_ketua_rw"]')?.value  || '<?php echo addslashes($pengaturan->sebutan_ketua_rw ?? "Ketua RW"); ?>';
    const sbtLurah  = document.querySelector('[name="sebutan_lurah"]')?.value     || '<?php echo addslashes($pengaturan->sebutan_lurah ?? "Lurah"); ?>';

    const contoh = `<h1>PERATURAN DAN TATA TERTIB</h1>
<h1>${sbtRt} ${namaRt} ${sbtRw} ${namaRw}</h1>
<p style="text-align:center;"><strong>${namaKel}, Kecamatan ${namaKec}</strong></p>
<p><br></p>
<p style="text-align:center;"><em>Dengan rahmat Tuhan Yang Maha Esa, demi terciptanya lingkungan yang aman, nyaman, tertib, bersih, dan harmonis, warga ${sbtRt} ${namaRt} ${sbtRw} ${namaRw} sepakat menetapkan peraturan sebagai berikut:</em></p>
<p><br></p>
<h2>Pasal 1 – Ketertiban Umum</h2>
<ol>
<li>Warga <strong>dilarang membuat keributan</strong> yang mengganggu ketenangan antara pukul <strong>22.00 – 05.00 WIB</strong>.</li>
<li>Penggunaan sound system dengan volume tinggi hanya diperbolehkan hingga pukul <strong>22.00 WIB</strong>, kecuali ada izin ${sbtKrt}.</li>
<li>Setiap kegiatan yang mengundang banyak orang <strong>wajib memberitahu ${sbtKrt} minimal 3 hari sebelumnya</strong>.</li>
<li>Warga <strong>dilarang keras</strong> berjudi, mabuk-mabukan, atau melakukan tindakan asusila di lingkungan ${sbtRt} ${namaRt}.</li>
</ol>
<p><br></p>
<h2>Pasal 2 – Tamu dan Pendatang</h2>
<ol>
<li>Tamu yang menginap lebih dari <strong>1×24 jam wajib dilaporkan</strong> kepada ${sbtKrt} selambat-lambatnya 24 jam sejak tiba.</li>
<li>Warga yang <strong>menyewakan atau mengontrakkan rumah</strong> wajib melaporkan identitas penyewa kepada ${sbtKrt}.</li>
<li>Pendatang baru yang menetap <strong>wajib melapor dalam 3 hari</strong> dan membawa surat keterangan pindah.</li>
</ol>
<p><br></p>
<h2>Pasal 3 – Kebersihan dan Kesehatan Lingkungan</h2>
<ol>
<li>Setiap warga <strong>wajib menjaga kebersihan</strong> di depan dan sekitar rumah masing-masing.</li>
<li>Sampah dibuang pada hari pengambilan: <strong>Selasa dan Jumat pagi sebelum pukul 06.00 WIB</strong>.</li>
<li><strong>Dilarang membuang sampah</strong> ke selokan, sungai, atau lahan kosong.</li>
<li>Setiap warga <strong>wajib mengikuti kerja bakti</strong> minimal 1 kali per bulan.</li>
</ol>
<p><br></p>
<h2>Pasal 4 – Keamanan Lingkungan</h2>
<ol>
<li>Setiap kepala keluarga <strong>wajib mengikuti ronda malam</strong> sesuai jadwal yang ditetapkan.</li>
<li>Segera laporkan kejadian atau orang mencurigakan kepada <strong>${sbtKrt} atau petugas keamanan</strong>.</li>
</ol>
<p><br></p>
<h2>Pasal 5 – Iuran dan Keuangan ${sbtRt}</h2>
<ol>
<li>Setiap kepala keluarga <strong>wajib membayar iuran ${sbtRt}</strong> sesuai kesepakatan musyawarah warga.</li>
<li>Pembayaran iuran paling lambat <strong>tanggal 10 setiap bulan</strong>.</li>
<li>Laporan keuangan ${sbtRt} disampaikan secara terbuka setiap 3 bulan sekali.</li>
</ol>
<p><br></p>
<h2>Pasal 6 – Kendaraan dan Lalu Lintas</h2>
<ol>
<li>Kecepatan kendaraan di lingkungan <strong>maksimal 20 km/jam</strong>.</li>
<li>Parkir kendaraan <strong>tidak boleh menghalangi</strong> akses jalan atau pintu rumah warga lain.</li>
</ol>
<p><br></p>
<h2>Pasal 7 – Hewan Peliharaan</h2>
<ol>
<li>Hewan peliharaan <strong>wajib dikandangkan atau diikat</strong> agar tidak berkeliaran di jalan.</li>
<li>Kotoran hewan peliharaan yang mengotori area umum menjadi <strong>tanggung jawab pemiliknya</strong>.</li>
</ol>
<p><br></p>
<h2>Pasal 8 – Sanksi</h2>
<ol>
<li>Pelanggaran pertama: <strong>teguran lisan</strong> oleh ${sbtKrt}.</li>
<li>Pelanggaran berlanjut: <strong>teguran tertulis</strong>.</li>
<li>Pelanggaran berat atau berulang: dilaporkan kepada <strong>${sbtKrw} atau yang berwenang</strong>.</li>
</ol>
<p><br></p>
<h2>Pasal 9 – Ketentuan Penutup</h2>
<ol>
<li>Peraturan ini berlaku bagi <strong>seluruh warga, penyewa, dan pendatang</strong> di wilayah ${sbtRt} ${namaRt} ${sbtRw} ${namaRw}.</li>
<li>Hal-hal yang belum diatur akan diputuskan melalui <strong>musyawarah warga</strong>.</li>
<li>Peraturan ini ditinjau setiap <strong>2 tahun sekali</strong> atau sewaktu-waktu bila diperlukan.</li>
</ol>
<p><br></p>
<p style="text-align:center;"><em>Ditetapkan di ${namaKel}</em></p>`;

    quill.root.innerHTML = contoh;
    updateCount();
}

// ================================================================
// PREVIEW FOTO
// ================================================================
function previewFoto(input, previewId, placeholderId) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const prev = document.getElementById(previewId);
            const ph   = document.getElementById(placeholderId);
            if (prev) { prev.src = e.target.result; prev.style.display = 'block'; }
            if (ph)   { ph.style.display = 'none'; }
            if (previewId === 'logoPreview') {
                const kopLogo = document.getElementById('kopLogo');
                const kopPh   = document.getElementById('kopLogoPlaceholder');
                if (kopLogo) { kopLogo.src = e.target.result; kopLogo.style.display = 'block'; }
                if (kopPh)   { kopPh.style.display = 'none'; }
            }
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// ================================================================
// LIVE PREVIEW SEBUTAN JABATAN
// Setiap input.sebutan-preview meng-update elemen dengan id
// yang ada di atribut data-targets (comma-separated)
// ================================================================
document.querySelectorAll('.sebutan-preview').forEach(function(input) {
    input.addEventListener('input', function() {
        const val     = this.value.trim() || this.placeholder;
        const targets = (this.dataset.targets || '').split(',');
        targets.forEach(function(id) {
            const el = document.getElementById(id.trim());
            if (el) el.textContent = val;
        });
    });
});

// ================================================================
// LIVE PREVIEW SURAT MINI — field identitas wilayah & pengurus
// ================================================================
const previewMap = {
    'nama_rt':        ['prev_rt2','prev_rt3'],
    'nama_rw':        ['prev_rw2','prev_rw3'],
    'nama_kelurahan': ['prev_kel','prev_kel2'],
    'nama_kecamatan': ['prev_kec','prev_kec2'],
    'nama_kota':      ['prev_kota','prev_kota2'],
    'nama_ketua_rw':  ['prev_ketua_rw'],
    'nama_lurah':     ['prev_nama_lurah'],
    'footer_surat':   ['prev_footer_text'],
};
Object.keys(previewMap).forEach(function(name) {
    const input = document.querySelector('[name="' + name + '"]');
    if (!input) return;
    input.addEventListener('input', function() {
        const val = input.value.trim();
        previewMap[name].forEach(function(id) {
            const el = document.getElementById(id);
            if (!el) return;
            el.textContent = (['prev_kota','prev_kec','prev_kel'].includes(id))
                ? (val || '...').toUpperCase()
                : (val || '...');
        });
        if (name === 'nama_lurah') {
            const boxLurah = document.getElementById('prev_box_lurah');
            const row2     = document.getElementById('prev_ttd_row2');
            if (boxLurah && row2) {
                boxLurah.style.display    = val ? 'block' : 'none';
                row2.style.justifyContent = val ? 'space-between' : 'center';
            }
        }
        if (name === 'footer_surat' && val === '') {
            const elFt = document.getElementById('prev_footer_text');
            const rt   = document.getElementById('prev_rt2')?.textContent || 'RT';
            const rw   = document.getElementById('prev_rw2')?.textContent || 'RW';
            if (elFt) elFt.textContent = 'Diterbitkan oleh Sistem Informasi Manajemen ' + rt + ' ' + rw;
        }
    });
});

const nipInput = document.querySelector('[name="nip_lurah"]');
if (nipInput) nipInput.addEventListener('input', function() {
    const el = document.getElementById('prev_nip_lurah');
    if (el) el.textContent = this.value.trim() ? 'NIP: ' + this.value.trim() : '';
});
const nikRwInput = document.querySelector('[name="nik_ketua_rw"]');
if (nikRwInput) nikRwInput.addEventListener('input', function() {
    const el = document.getElementById('prev_nik_rw');
    if (el) el.textContent = this.value.trim() ? 'NIK: ' + this.value.trim() : '';
});

// ================================================================
// LOKASI CUACA (Open-Meteo geocoding)
// ================================================================
(function() {
    const inputCari = document.getElementById('inputCariKota');
    const btnCari   = document.getElementById('btnCariKota');
    const hasilDiv  = document.getElementById('hasilCariKota');
    const lokasiBox = document.getElementById('lokasiDipilih');
    const namaSpan  = document.getElementById('namaLokasiDipilih');
    const btnGanti  = document.getElementById('btnGantiLokasi');
    const inpLat    = document.getElementById('cuaca_latitude');
    const inpLon    = document.getElementById('cuaca_longitude');
    const inpKota   = document.getElementById('cuaca_kota');

    async function cariKota() {
        const q = inputCari.value.trim();
        if (q.length < 2) return;
        btnCari.innerHTML = '<i class="bi bi-hourglass-split"></i>';
        try {
            const res  = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(q)}&count=8&language=id&countryCode=ID`);
            const data = await res.json();
            tampilHasil(data.results || []);
        } catch(e) {
            hasilDiv.innerHTML = '<div class="p-2 text-danger small"><i class="bi bi-wifi-off me-1"></i>Gagal konek</div>';
            hasilDiv.style.display = 'block';
        }
        btnCari.innerHTML = '<i class="bi bi-search me-1"></i>Cari';
    }

    function tampilHasil(results) {
        if (!results.length) {
            hasilDiv.innerHTML = '<div class="p-2 text-muted small">Kota tidak ditemukan</div>';
            hasilDiv.style.display = 'block';
            return;
        }
        hasilDiv.innerHTML = results.map(r => {
            const label = [r.name, r.admin2, r.admin1].filter(Boolean).join(', ');
            return `<div class="hasil-item" data-lat="${r.latitude}" data-lon="${r.longitude}" data-nama="${label}"
                        style="padding:7px 12px;cursor:pointer;font-size:.82rem;border-bottom:1px solid #f0f9ff;"
                        onmouseover="this.style.background='#f0f9ff'" onmouseout="this.style.background='#fff'">
                        <i class="bi bi-geo-alt me-1 text-info"></i>${label}
                        <span style="font-size:.7rem;color:#94a3b8;font-family:monospace;">(${r.latitude}, ${r.longitude})</span>
                    </div>`;
        }).join('');
        hasilDiv.style.display = 'block';
        hasilDiv.querySelectorAll('.hasil-item').forEach(el => {
            el.addEventListener('click', function() {
                pilihLokasi(this.dataset.lat, this.dataset.lon, this.dataset.nama);
            });
        });
    }

    function pilihLokasi(lat, lon, nama) {
        inpLat.value  = lat;
        inpLon.value  = lon;
        inpKota.value = nama;
        namaSpan.textContent = nama;
        lokasiBox.style.display = 'block';
        hasilDiv.style.display  = 'none';
        inputCari.value = '';
    }

    btnCari?.addEventListener('click', cariKota);
    inputCari?.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); cariKota(); } });
    inputCari?.addEventListener('input',   () => { if (inputCari.value.length >= 2) cariKota(); });
    btnGanti?.addEventListener('click', () => {
        lokasiBox.style.display = 'none';
        inpLat.value = inpLon.value = inpKota.value = '';
        inputCari.value = '';
        inputCari.focus();
    });
    document.addEventListener('click', e => {
        if (!hasilDiv?.contains(e.target) && e.target !== inputCari && e.target !== btnCari) {
            if (hasilDiv) hasilDiv.style.display = 'none';
        }
    });
})();

// ================================================================
// TOGGLE YOUTUBE KEY
// ================================================================
function toggleYtKey() {
    const inp  = document.getElementById('inputYoutubeKey');
    const icon = document.getElementById('iconYtKey');
    if (inp.type === 'password') { inp.type = 'text'; icon.className = 'bi bi-eye-slash'; }
    else { inp.type = 'password'; icon.className = 'bi bi-eye'; }
}

// ================================================================
// AKTIFKAN TAB DARI FLASHDATA
// ================================================================
(function() {
    const activeTab = '<?php echo $active_tab; ?>';
    if (activeTab === 'peraturan') {
        const tabEl = document.getElementById('tab-peraturan');
        if (tabEl) new bootstrap.Tab(tabEl).show();
    }
})();
</script>

<!-- Modal Konfirmasi Hapus Foto -->
<div class="modal fade" id="modalHapusFotoPengaturan" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width:360px;">
        <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:16px 20px;">
                <div class="d-flex align-items-center gap-2">
                    <div style="width:34px;height:34px;background:#fee2e2;border-radius:9px;display:flex;align-items:center;justify-content:center;">
                        <i class="bi bi-trash-fill" style="color:#dc2626;"></i>
                    </div>
                    <h6 class="modal-title mb-0 fw-bold" style="color:#991b1b;font-size:.92rem;">Hapus Foto</h6>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" style="padding:18px 20px;">
                <p style="font-size:.84rem;color:#334155;margin-bottom:10px;">Anda akan menghapus foto:</p>
                <div style="background:#fef2f2;border:1.5px solid #fecaca;border-radius:9px;padding:10px 14px;font-weight:700;font-size:.86rem;color:#991b1b;" id="hapusFotoPengaturanLabel">-</div>
                <div style="background:#fffbeb;border:1.5px solid #fde68a;border-radius:8px;padding:8px 13px;margin-top:10px;font-size:.76rem;color:#92400e;">
                    <i class="bi bi-exclamation-triangle-fill me-1"></i>Foto akan <strong>terhapus permanen</strong>.
                </div>
            </div>
            <div class="modal-footer" style="border:none;padding:0 20px 16px;gap:8px;">
                <button type="button" class="btn" data-bs-dismiss="modal"
                        style="border-radius:8px;border:1.5px solid #e5e7eb;font-size:.81rem;font-weight:600;color:#64748b;padding:7px 18px;flex:1;">
                    <i class="bi bi-x-lg me-1"></i>Batal
                </button>
                <a href="#" id="btnKonfirmasiHapusFotoPengaturan"
                   style="border-radius:8px;border:none;font-size:.81rem;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,.24);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 _bsModalHapusFotoPengaturan = null;
function konfirmasiHapusFotoPengaturan(url, label) {
    const elLabel = document.getElementById('hapusFotoPengaturanLabel');
    const elBtn   = document.getElementById('btnKonfirmasiHapusFotoPengaturan');
    if (elLabel) elLabel.textContent = label || '-';
    if (elBtn)   elBtn.href          = url;
    const modalEl = document.getElementById('modalHapusFotoPengaturan');
    if (!modalEl) return;
    if (!_bsModalHapusFotoPengaturan) _bsModalHapusFotoPengaturan = new bootstrap.Modal(modalEl);
    _bsModalHapusFotoPengaturan.show();
}
</script>

<!-- ================================================================
     PANE TAB WHATSAPP (WAHA)
================================================================ -->
<div class="tab-pane fade <?php echo ($active_tab === 'whatsapp') ? 'show active' : ''; ?>"
     id="pane-whatsapp" role="tabpanel">

    <div class="row g-4">
        <div class="col-lg-7">

            <!-- ── KARTU STATUS WAHA ──────────────────────────────── -->
            <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                <div class="card-body p-0">
                    <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;background:linear-gradient(135deg,#dcfce7,#f0fdf4);border-radius:14px 14px 0 0;">
                        <div class="d-flex align-items-center gap-2">
                            <i class="bi bi-whatsapp" style="font-size:1.4rem;color:#25d366;"></i>
                            <div>
                                <span class="fw-bold" style="color:#166534;font-size:.95rem;">Integrasi WAHA WhatsApp API</span>
                                <div class="small text-muted" style="font-size:.72rem;">Kirim pesan otomatis langsung dari server — tanpa klik link manual</div>
                            </div>
                            <!-- Badge status aktif/nonaktif -->
                            <?php if(!empty($pengaturan->waha_enabled) && $pengaturan->waha_enabled == 1): ?>
                            <span class="badge ms-auto" style="background:#dcfce7;color:#166534;border:1px solid #86efac;font-size:.75rem;padding:5px 10px;">
                                <i class="bi bi-circle-fill me-1" style="font-size:.5rem;"></i>Aktif
                            </span>
                            <?php else: ?>
                            <span class="badge ms-auto" style="background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;font-size:.75rem;padding:5px 10px;">
                                <i class="bi bi-circle me-1" style="font-size:.5rem;"></i>Nonaktif
                            </span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="p-4">
                        <!-- Toggle aktif -->
                        <div class="d-flex align-items-center justify-content-between mb-4 p-3"
                             style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;">
                            <div>
                                <div class="fw-semibold" style="font-size:.88rem;">Aktifkan WAHA WhatsApp</div>
                                <div class="text-muted" style="font-size:.75rem;">Kirim WA otomatis untuk tagihan iuran, ulang tahun &amp; pengumuman</div>
                            </div>
                            <div class="form-check form-switch ms-3 mb-0">
                                <input class="form-check-input" type="checkbox" id="wahaEnabledToggle"
                                       role="switch" style="width:42px;height:22px;cursor:pointer;"
                                       <?php echo (!empty($pengaturan->waha_enabled) && $pengaturan->waha_enabled == 1) ? 'checked' : ''; ?>>
                            </div>
                        </div>

                        <!-- Form konfigurasi -->
                        <div class="row g-3" id="wahaConfigForm">
                            <!-- Base URL -->
                            <div class="col-12">
                                <label class="form-label small fw-semibold">
                                    <i class="bi bi-link-45deg me-1" style="color:#25d366;"></i>WAHA Base URL
                                </label>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text" style="background:#f0fdf4;border-color:#86efac;">
                                        <i class="bi bi-globe" style="color:#25d366;"></i>
                                    </span>
                                    <input type="url" id="wahaBaseUrl" class="form-control form-control-sm font-monospace"
                                           placeholder="https://waha-xxx.sumopod.my.id"
                                           value="<?php echo htmlspecialchars($pengaturan->waha_base_url ?? ''); ?>"
                                           style="font-size:.82rem;">
                                </div>
                                <small class="text-muted" style="font-size:.7rem;">
                                    <i class="bi bi-info-circle me-1"></i>URL server WAHA Anda (tanpa trailing slash)
                                </small>
                            </div>

                            <!-- API Key -->
                            <div class="col-12">
                                <label class="form-label small fw-semibold">
                                    <i class="bi bi-key-fill me-1" style="color:#25d366;"></i>WAHA API Key
                                </label>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text" style="background:#f0fdf4;border-color:#86efac;">
                                        <i class="bi bi-shield-lock" style="color:#25d366;"></i>
                                    </span>
                                    <input type="password" id="wahaApiKey" class="form-control form-control-sm font-monospace"
                                           placeholder="sha512:8eb0f..."
                                           value="<?php echo htmlspecialchars($pengaturan->waha_api_key ?? ''); ?>"
                                           style="font-size:.82rem;">
                                    <button class="btn btn-sm btn-outline-secondary" type="button"
                                            onclick="toggleWahaKey()" title="Tampilkan/sembunyikan">
                                        <i class="bi bi-eye" id="iconWahaKey"></i>
                                    </button>
                                </div>
                                <small class="text-muted" style="font-size:.7rem;">
                                    <i class="bi bi-info-circle me-1"></i>Ambil dari Dashboard WAHA → Settings → API Key
                                </small>
                            </div>

                            <!-- Session Name -->
                            <div class="col-md-5">
                                <label class="form-label small fw-semibold">
                                    <i class="bi bi-phone me-1" style="color:#25d366;"></i>Nama Session
                                </label>
                                <input type="text" id="wahaSession" class="form-control form-control-sm font-monospace"
                                       placeholder="default"
                                       value="<?php echo htmlspecialchars($pengaturan->waha_session ?? 'default'); ?>"
                                       style="font-size:.82rem;">
                                <small class="text-muted" style="font-size:.7rem;">Biasanya: <code>default</code></small>
                            </div>

                            <!-- Tombol aksi -->
                            <div class="col-12 d-flex flex-wrap gap-2 align-items-center mt-1">
                                <button type="button" id="btnSimpanWaha"
                                        style="background:linear-gradient(135deg,#25d366,#128c7e);color:#fff;border:none;border-radius:8px;padding:7px 20px;font-weight:600;font-size:.84rem;">
                                    <i class="bi bi-floppy me-1"></i>Simpan Konfigurasi
                                </button>
                                <button type="button" id="btnTestWaha"
                                        style="background:#f0fdf4;color:#166534;border:1.5px solid #86efac;border-radius:8px;padding:7px 18px;font-weight:600;font-size:.84rem;">
                                    <i class="bi bi-wifi me-1"></i>Test Koneksi
                                </button>
                                <span id="statusWahaTest" class="small" style="display:none;"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ── KARTU CARA PENGGUNAAN ──────────────────────────── -->
            <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                <div class="card-body p-0">
                    <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                        <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                            <i class="bi bi-book me-1" style="color:#25d366;"></i>Cara Penggunaan
                        </span>
                    </div>
                    <div class="p-4">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="p-3 text-center" style="background:#f0fdf4;border:1px solid #86efac;border-radius:12px;">
                                    <i class="bi bi-cash-coin" style="font-size:1.8rem;color:#25d366;"></i>
                                    <div class="fw-semibold mt-2" style="font-size:.85rem;color:#166534;">Tagih Iuran</div>
                                    <div class="text-muted mt-1" style="font-size:.72rem;">Klik tombol <strong>Kirim WA</strong> di tabel iuran. Pesan langsung terkirim ke warga.</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="p-3 text-center" style="background:#fef9c3;border:1px solid #fde68a;border-radius:12px;">
                                    <i class="bi bi-balloon-heart" style="font-size:1.8rem;color:#ca8a04;"></i>
                                    <div class="fw-semibold mt-2" style="font-size:.85rem;color:#92400e;">Ucapan Ultah</div>
                                    <div class="text-muted mt-1" style="font-size:.72rem;">Klik <strong>Kirim Ucapan</strong> di halaman Data Warga untuk warga yang ultah hari ini.</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="p-3 text-center" style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:12px;">
                                    <i class="bi bi-megaphone" style="font-size:1.8rem;color:#2563eb;"></i>
                                    <div class="fw-semibold mt-2" style="font-size:.85rem;color:#1e40af;">Pengumuman</div>
                                    <div class="text-muted mt-1" style="font-size:.72rem;">Klik <strong>Sebar WA</strong> di halaman Pengumuman untuk broadcast ke semua warga.</div>
                                </div>
                            </div>
                        </div>

                        <div class="mt-3 p-3" style="background:#fff7ed;border:1.5px solid #fed7aa;border-radius:10px;">
                            <div class="small fw-semibold mb-1" style="color:#c2410c;">
                                <i class="bi bi-exclamation-triangle-fill me-1"></i>Syarat Agar WAHA Berfungsi
                            </div>
                            <ul class="mb-0" style="font-size:.78rem;color:#7c2d12;padding-left:16px;">
                                <li>Session WAHA harus sudah <strong>WORKING</strong> (WA sudah di-scan QR Code di dashboard WAHA)</li>
                                <li>Nomor HP warga harus sudah diisi di profil akun warga</li>
                                <li>Nomor HP harus aktif di WhatsApp</li>
                                <li>Server WAHA harus dapat diakses dari server ini (internet)</li>
                            </ul>
                        </div>

                        <div class="mt-3 p-3" style="background:#f0fdfa;border:1.5px solid #99f6e4;border-radius:10px;">
                            <div class="small fw-semibold mb-1" style="color:#0f766e;">
                                <i class="bi bi-robot me-1"></i>Otomatisasi (Cron Job)
                            </div>
                            <div class="text-muted" style="font-size:.75rem;line-height:1.5;">
                                Untuk mengirim ucapan ulang tahun secara otomatis setiap hari (misal jam 08:00 pagi), pasang Cron Job di server Anda dengan perintah:
                                <div class="mt-2 p-2 bg-dark text-white rounded font-monospace" style="font-size:.68rem;">
                                    0 8 * * * php <?php echo FCPATH; ?>index.php cron birthday_wishes
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <!-- ── KOLOM KANAN: Info Dashboard WAHA ──────────────────── -->
        <div class="col-lg-5">
            <div class="card border-0 shadow-sm mb-4" style="border-radius:14px;">
                <div class="card-body p-0">
                    <div class="px-4 py-3" style="border-bottom:1px solid #f1f3f5;">
                        <span class="fw-semibold small text-muted text-uppercase" style="letter-spacing:.05em;">
                            <i class="bi bi-display me-1" style="color:#25d366;"></i>Dashboard WAHA
                        </span>
                    </div>
                    <div class="p-4">
                        <?php if(!empty($pengaturan->waha_base_url)): ?>
                        <div class="mb-3">
                            <label class="form-label small fw-semibold">Link Dashboard WAHA</label>
                            <div class="input-group input-group-sm">
                                <input type="text" id="wahaDashboardUrl" class="form-control form-control-sm font-monospace"
                                       value="<?php echo htmlspecialchars(rtrim($pengaturan->waha_base_url, '/') . '/dashboard'); ?>"
                                       readonly style="background:#fafafa;font-size:.78rem;">
                                <a href="<?php echo htmlspecialchars(rtrim($pengaturan->waha_base_url, '/') . '/dashboard'); ?>"
                                   target="_blank" class="btn btn-sm" style="background:#25d366;color:#fff;border:none;">
                                    <i class="bi bi-box-arrow-up-right"></i>
                                </a>
                            </div>
                        </div>
                        <?php endif; ?>

                        <div class="p-3" style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;font-size:.78rem;color:#166534;">
                            <div class="fw-semibold mb-2"><i class="bi bi-info-circle me-1"></i>Konfigurasi WAHA Anda</div>
                            <div class="font-monospace" style="font-size:.72rem;word-break:break-all;line-height:1.9;">
                                <div><strong>WAHA_BASE_URL</strong>=<br><?php echo htmlspecialchars($pengaturan->waha_base_url ?? '(belum diisi)'); ?></div>
                                <div class="mt-1"><strong>WAHA_SESSION</strong>=<?php echo htmlspecialchars($pengaturan->waha_session ?? 'default'); ?></div>
                                <div class="mt-1"><strong>Status</strong>:
                                    <?php if(!empty($pengaturan->waha_enabled) && $pengaturan->waha_enabled == 1): ?>
                                    <span style="color:#166534;font-weight:700;">✓ Aktif</span>
                                    <?php else: ?>
                                    <span style="color:#64748b;">✗ Nonaktif</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                                <a href="https://waha.devlike.pro/docs/" target="_blank" style="color:#7c3aed;display:block;margin-bottom:4px;">
                                    <i class="bi bi-book me-1"></i>Dokumentasi WAHA
                                </a>
                                <?php if(!empty($pengaturan->waha_base_url)): ?>
                                <a href="<?php echo htmlspecialchars(rtrim($pengaturan->waha_base_url, '/') . '/api'); ?>" target="_blank" style="color:#7c3aed;display:block;">
                                    <i class="bi bi-code-slash me-1"></i>Swagger API Explorer
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- ── END PANE WHATSAPP ─────────────────────────────────────────── -->


<!-- ================================================================
     MODAL: MASTER JABATAN
================================================================ -->
<div class="modal fade" id="modalJabatan" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg" style="border-radius:18px;">
            <div class="modal-header border-0 px-4 pt-4 pb-0">
                <h5 class="modal-title fw-bold" id="titleModalJabatan">Tambah Jabatan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="<?php echo base_url('pengaturan/simpan_jabatan'); ?>" method="post">
                <div class="modal-body p-4">
                    <input type="hidden" name="id" id="jab_id">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Nama Jabatan <span class="text-danger">*</span></label>
                        <input type="text" name="nama_jabatan" id="jab_nama" class="form-control" required placeholder="Contoh: Wakil RT, Seksi Humas">
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Kategori</label>
                        <select name="kategori" id="jab_kategori" class="form-select">
                            <option value="pengurus">Pengurus Inti</option>
                            <option value="seksi">Seksi / Departemen</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Urutan Tampil</label>
                        <input type="number" name="urutan" id="jab_urutan" class="form-control" value="0">
                        <small class="text-muted" style="font-size:11px;">Angka lebih kecil tampil lebih atas.</small>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal" style="border-radius:10px;">Batal</button>
                    <button type="submit" class="btn btn-primary px-4 fw-semibold" style="border-radius:10px;">Simpan Jabatan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ================================================================
     MODAL: STRUKTUR ORGANISASI (TETAPKAN PENGURUS)
================================================================ -->
<div class="modal fade" id="modalStruktur" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow-lg" style="border-radius:18px;">
            <div class="modal-header border-0 px-4 pt-4 pb-0">
                <h5 class="modal-title fw-bold" id="titleModalStruktur">Tetapkan Pengurus</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="<?php echo base_url('pengaturan/simpan_struktur'); ?>" method="post" enctype="multipart/form-data">
                <div class="modal-body p-4">
                    <input type="hidden" name="id" id="st_id">
                    
                    <div class="row g-4">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Pilih Jabatan <span class="text-danger">*</span></label>
                                <select name="jabatan_id" id="st_jabatan_id" class="form-select" required>
                                    <option value="">-- Pilih Jabatan --</option>
                                    <?php foreach($master_jabatan as $mj): ?>
                                    <option value="<?php echo $mj->id; ?>"><?php echo $mj->nama_jabatan; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label class="form-label small fw-bold">Sumber Data</label>
                                <div class="d-flex gap-3 mt-1">
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="sumber" id="sumberWarga" value="warga" checked onchange="toggleSumber(this.value)">
                                        <label class="form-check-label small" for="sumberWarga">Warga Terdaftar</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="sumber" id="sumberManual" value="manual" onchange="toggleSumber(this.value)">
                                        <label class="form-check-label small" for="sumberManual">Input Manual</label>
                                    </div>
                                </div>
                            </div>

                            <!-- Box Warga -->
                            <div id="boxWarga">
                                <div class="mb-3">
                                    <label class="form-label small fw-bold">Cari Warga</label>
                                    <select name="warga_id" id="st_warga_id" class="form-select select2-modal">
                                        <option value="">-- Pilih Warga --</option>
                                        <?php foreach($warga_list as $w): ?>
                                        <option value="<?php echo $w->id; ?>"><?php echo $w->nama_lengkap; ?> (NIK: <?php echo $w->nik; ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <!-- Box Manual -->
                            <div id="boxManual" style="display:none;">
                                <div class="mb-3">
                                    <label class="form-label small fw-bold">Nama Lengkap</label>
                                    <input type="text" name="nama_manual" id="st_nama_manual" class="form-control" placeholder="Input nama jika warga tidak terdaftar">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label small fw-bold">NIK (Opsional)</label>
                                    <input type="text" name="nik_manual" id="st_nik_manual" class="form-control" placeholder="16 digit NIK">
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label small fw-bold">Foto Profil</label>
                                <div class="text-center p-3 bg-light rounded-3 mb-2 border border-dashed">
                                    <img id="prev_foto_st" src="#" alt="Preview" style="display:none;width:100px;height:100px;object-fit:cover;" class="rounded-circle border shadow-sm mx-auto mb-2">
                                    <div id="ph_foto_st" class="mx-auto mb-2 text-muted" style="width:100px;height:100px;border:2px dashed #ccc;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:2rem;">
                                        <i class="bi bi-person"></i>
                                    </div>
                                    <input type="file" name="foto" id="input_foto_st" class="form-control form-control-sm" accept="image/*" onchange="previewFoto(this, 'prev_foto_st', 'ph_foto_st')">
                                    <small class="text-muted d-block mt-2" style="font-size:10px;">Gunakan rasio 1:1 untuk hasil terbaik.</small>
                                </div>
                            </div>
                            <div class="mb-0">
                                <label class="form-label small fw-bold">Urutan</label>
                                <input type="number" name="urutan" id="st_urutan" class="form-control" value="0">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal" style="border-radius:10px;">Batal</button>
                    <button type="submit" class="btn btn-success px-4 fw-semibold" style="border-radius:10px;">Simpan Pengurus</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ── WAHA: Toggle tampilkan/sembunyikan API Key ───────────────────
function toggleWahaKey() {
    const inp  = document.getElementById('wahaApiKey');
    const icon = document.getElementById('iconWahaKey');
    if (!inp) return;
    if (inp.type === 'password') {
        inp.type = 'text';
        icon.className = 'bi bi-eye-slash';
    } else {
        inp.type = 'password';
        icon.className = 'bi bi-eye';
    }
}

// ── WAHA: Simpan konfigurasi ─────────────────────────────────────
document.getElementById('btnSimpanWaha')?.addEventListener('click', function() {
    const btn = this;
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>Menyimpan...';

    const payload = {
        waha_base_url: document.getElementById('wahaBaseUrl')?.value?.trim() || '',
        waha_api_key:  document.getElementById('wahaApiKey')?.value?.trim()  || '',
        waha_session:  document.getElementById('wahaSession')?.value?.trim() || 'default',
        waha_enabled:  document.getElementById('wahaEnabledToggle')?.checked  ? 1 : 0,
    };

    fetch('<?php echo base_url("pengaturan/simpan_waha"); ?>', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
    })
    .then(r => r.json())
    .then(data => {
        tampilNotifWaha(data.message || (data.status === 'ok' ? 'Tersimpan!' : 'Gagal!'), data.status === 'ok' ? 'success' : 'danger');
        if (data.status === 'ok') {
            setTimeout(() => location.reload(), 1200);
        }
    })
    .catch(e => tampilNotifWaha('Error: ' + e.message, 'danger'))
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-floppy me-1"></i>Simpan Konfigurasi';
    });
});

// ── WAHA: Test Koneksi ───────────────────────────────────────────
document.getElementById('btnTestWaha')?.addEventListener('click', function() {
    const btn    = this;
    const status = document.getElementById('statusWahaTest');
    btn.disabled = true;
    btn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>Mengecek...';
    status.style.display = 'inline';
    status.innerHTML = '<em class="text-muted">Menghubungi server WAHA...</em>';

    const payload = {
        waha_base_url: document.getElementById('wahaBaseUrl')?.value?.trim() || '',
        waha_api_key:  document.getElementById('wahaApiKey')?.value?.trim()  || '',
        waha_session:  document.getElementById('wahaSession')?.value?.trim() || 'default',
    };

    fetch('<?php echo base_url("pengaturan/test_waha"); ?>', {
        method: 'POST',
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
    })
    .then(r => r.json())
    .then(data => {
        if (data.status === 'ok') {
            status.innerHTML = '<i class="bi bi-check-circle-fill text-success me-1"></i><span class="text-success fw-semibold">' + (data.message || 'Terhubung ✓') + '</span>';
        } else if (data.status === 'warning') {
            status.innerHTML = '<i class="bi bi-exclamation-triangle-fill text-warning me-1"></i><span class="text-warning fw-semibold">' + (data.message || 'Perhatian') + '</span>';
        } else {
            status.innerHTML = '<i class="bi bi-x-circle-fill text-danger me-1"></i><span class="text-danger">' + (data.message || 'Gagal') + '</span>';
        }
        setTimeout(() => { status.style.display = 'none'; }, 8000);
    })
    .catch(e => {
        status.innerHTML = '<span class="text-danger">Error: ' + e.message + '</span>';
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-wifi me-1"></i>Test Koneksi';
    });
});

// ── WAHA: Helper notif kecil ─────────────────────────────────────
function tampilNotifWaha(pesan, tipe) {
    const existing = document.getElementById('notifWaha');
    if (existing) existing.remove();
    const div = document.createElement('div');
    div.id = 'notifWaha';
    div.className = 'alert alert-' + tipe + ' alert-dismissible fade show mt-3';
    div.style.cssText = 'border-radius:10px;font-size:.85rem;';
    div.innerHTML = '<i class="bi bi-' + (tipe === 'success' ? 'check-circle' : 'exclamation-triangle') + ' me-2"></i>' + pesan +
        '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
    const pane = document.getElementById('pane-whatsapp');
    if (pane) pane.insertAdjacentElement('afterbegin', div);
    setTimeout(() => div.remove(), 5000);
}

// ── MASTER JABATAN ───────────────────────────────────────────
function tambahJabatan() {
    document.getElementById('jab_id').value = '';
    document.getElementById('jab_nama').value = '';
    document.getElementById('jab_kategori').value = 'pengurus';
    document.getElementById('jab_urutan').value = '0';
    document.getElementById('titleModalJabatan').innerText = 'Tambah Jabatan';
    new bootstrap.Modal(document.getElementById('modalJabatan')).show();
}

function editJabatan(data) {
    document.getElementById('jab_id').value = data.id;
    document.getElementById('jab_nama').value = data.nama_jabatan;
    document.getElementById('jab_kategori').value = data.kategori;
    document.getElementById('jab_urutan').value = data.urutan;
    document.getElementById('titleModalJabatan').innerText = 'Edit Jabatan';
    new bootstrap.Modal(document.getElementById('modalJabatan')).show();
}

function konfirmasiHapusJabatan(id, nama) {
    GlobalModal.confirm({
        title: 'Hapus Jabatan?',
        message: 'Apakah Anda yakin ingin menghapus jabatan <strong>'+nama+'</strong>? Semua pengurus yang ditetapkan pada jabatan ini juga akan terhapus.',
        confirmText: 'Ya, Hapus',
        confirmClass: 'btn-danger',
        onConfirm: () => {
            window.location.href = '<?php echo base_url("pengaturan/hapus_jabatan/"); ?>' + id;
        }
    });
}

// ── STRUKTUR PENGURUS ─────────────────────────────────────────
function toggleSumber(val) {
    if(val === 'warga') {
        document.getElementById('boxWarga').style.display = 'block';
        document.getElementById('boxManual').style.display = 'none';
    } else {
        document.getElementById('boxWarga').style.display = 'none';
        document.getElementById('boxManual').style.display = 'block';
    }
}

function tambahStruktur() {
    document.getElementById('st_id').value = '';
    document.getElementById('st_jabatan_id').value = '';
    document.getElementById('st_warga_id').value = '';
    document.getElementById('st_nama_manual').value = '';
    document.getElementById('st_nik_manual').value = '';
    document.getElementById('st_urutan').value = '0';
    
    document.getElementById('sumberWarga').checked = true;
    toggleSumber('warga');

    document.getElementById('prev_foto_st').style.display = 'none';
    document.getElementById('ph_foto_st').style.display = 'flex';
    
    document.getElementById('titleModalStruktur').innerText = 'Tetapkan Pengurus';
    new bootstrap.Modal(document.getElementById('modalStruktur')).show();
}

function editStruktur(data) {
    document.getElementById('st_id').value = data.id;
    document.getElementById('st_jabatan_id').value = data.jabatan_id;
    document.getElementById('st_warga_id').value = data.warga_id || '';
    document.getElementById('st_nama_manual').value = data.nama_manual || '';
    document.getElementById('st_nik_manual').value = data.nik_manual || '';
    document.getElementById('st_urutan').value = data.urutan;

    if(data.warga_id) {
        document.getElementById('sumberWarga').checked = true;
        toggleSumber('warga');
    } else {
        document.getElementById('sumberManual').checked = true;
        toggleSumber('manual');
    }

    if(data.foto) {
        const preview = document.getElementById('prev_foto_st');
        const ph = document.getElementById('ph_foto_st');
        preview.src = '<?php echo base_url("uploads/pengaturan/"); ?>' + data.foto;
        preview.style.display = 'block';
        ph.style.display = 'none';
    } else {
        document.getElementById('prev_foto_st').style.display = 'none';
        document.getElementById('ph_foto_st').style.display = 'flex';
    }

    document.getElementById('titleModalStruktur').innerText = 'Edit Pengurus';
    new bootstrap.Modal(document.getElementById('modalStruktur')).show();
}

function konfirmasiHapusStruktur(id, jabatan) {
    GlobalModal.confirm({
        title: 'Hapus Pengurus?',
        message: 'Apakah Anda yakin ingin menghapus pengurus untuk jabatan <strong>'+jabatan+'</strong> dari struktur?',
        confirmText: 'Ya, Hapus',
        confirmClass: 'btn-danger',
        onConfirm: () => {
            window.location.href = '<?php echo base_url("pengaturan/hapus_struktur/"); ?>' + id;
        }
    });
}
</script>
