<style>
/* ===== DETAIL KARTU KELUARGA ===== */
.btn:focus, .form-control:focus, .form-select:focus { box-shadow: none; }
.form-control:focus, .form-select:focus { border-color: #20c997; box-shadow: 0 0 0 3px rgba(32,201,151,.12); }
.form-control, .form-select { border-radius: 8px; border: 1.5px solid #e5e7eb; font-size: .88rem; padding: 9px 12px; }

/* ===== INFO KK CARD ===== */
.kk-info-card { border-radius: 14px; border: 1.5px solid #e5e7eb; box-shadow: 0 1px 5px rgba(0,0,0,.06); background: #fff; margin-bottom: 16px; overflow: hidden; }
.kk-info-card .kk-info-header { background: linear-gradient(135deg, #1abc9c 0%, #16a085 100%); padding: 14px 20px; display: flex; align-items: center; gap: 10px; }
.kk-info-card .kk-info-header .kk-no { font-size: .78rem; font-weight: 700; color: rgba(255,255,255,.85); letter-spacing: .03em; text-transform: uppercase; margin-bottom: 2px; }
.kk-info-card .kk-info-header .kk-kepala { font-size: 1rem; font-weight: 800; color: #fff; }
.kk-info-badge { background: rgba(255,255,255,.22); border-radius: 8px; padding: 6px 12px; color: #fff; font-size: .78rem; font-weight: 700; white-space: nowrap; flex-shrink: 0; }
.kk-info-body { padding: 14px 20px; display: flex; flex-wrap: wrap; gap: 16px; }
.kk-info-item { flex: 1; min-width: 140px; }
.kk-info-item .lbl { font-size: .72rem; color: #9ca3af; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; margin-bottom: 2px; }
.kk-info-item .val { font-size: .85rem; font-weight: 600; color: #374151; }

/* ===== SECTION CARD ===== */
.section-card { border-radius: 14px; border: 1.5px solid #e5e7eb; box-shadow: 0 1px 5px rgba(0,0,0,.06); overflow: hidden; margin-bottom: 16px; background: #fff; }
.section-card-header { padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #f1f3f5; background: #fff; }
.section-card-header .title { font-size: .85rem; font-weight: 700; color: #374151; display: flex; align-items: center; gap: 6px; }
.section-card-header .title i { color: #20c997; }

/* ===== TABLE ===== */
.kk-table th { font-size: .72rem; text-transform: uppercase; letter-spacing: .04em; color: #6b7280; font-weight: 700; padding: 10px 14px; background: #f8fffe; border-bottom: 1.5px solid #e5e7eb; white-space: nowrap; }
.kk-table td { padding: 10px 14px; vertical-align: middle; font-size: .84rem; border-bottom: 1px solid #f3f4f6; }
.kk-table tbody tr:last-child td { border-bottom: none; }
.kk-table tbody tr:hover { background: #f8fffe; }

/* ===== ROW MENINGGAL ===== */
.row-meninggal td { opacity: 0.55; background: #fafafa !important; }
.row-meninggal:hover td { background: #f3f4f6 !important; }
.row-meninggal .nama-warga { text-decoration: line-through; color: #9ca3af !important; }

/* ===== STATUS BADGES ===== */
.status-badge { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 999px; font-size: .72rem; font-weight: 600; white-space: nowrap; }
.sb-kepala    { background:#dbeafe; color:#1e40af; border:1px solid #93c5fd; }
.sb-istri     { background:#cffafe; color:#155e75; border:1px solid #a5f3fc; }
.sb-anak      { background:#dcfce7; color:#166534; border:1px solid #bbf7d0; }
.sb-secondary { background:#f3f4f6; color:#6b7280; border:1px solid #e5e7eb; }
.sb-warning   { background:#fef3c7; color:#92400e; border:1px solid #fde68a; }
.sb-meninggal { background:#f3f4f6; color:#6b7280; border:1px solid #d1d5db; }

.dom-tetap     { background:#dcfce7; color:#166534; border:1px solid #bbf7d0; }
.dom-kost      { background:#fef3c7; color:#92400e; border:1px solid #fde68a; }
.dom-kontrak   { background:#cffafe; color:#155e75; border:1px solid #a5f3fc; }
.dom-pendatang { background:#fee2e2; color:#991b1b; border:1px solid #fecaca; }
.dom-sementara { background:#f3f4f6; color:#6b7280; border:1px solid #e5e7eb; }

/* ===== ACTION BUTTONS ===== */
.btn-act { font-size:.78rem; padding:5px 10px; border-radius:7px; font-weight:600; white-space:nowrap; display:inline-flex; align-items:center; gap:4px; }
.btn-act-edit   { background:#fef3c7; border:1px solid #fde68a; color:#92400e; }
.btn-act-edit:hover { background:#fde68a; color:#78350f; }
.btn-act-delete { background:#fee2e2; border:1px solid #fecaca; color:#991b1b; }
.btn-act-delete:hover { background:#fecaca; color:#7f1d1d; }
.btn-act-death  { background:#f3f4f6; border:1px solid #9ca3af; color:#374151; }
.btn-act-death:hover { background:#e5e7eb; color:#111827; }
.btn-act-hapus-meninggal { background:#fee2e2; border:1px solid #fecaca; color:#991b1b; }
.btn-act-hapus-meninggal:hover { background:#fecaca; color:#7f1d1d; }

/* ===== HEADER BUTTONS ===== */
.kk-header-btns { display:flex; gap:8px; flex-wrap:wrap; }
.kk-header-btns .btn { font-size:.82rem; padding:7px 14px; border-radius:8px; font-weight:600; white-space:nowrap; }

/* ===== MOBILE ===== */
.desktop-table  { display: block; }
.mobile-kk-list { display: none; }

/* ===== MODAL ===== */
.modal-content { border-radius: 14px; border: none; box-shadow: 0 8px 32px rgba(0,0,0,.12); }
.modal-header { padding: 16px 20px; border-bottom: 1px solid #f1f3f5; }
.modal-body   { padding: 20px; }
.modal-footer { padding: 14px 20px; border-top: 1px solid #f1f3f5; }
.form-label { font-size: .8rem; font-weight: 700; color: #374151; margin-bottom: 4px; }

/* ===== MOBILE RESPONSIVE ===== */
@media (max-width: 767.98px) {
    .container-fluid { padding-left: 12px !important; padding-right: 12px !important; }
    .kk-page-header { flex-direction: column !important; align-items: flex-start !important; gap: 10px; }
    .kk-header-btns { display: grid; grid-template-columns: 1fr 1fr; width: 100%; }
    .kk-header-btns .btn { justify-content: center; }
    .kk-info-header { flex-wrap: wrap; gap: 8px; }
    .kk-info-body { gap: 10px; }
    .kk-info-item { min-width: calc(50% - 8px); flex: none; }
    .desktop-table  { display: none !important; }
    .mobile-kk-list { display: flex !important; flex-direction: column; gap: 8px; padding: 10px; }
}
</style>

<?php
$_can_see_nokk = in_array($this->session->userdata('role'), ['admin','rt','ketua_rt','sekretaris']);
$_is_admin_rt  = in_array($this->session->userdata('role'), ['admin','rt']);

// Hitung jiwa aktif (tidak meninggal)
$jiwa_aktif = 0;
$jiwa_meninggal = 0;
foreach($anggota as $a) {
    if(!empty($a->status_meninggal) && $a->status_meninggal == 1) {
        $jiwa_meninggal++;
    } else {
        $jiwa_aktif++;
    }
}
?>

<div class="container-fluid px-2 px-md-3 py-3">

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-3 kk-page-header">
        <div>
            <a href="<?php echo base_url('kartu-keluarga'); ?>" class="text-decoration-none d-inline-flex align-items-center gap-1 mb-1" style="font-size:.8rem; color:#6b7280;">
                <i class="bi bi-arrow-left"></i> Kembali ke Daftar KK
            </a>
            <h5 class="mb-0 fw-bold text-dark">
                <i class="bi bi-house-door me-2" style="color:#20c997;"></i>Detail Kartu Keluarga
            </h5>
        </div>
        <?php if($_is_admin_rt): ?>
        <div class="kk-header-btns">
            <a href="<?php echo base_url('kartu-keluarga/edit/'.$kk->id); ?>" class="btn btn-outline-warning d-flex align-items-center gap-1">
                <i class="bi bi-pencil"></i> Edit KK
            </a>
            <button class="btn d-flex align-items-center gap-1" data-bs-toggle="modal" data-bs-target="#modalTambahAnggota"
                style="background:#20c997; border-color:#20c997; color:#fff;">
                <i class="bi bi-person-plus"></i> Tambah Anggota
            </button>
        </div>
        <?php endif; ?>
    </div>

    <!-- Flash messages -->
    <?php if($this->session->flashdata('success')): ?>
    <div class="alert alert-success alert-dismissible fade show" style="border-radius:10px; font-size:.84rem; border:1.5px solid #6ee7b7;">
        <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" style="border-radius:10px; font-size:.84rem;">
        <i class="bi bi-exclamation-circle me-2"></i><?php echo $this->session->flashdata('error'); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <!-- INFO KK CARD -->
    <div class="kk-info-card">
        <div class="kk-info-header">
            <div class="flex-grow-1">
                <div class="kk-no"><i class="bi bi-credit-card-2-front me-1"></i>Kartu Keluarga</div>
                <div class="kk-kepala"><?php echo $kk->nama_kepala_keluarga ?: '<span style="opacity:.7; font-style:italic;">Belum ditetapkan</span>'; ?></div>
            </div>
            <div class="d-flex flex-column gap-1 align-items-end">
                <div class="kk-info-badge">
                    <i class="bi bi-people-fill me-1"></i><?php echo $jiwa_aktif; ?> jiwa aktif
                </div>
                <?php if($jiwa_meninggal > 0): ?>
                <div class="kk-info-badge" style="background:rgba(0,0,0,.18); font-size:.7rem;">
                    <i class="bi bi-heartbreak me-1"></i><?php echo $jiwa_meninggal; ?> meninggal
                </div>
                <?php endif; ?>
            </div>
        </div>
        <div class="kk-info-body">
            <?php if($_can_see_nokk): ?>
            <div class="kk-info-item">
                <div class="lbl">Nomor KK</div>
                <div class="val"><code style="font-size:.83rem; color:#374151;"><?php echo $kk->no_kk; ?></code></div>
            </div>
            <?php endif; ?>
            <div class="kk-info-item">
                <div class="lbl">Alamat</div>
                <div class="val"><?php echo $kk->alamat; ?><?php if($kk->rt || $kk->rw): ?> <span style="color:#9ca3af;">— RT <?php echo $kk->rt; ?>/RW <?php echo $kk->rw; ?></span><?php endif; ?></div>
            </div>
            <?php if(!empty($kk->kelurahan)): ?>
            <div class="kk-info-item">
                <div class="lbl">Kelurahan</div>
                <div class="val"><?php echo $kk->kelurahan; ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- TABEL ANGGOTA -->
    <?php
    $hub_cfg = [
        'kepala_keluarga'=>['label'=>'Kepala KK',  'cls'=>'sb-kepala'],
        'istri'          =>['label'=>'Istri',      'cls'=>'sb-istri'],
        'anak'           =>['label'=>'Anak',       'cls'=>'sb-anak'],
        'cucu'           =>['label'=>'Cucu',       'cls'=>'sb-anak'],
        'orang_tua'      =>['label'=>'Orang Tua',  'cls'=>'sb-secondary'],
        'mertua'         =>['label'=>'Mertua',     'cls'=>'sb-secondary'],
        'famili_lain'    =>['label'=>'Famili Lain','cls'=>'sb-secondary'],
        'pembantu'       =>['label'=>'Pembantu',   'cls'=>'sb-warning'],
        'lainnya'        =>['label'=>'Lainnya',    'cls'=>'sb-secondary'],
    ];
    $dom_cfg = [
        'tetap'    =>['label'=>'Tetap',    'cls'=>'dom-tetap'],
        'kost'     =>['label'=>'Kost',     'cls'=>'dom-kost'],
        'kontrak'  =>['label'=>'Kontrak',  'cls'=>'dom-kontrak'],
        'pendatang'=>['label'=>'Pendatang','cls'=>'dom-pendatang'],
        'sementara'=>['label'=>'Sementara','cls'=>'dom-sementara'],
    ];
    $dom_border = [
        'tetap'=>'#1abc9c','kost'=>'#f59e0b','kontrak'=>'#0ea5e9',
        'pendatang'=>'#ef4444','sementara'=>'#9ca3af'
    ];
    $hasAnggota = !empty($anggota);
    ?>

    <div class="section-card">
        <div class="section-card-header">
            <div class="title">
                <i class="bi bi-people-fill"></i>Anggota Keluarga
            </div>
            <span style="font-size:.75rem; color:#9ca3af; font-weight:600;"><?php echo count($anggota); ?> orang</span>
        </div>

        <?php if($hasAnggota): ?>

        <!-- Desktop Table -->
        <div class="desktop-table table-responsive">
            <table class="table kk-table mb-0">
                <thead><tr>
                    <th style="width:44px;">No</th>
                    <?php if($_can_see_nokk): ?><th>NIK</th><?php endif; ?>
                    <th>Nama Lengkap</th>
                    <th>L/P</th>
                    <th>Status Hubungan</th>
                    <th>Domisili</th>
                    <th>Pekerjaan</th>
                    <th>Status</th>
                    <?php if($_is_admin_rt): ?>
                    <th class="text-center">Aksi</th>
                    <?php endif; ?>
                </tr></thead>
                <tbody>
                <?php $no=1; foreach($anggota as $a):
                    $hub         = $a->status_hubungan ?? 'lainnya';
                    $dom         = $a->status_domisili ?? 'tetap';
                    $h           = $hub_cfg[$hub] ?? ['label'=>$hub, 'cls'=>'sb-secondary'];
                    $d           = $dom_cfg[$dom] ?? ['label'=>$dom, 'cls'=>'dom-sementara'];
                    $isMenuinggal = (!empty($a->status_meninggal) && $a->status_meninggal == 1);
                    $isKepala    = ($hub === 'kepala_keluarga');
                ?>
                <tr class="<?php echo $isMenuinggal ? 'row-meninggal' : ''; ?>">
                    <td><?php echo $no++; ?></td>
                    <?php if($_can_see_nokk): ?>
                    <td><code style="font-size:.78rem; color:#6b7280;"><?php echo $a->nik ?? '-'; ?></code></td>
                    <?php endif; ?>
                    <td>
                        <strong class="nama-warga" style="font-size:.84rem;"><?php echo $a->nama_lengkap ?? '-'; ?></strong>
                        <?php if($isMenuinggal && !empty($a->tanggal_meninggal)): ?>
                        <br><small style="color:#ef4444; font-size:.72rem;"><i class="bi bi-heartbreak me-1"></i>Meninggal <?php echo date('d/m/Y', strtotime($a->tanggal_meninggal)); ?></small>
                        <?php elseif(!empty($a->tempat_lahir) && !empty($a->tanggal_lahir)): ?>
                        <br><small class="text-muted"><?php echo $a->tempat_lahir.', '.date('d/m/Y',strtotime($a->tanggal_lahir)); ?></small>
                        <?php endif; ?>
                        <?php if($isMenuinggal && !empty($a->keterangan_meninggal)): ?>
                        <br><small class="text-muted" style="font-style:italic;"><?php echo $a->keterangan_meninggal; ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if(($a->jenis_kelamin??'')==='L'): ?>
                            <span style="color:#3b82f6; font-weight:700; font-size:.83rem;">L</span>
                        <?php else: ?>
                            <span style="color:#ef4444; font-weight:700; font-size:.83rem;">P</span>
                        <?php endif; ?>
                    </td>
                    <td><span class="status-badge <?php echo $h['cls']; ?>"><?php echo $h['label']; ?></span></td>
                    <td>
                        <span class="status-badge <?php echo $d['cls']; ?>"><?php echo $d['label']; ?></span>
                        <?php if(!empty($a->keterangan_domisili)): ?><br><small class="text-muted"><?php echo $a->keterangan_domisili; ?></small><?php endif; ?>
                    </td>
                    <td style="color:#6b7280;"><?php echo $a->pekerjaan ?? '-'; ?></td>
                    <td>
                        <?php if($isMenuinggal): ?>
                        <span class="status-badge sb-meninggal"><i class="bi bi-heartbreak me-1"></i>Meninggal</span>
                        <?php else: ?>
                        <span class="status-badge dom-tetap"><i class="bi bi-check-circle me-1"></i>Aktif</span>
                        <?php endif; ?>
                    </td>
                    <?php if($_is_admin_rt): ?>
                    <td class="text-center">
                        <div class="d-flex gap-1 justify-content-center flex-wrap">
                            <?php if(!$isMenuinggal): ?>
                            <!-- Tombol Edit -->
                            <button class="btn-act btn-act-edit btn"
                                onclick="editAnggota(<?php echo $a->id; ?>,'<?php echo addslashes($a->nik??''); ?>','<?php echo addslashes($a->nama_lengkap??''); ?>','<?php echo $a->jenis_kelamin??''; ?>','<?php echo addslashes($a->tempat_lahir??''); ?>','<?php echo $a->tanggal_lahir??''; ?>','<?php echo $a->agama??''; ?>','<?php echo $a->status_perkawinan??''; ?>','<?php echo addslashes($a->pekerjaan??''); ?>','<?php echo $hub; ?>','<?php echo $dom; ?>','<?php echo addslashes($a->keterangan_domisili??''); ?>')"
                                title="Edit Data">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <!-- Tombol Tandai Meninggal -->
                            <button class="btn-act btn-act-death btn"
                                onclick="bukaModalMenuinggal(<?php echo $a->id; ?>, '<?php echo addslashes($a->nama_lengkap??''); ?>')"
                                title="Tandai Meninggal">
                                <i class="bi bi-heartbreak"></i>
                            </button>
                            <!-- Tombol Hapus (bukan kepala) -->
                            <?php if(!$isKepala): ?>
                            <a href="<?php echo base_url('kartu-keluarga/hapus_anggota/'.$a->id); ?>"
                               class="btn-act btn-act-delete btn"
                               onclick="return confirm('Yakin hapus anggota ini? Data akan terhapus permanen.')"
                               title="Hapus Data">
                                <i class="bi bi-trash"></i>
                            </a>
                            <?php endif; ?>
                            <?php else: ?>
                            <!-- Warga Meninggal: hanya tombol hapus permanen -->
                            <a href="<?php echo base_url('kartu-keluarga/hapus_warga_meninggal/'.$a->id); ?>"
                               class="btn-act btn-act-hapus-meninggal btn"
                               onclick="return confirm('Hapus permanen data <?php echo addslashes($a->nama_lengkap??''); ?> yang telah meninggal dari KK ini?')"
                               title="Hapus dari KK">
                                <i class="bi bi-trash me-1"></i>Hapus dari KK
                            </a>
                            <?php endif; ?>
                        </div>
                    </td>
                    <?php endif; ?>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Mobile Card List -->
        <div class="mobile-kk-list">
            <?php foreach($anggota as $a):
                $hub         = $a->status_hubungan ?? 'lainnya';
                $dom         = $a->status_domisili ?? 'tetap';
                $h           = $hub_cfg[$hub] ?? ['label'=>$hub, 'cls'=>'sb-secondary'];
                $d           = $dom_cfg[$dom] ?? ['label'=>$dom, 'cls'=>'dom-sementara'];
                $bc          = $dom_border[$dom] ?? '#e5e7eb';
                $isKepala    = ($hub === 'kepala_keluarga');
                $isMenuinggal = (!empty($a->status_meninggal) && $a->status_meninggal == 1);
            ?>
            <div style="border-radius:11px; border:1.5px solid <?php echo $isMenuinggal ? '#e5e7eb' : '#f1f3f5'; ?>; border-left:4px solid <?php echo $isMenuinggal ? '#9ca3af' : $bc; ?>; background:<?php echo $isMenuinggal ? '#f9fafb' : '#fff'; ?>; padding:12px 14px; opacity:<?php echo $isMenuinggal ? '0.7' : '1'; ?>;">
                <div class="d-flex justify-content-between align-items-start mb-1">
                    <div>
                        <div class="fw-semibold <?php echo $isMenuinggal ? 'text-decoration-line-through text-muted' : ''; ?>" style="font-size:.88rem;"><?php echo $a->nama_lengkap ?? '-'; ?></div>
                        <?php if($_can_see_nokk): ?>
                        <code style="font-size:.73rem; color:#9ca3af;"><?php echo $a->nik ?? '-'; ?></code>
                        <?php endif; ?>
                    </div>
                    <div class="d-flex flex-column gap-1 align-items-end">
                        <span class="status-badge <?php echo $h['cls']; ?> flex-shrink-0 ms-2"><?php echo $h['label']; ?></span>
                        <?php if($isMenuinggal): ?>
                        <span class="status-badge sb-meninggal flex-shrink-0 ms-2"><i class="bi bi-heartbreak me-1"></i>Meninggal</span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if($isMenuinggal && !empty($a->tanggal_meninggal)): ?>
                <div style="font-size:.76rem; color:#ef4444; margin-bottom:6px;">
                    <i class="bi bi-heartbreak me-1"></i>
                    Meninggal <?php echo date('d/m/Y', strtotime($a->tanggal_meninggal)); ?>
                    <?php if(!empty($a->keterangan_meninggal)): ?> — <?php echo $a->keterangan_meninggal; ?><?php endif; ?>
                </div>
                <?php endif; ?>
                <div class="d-flex flex-wrap gap-2 align-items-center mt-1 mb-2" style="font-size:.75rem; color:#6b7280;">
                    <span class="status-badge <?php echo $d['cls']; ?>"><?php echo $d['label']; ?></span>
                    <span>·</span>
                    <span><?php echo ($a->jenis_kelamin??'')==='L' ? '<span style="color:#3b82f6;font-weight:700;">Laki-laki</span>' : '<span style="color:#ef4444;font-weight:700;">Perempuan</span>'; ?></span>
                    <?php if(!empty($a->pekerjaan)): ?><span>·</span><span><?php echo $a->pekerjaan; ?></span><?php endif; ?>
                    <?php if(!empty($a->tempat_lahir) && !empty($a->tanggal_lahir) && !$isMenuinggal): ?>
                    <span>·</span><span><?php echo $a->tempat_lahir.', '.date('d/m/Y',strtotime($a->tanggal_lahir)); ?></span>
                    <?php endif; ?>
                </div>
                <?php if($_is_admin_rt): ?>
                <div class="d-flex gap-2" style="border-top:1px solid #f3f4f6; padding-top:9px;">
                    <?php if(!$isMenuinggal): ?>
                    <button class="btn flex-fill fw-semibold btn-act-edit"
                        style="border-radius:8px; font-size:.8rem; padding:7px;"
                        onclick="editAnggota(<?php echo $a->id; ?>,'<?php echo addslashes($a->nik??''); ?>','<?php echo addslashes($a->nama_lengkap??''); ?>','<?php echo $a->jenis_kelamin??''; ?>','<?php echo addslashes($a->tempat_lahir??''); ?>','<?php echo $a->tanggal_lahir??''; ?>','<?php echo $a->agama??''; ?>','<?php echo $a->status_perkawinan??''; ?>','<?php echo addslashes($a->pekerjaan??''); ?>','<?php echo $hub; ?>','<?php echo $dom; ?>','<?php echo addslashes($a->keterangan_domisili??''); ?>')">
                        <i class="bi bi-pencil me-1"></i>Edit
                    </button>
                    <button class="btn fw-semibold btn-act-death"
                        style="border-radius:8px; font-size:.8rem; padding:7px 12px;"
                        onclick="bukaModalMenuinggal(<?php echo $a->id; ?>, '<?php echo addslashes($a->nama_lengkap??''); ?>')">
                        <i class="bi bi-heartbreak"></i>
                    </button>
                    <?php if(!$isKepala): ?>
                    <a href="<?php echo base_url('kartu-keluarga/hapus_anggota/'.$a->id); ?>"
                       class="btn fw-semibold btn-act-delete"
                       style="border-radius:8px; font-size:.8rem; padding:7px 12px;"
                       onclick="return confirm('Yakin hapus anggota ini?')">
                        <i class="bi bi-trash"></i>
                    </a>
                    <?php endif; ?>
                    <?php else: ?>
                    <a href="<?php echo base_url('kartu-keluarga/hapus_warga_meninggal/'.$a->id); ?>"
                       class="btn flex-fill fw-semibold btn-act-hapus-meninggal"
                       style="border-radius:8px; font-size:.8rem; padding:7px; justify-content:center;"
                       onclick="return confirm('Hapus permanen data <?php echo addslashes($a->nama_lengkap??''); ?> dari KK ini?')">
                        <i class="bi bi-trash me-1"></i>Hapus dari KK
                    </a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <?php else: ?>
        <div class="text-center py-5 text-muted">
            <i class="bi bi-people fs-1 d-block mb-2 opacity-50"></i>
            <div class="fw-semibold mb-1">Belum ada anggota keluarga</div>
            <?php if($_is_admin_rt): ?>
            <button class="btn btn-sm mt-1" data-bs-toggle="modal" data-bs-target="#modalTambahAnggota"
                style="background:#20c997; color:#fff; border-radius:8px; font-size:.82rem;">
                <i class="bi bi-person-plus me-1"></i>Tambah Anggota
            </button>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

</div>

<?php if($_is_admin_rt): ?>

<!-- ===== MODAL TAMBAH ===== -->
<div class="modal fade" id="modalTambahAnggota" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header" style="background:linear-gradient(135deg,#1abc9c,#16a085);">
                <h6 class="modal-title text-white fw-bold"><i class="bi bi-person-plus me-2"></i>Tambah Anggota Baru</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="<?php echo base_url('kartu-keluarga/tambah_anggota/'.$kk->id); ?>" method="post">
                <div class="modal-body">
                    <div style="background:#f0fdf4; border:1.5px solid #6ee7b7; border-radius:8px; padding:9px 14px; font-size:.8rem; color:#065f46; margin-bottom:14px;">
                        <i class="bi bi-house-door me-1"></i>
                        <strong>KK <?php echo $kk->no_kk; ?></strong> — <?php echo $kk->alamat; ?>
                    </div>
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">NIK <span class="text-danger">*</span></label>
                            <input type="text" name="nik" class="form-control" maxlength="16" required placeholder="16 digit NIK">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
                            <input type="text" name="nama_lengkap" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status Hubungan <span class="text-danger">*</span></label>
                            <select name="status_hubungan" class="form-select" required>
                                <option value="">-- Pilih --</option>
                                <?php foreach($status_hubungan as $k=>$v): ?>
                                <option value="<?php echo $k; ?>"><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Jenis Kelamin</label>
                            <select name="jenis_kelamin" class="form-select">
                                <option value="">-- Pilih --</option>
                                <option value="L">Laki-laki</option>
                                <option value="P">Perempuan</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Tempat Lahir</label>
                            <input type="text" name="tempat_lahir" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Tanggal Lahir</label>
                            <input type="date" name="tanggal_lahir" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Agama</label>
                            <select name="agama" class="form-select">
                                <option value="">-- Pilih --</option>
                                <option value="Islam">Islam</option>
                                <option value="Kristen">Kristen</option>
                                <option value="Katolik">Katolik</option>
                                <option value="Hindu">Hindu</option>
                                <option value="Buddha">Buddha</option>
                                <option value="Konghucu">Konghucu</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status Perkawinan</label>
                            <select name="status_perkawinan" class="form-select">
                                <option value="">-- Pilih --</option>
                                <option value="belum_kawin">Belum Kawin</option>
                                <option value="kawin">Kawin</option>
                                <option value="cerai_hidup">Cerai Hidup</option>
                                <option value="cerai_mati">Cerai Mati</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Pekerjaan</label>
                            <input type="text" name="pekerjaan" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status Domisili</label>
                            <select name="status_domisili" class="form-select">
                                <?php foreach($status_domisili as $k=>$v): ?>
                                <option value="<?php echo $k; ?>"><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Keterangan Domisili</label>
                            <input type="text" name="keterangan_domisili" class="form-control" placeholder="Opsional">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal" style="border-radius:8px;">Batal</button>
                    <button type="submit" class="btn btn-sm fw-bold" style="background:#20c997; color:#fff; border-radius:8px; padding:7px 20px;">
                        <i class="bi bi-save me-1"></i>Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ===== MODAL EDIT ===== -->
<div class="modal fade" id="modalEditAnggota" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header" style="background:#fffbeb; border-bottom:1.5px solid #fde68a;">
                <h6 class="modal-title fw-bold" style="color:#92400e;"><i class="bi bi-pencil me-2"></i>Edit Anggota</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formEditAnggota" action="" method="post">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">NIK</label>
                            <input type="text" id="e_nik" class="form-control" style="background:#f9fafb; color:#9ca3af;" readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
                            <input type="text" name="nama_lengkap" id="e_nama" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status Hubungan <span class="text-danger">*</span></label>
                            <select name="status_hubungan" id="e_hub" class="form-select" required>
                                <?php foreach($status_hubungan as $k=>$v): ?>
                                <option value="<?php echo $k; ?>"><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Jenis Kelamin</label>
                            <select name="jenis_kelamin" id="e_jk" class="form-select">
                                <option value="">-- Pilih --</option>
                                <option value="L">Laki-laki</option>
                                <option value="P">Perempuan</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Tempat Lahir</label>
                            <input type="text" name="tempat_lahir" id="e_tempat" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Tanggal Lahir</label>
                            <input type="date" name="tanggal_lahir" id="e_tgl" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Agama</label>
                            <select name="agama" id="e_agama" class="form-select">
                                <option value="">-- Pilih --</option>
                                <option value="Islam">Islam</option>
                                <option value="Kristen">Kristen</option>
                                <option value="Katolik">Katolik</option>
                                <option value="Hindu">Hindu</option>
                                <option value="Buddha">Buddha</option>
                                <option value="Konghucu">Konghucu</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status Perkawinan</label>
                            <select name="status_perkawinan" id="e_kawin" class="form-select">
                                <option value="">-- Pilih --</option>
                                <option value="belum_kawin">Belum Kawin</option>
                                <option value="kawin">Kawin</option>
                                <option value="cerai_hidup">Cerai Hidup</option>
                                <option value="cerai_mati">Cerai Mati</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Pekerjaan</label>
                            <input type="text" name="pekerjaan" id="e_pekerjaan" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status Domisili</label>
                            <select name="status_domisili" id="e_dom" class="form-select">
                                <?php foreach($status_domisili as $k=>$v): ?>
                                <option value="<?php echo $k; ?>"><?php echo $v; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Keterangan Domisili</label>
                            <input type="text" name="keterangan_domisili" id="e_ket" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal" style="border-radius:8px;">Batal</button>
                    <button type="submit" class="btn btn-sm fw-bold" style="background:#f59e0b; color:#fff; border:none; border-radius:8px; padding:7px 20px;">
                        <i class="bi bi-save me-1"></i>Update
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ===== MODAL TANDAI MENINGGAL ===== -->
<div class="modal fade" id="modalMenuinggal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background:#fef2f2; border-bottom:1.5px solid #fecaca;">
                <h6 class="modal-title fw-bold" style="color:#991b1b;">
                    <i class="bi bi-heartbreak me-2"></i>Tandai Warga Meninggal
                </h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formMenuinggal" action="" method="post">
                <div class="modal-body">
                    <div style="background:#fef2f2; border:1.5px solid #fecaca; border-radius:8px; padding:10px 14px; font-size:.82rem; color:#991b1b; margin-bottom:16px;">
                        <i class="bi bi-exclamation-triangle me-1"></i>
                        Data warga <strong id="namaMenuinggal"></strong> akan ditandai sebagai <strong>meninggal dunia</strong>.
                        Data tetap tersimpan di KK sebagai catatan.
                    </div>
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label">Tanggal Meninggal <span class="text-danger">*</span></label>
                            <input type="date" name="tanggal_meninggal" id="m_tgl" class="form-control" required
                                max="<?php echo date('Y-m-d'); ?>">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Keterangan</label>
                            <input type="text" name="keterangan_meninggal" class="form-control"
                                placeholder="Contoh: Sakit, kecelakaan, dll. (opsional)">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal" style="border-radius:8px;">Batal</button>
                    <button type="submit" class="btn btn-sm fw-bold" style="background:#ef4444; color:#fff; border:none; border-radius:8px; padding:7px 20px;">
                        <i class="bi bi-heartbreak me-1"></i>Tandai Meninggal
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Edit Anggota
function editAnggota(id, nik, nama, jk, tempat, tgl, agama, kawin, pekerjaan, hub, dom, ket) {
    document.getElementById('formEditAnggota').action = '<?php echo base_url('kartu-keluarga/edit_anggota/'); ?>' + id;
    document.getElementById('e_nik').value       = nik;
    document.getElementById('e_nama').value      = nama;
    document.getElementById('e_tempat').value    = tempat;
    document.getElementById('e_tgl').value       = tgl;
    document.getElementById('e_pekerjaan').value = pekerjaan;
    document.getElementById('e_ket').value       = ket;
    setVal('e_jk',    jk);
    setVal('e_agama', agama);
    setVal('e_kawin', kawin);
    setVal('e_hub',   hub);
    setVal('e_dom',   dom);
    new bootstrap.Modal(document.getElementById('modalEditAnggota')).show();
}

// Buka Modal Meninggal
function bukaModalMenuinggal(id, nama) {
    document.getElementById('formMenuinggal').action = '<?php echo base_url('kartu-keluarga/tandai_meninggal/'); ?>' + id;
    document.getElementById('namaMenuinggal').textContent = nama;
    document.getElementById('m_tgl').value = new Date().toISOString().split('T')[0];
    new bootstrap.Modal(document.getElementById('modalMenuinggal')).show();
}

function setVal(id, val) {
    const el = document.getElementById(id);
    if (!el) return;
    for (let i = 0; i < el.options.length; i++) {
        if (el.options[i].value == val) { el.selectedIndex = i; break; }
    }
}
</script>

<?php endif; // end admin/rt ?>