<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; }
.btn-act-upload { background:#e0f2fe; border:1px solid #bae6fd; color:#0284c7; }
.btn-act-upload:hover { background:#bae6fd; color:#0369a1; }

/* ===== 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; }

/* ===== SHOW/HIDE TABLE vs CARDS ===== */
.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: 10px; padding: 12px; }
}

/* ===== MOBILE CARD ===== */
.member-card { border-radius: 12px; border: 1.5px solid #e5e7eb; background: #fff; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,.05); transition: box-shadow .15s; }
.member-card:active { box-shadow: 0 2px 8px rgba(0,0,0,.1); }
.member-card.card-meninggal { opacity: 0.65; background: #f9fafb; border-color: #e5e7eb; }
.member-card-inner { display: flex; gap: 0; }
.member-card-stripe { width: 5px; flex-shrink: 0; }
.member-card-body { flex: 1; padding: 11px 13px; min-width: 0; }
.mc-row-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; margin-bottom: 4px; }
.mc-nama { font-size: .88rem; font-weight: 700; color: #1f2937; line-height: 1.3; word-break: break-word; }
.mc-nama.meninggal { text-decoration: line-through; color: #9ca3af !important; }
.mc-nik { font-family: monospace; font-size: .71rem; color: #9ca3af; margin-top: 2px; letter-spacing: .02em; }
.mc-info-row { display: flex; flex-wrap: wrap; gap: 5px 10px; margin: 6px 0; align-items: center; }
.mc-info-item { display: flex; align-items: center; gap: 4px; font-size: .75rem; color: #6b7280; }
.mc-info-item i { font-size: .72rem; color: #9ca3af; }
.mc-meninggal-info { display: flex; align-items: center; gap: 5px; font-size: .75rem; color: #ef4444; background: #fff5f5; border: 1px solid #fecaca; border-radius: 6px; padding: 5px 9px; margin-bottom: 8px; }
.mc-hp { display: inline-flex; align-items: center; gap: 4px; font-size: .75rem; color: #20c997; text-decoration: none; font-weight: 600; }
.mc-hp:hover { color: #16a085; }
.mc-actions { display: flex; gap: 7px; border-top: 1px solid #f3f4f6; padding-top: 9px; margin-top: 4px; }
.mc-btn { flex: 1; display: inline-flex; align-items: center; justify-content: center; gap: 5px; font-size: .78rem; font-weight: 600; padding: 8px 10px; border-radius: 8px; border: 1.5px solid transparent; cursor: pointer; text-decoration: none; white-space: nowrap; transition: background .12s, transform .1s; }
.mc-btn:active { transform: scale(.97); }
.mc-btn-edit   { background:#fef3c7; border-color:#fde68a; color:#92400e; }
.mc-btn-death  { background:#f3f4f6; border-color:#d1d5db; color:#374151; flex: 0 0 auto; padding: 8px 12px; }
.mc-btn-delete { background:#fee2e2; border-color:#fecaca; color:#991b1b; flex: 0 0 auto; padding: 8px 12px; }
.mc-btn-del-meninggal { background:#fee2e2; border-color:#fecaca; color:#991b1b; }
.mc-btn-upload { background:#e0f2fe; border-color:#bae6fd; color:#0284c7; flex: 0 0 auto; padding: 8px 12px; }

/* ===== MODAL MOBILE FIX — BOTTOM SHEET ===== */
@media (max-width: 767.98px) {

    /* Paksa modal wrapper jadi flexbox align-bottom */
    .modal.show {
        display: flex !important;
        align-items: flex-end !important;
        padding: 0 !important;
    }
    .modal.fade {
        padding: 0 !important;
    }

    .modal-dialog,
    .modal-dialog-scrollable,
    .modal-dialog-centered {
        margin: 0 !important;
        max-width: 100vw !important;
        width: 100vw !important;
        min-height: unset !important;
        height: auto !important;
        transform: none !important;
    }

    /* Konten: bottom sheet dengan max 88vh */
    .modal-dialog .modal-content,
    .modal-dialog-scrollable .modal-content,
    .modal-dialog-centered .modal-content {
        width: 100vw !important;
        border-radius: 18px 18px 0 0 !important;
        max-height: 88vh !important;
        height: auto !important;
        min-height: unset !important;
        display: flex !important;
        flex-direction: column !important;
        overflow: hidden !important;
        box-shadow: 0 -4px 24px rgba(0,0,0,.15) !important;
    }

    /* Handle bar dekoratif di atas */
    .modal-header::before {
        content: '';
        display: block;
        width: 36px;
        height: 4px;
        background: #d1d5db;
        border-radius: 99px;
        position: absolute;
        top: 8px;
        left: 50%;
        transform: translateX(-50%);
    }
    .modal-header {
        position: relative;
        padding-top: 22px !important;
        flex-shrink: 0 !important;
    }

    /* Body: scrollable */
    .modal-content .modal-body {
        flex: 1 1 auto !important;
        overflow-y: scroll !important;
        -webkit-overflow-scrolling: touch !important;
        overscroll-behavior-y: contain !important;
        padding-bottom: 16px !important;
    }

    /* Footer: pinned di bawah */
    .modal-content .modal-footer {
        flex-shrink: 0 !important;
        position: relative !important;
        background: #fff !important;
        border-top: 1.5px solid #f1f3f5 !important;
        padding-bottom: max(14px, env(safe-area-inset-bottom)) !important;
    }

    /* ===== FORM 2 KOLOM DI DALAM MODAL MOBILE ===== */
    /* Override col-md-6 agar tetap 2 kolom di mobile */
    .modal-body .row.g-3 > .col-md-6 {
        width: 50% !important;
        flex: 0 0 50% !important;
        max-width: 50% !important;
    }
    /* Field yang lebih baik full width di mobile */
    .modal-body .row.g-3 > .col-md-6.col-full-mobile {
        width: 100% !important;
        flex: 0 0 100% !important;
        max-width: 100% !important;
    }
    /* Perkecil font & padding form di dalam modal mobile */
    .modal-body .form-label {
        font-size: .73rem !important;
        margin-bottom: 3px !important;
    }
    .modal-body .form-control,
    .modal-body .form-select {
        font-size: .8rem !important;
        padding: 7px 9px !important;
    }
    .modal-body .input-group .input-group-text {
        padding: 7px 9px !important;
        font-size: .8rem !important;
    }
    .modal-body .row.g-3 {
        --bs-gutter-x: 0.5rem !important;
        --bs-gutter-y: 0.5rem !important;
    }
}
</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']);

$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; ?>
                <button class="btn btn-sm btn-light mt-1 text-success fw-bold" style="font-size: .75rem; padding: 4px 8px; border-radius: 6px;" data-bs-toggle="modal" data-bs-target="#modalUploadKK">
                    <i class="bi bi-file-earmark-arrow-up"></i> <?php echo !empty($kk->scan_kk) ? 'Update/Lihat KK' : 'Upload KK'; ?>
                </button>
            </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>No. HP</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 style="color:#6b7280;">
                        <?php if(!empty($a->no_hp)): ?>
                        <a href="tel:<?php echo $a->no_hp; ?>" style="color:#20c997; text-decoration:none; font-size:.82rem;">
                            <i class="bi bi-telephone me-1"></i><?php echo $a->no_hp; ?>
                        </a>
                        <?php else: ?><span style="color:#d1d5db;">—</span><?php endif; ?>
                    </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): ?>
                            <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->pendidikan??''); ?>','<?php echo addslashes($a->pekerjaan??''); ?>','<?php echo $hub; ?>','<?php echo $dom; ?>','<?php echo addslashes($a->keterangan_domisili??''); ?>','<?php echo addslashes($a->no_hp??''); ?>')">  
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn-act btn-act-death btn"
                                onclick="bukaModalMenuinggal(<?php echo $a->id; ?>, '<?php echo addslashes($a->nama_lengkap??''); ?>')">
                                <i class="bi bi-heartbreak"></i>
                            </button>
                            <button class="btn-act btn-act-upload btn"
                                onclick="bukaModalUploadKTP(<?php echo $a->id; ?>, '<?php echo addslashes($a->nama_lengkap??''); ?>', '<?php echo !empty($a->foto_ktp) ? base_url('assets/uploads/ktp/'.$a->foto_ktp) : ''; ?>')">
                                <i class="bi bi-person-vcard"></i>
                            </button>
                            <?php if(!$isKepala): ?>
                          <!-- SESUDAH -->
<button class="btn-act btn-act-delete btn"
    onclick="konfirmasiHapus('<?php echo base_url('kartu-keluarga/hapus_anggota/'.$a->id); ?>','<?php echo addslashes($a->nama_lengkap??''); ?>')">
    <i class="bi bi-trash"></i>
</button>
                            <?php endif; ?>
                            <?php else: ?>
                           <!-- SESUDAH -->
<button class="btn-act btn-act-hapus-meninggal btn"
    onclick="konfirmasiHapus('<?php echo base_url('kartu-keluarga/hapus_warga_meninggal/'.$a->id); ?>','<?php echo addslashes($a->nama_lengkap??''); ?>')">
    <i class="bi bi-trash me-1"></i>Hapus dari KK
</button>
                            <?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);
            $stripeColor  = $isMenuinggal ? '#9ca3af' : $bc;
        ?>
        <div class="member-card <?php echo $isMenuinggal ? 'card-meninggal' : ''; ?>">
            <div class="member-card-inner">
                <div class="member-card-stripe" style="background:<?php echo $stripeColor; ?>;"></div>
                <div class="member-card-body">
                    <div class="mc-row-top">
                        <div style="min-width:0;">
                            <div class="mc-nama <?php echo $isMenuinggal ? 'meninggal' : ''; ?>">
                                <?php echo ($a->jenis_kelamin??'')==='L'
                                    ? '<span style="color:#3b82f6;font-size:.72rem;font-weight:700;margin-right:4px;">♂</span>'
                                    : '<span style="color:#e879a0;font-size:.72rem;font-weight:700;margin-right:4px;">♀</span>'; ?>
                                <?php echo htmlspecialchars($a->nama_lengkap ?? '-'); ?>
                            </div>
                            <?php if($_can_see_nokk && !empty($a->nik)): ?>
                            <div class="mc-nik"><?php echo $a->nik; ?></div>
                            <?php endif; ?>
                        </div>
                        <div class="d-flex flex-column gap-1 align-items-end flex-shrink-0 ms-2">
                            <span class="status-badge <?php echo $h['cls']; ?>"><?php echo $h['label']; ?></span>
                            <?php if($isMenuinggal): ?>
                            <span class="status-badge sb-meninggal" style="font-size:.68rem;"><i class="bi bi-heartbreak me-1"></i>Meninggal</span>
                            <?php else: ?>
                            <span class="status-badge <?php echo $d['cls']; ?>"><?php echo $d['label']; ?></span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if($isMenuinggal && !empty($a->tanggal_meninggal)): ?>
                    <div class="mc-meninggal-info">
                        <i class="bi bi-heartbreak"></i>
                        <span>Meninggal <?php echo date('d M Y', strtotime($a->tanggal_meninggal)); ?></span>
                        <?php if(!empty($a->keterangan_meninggal)): ?>
                        <span style="color:#9ca3af;">— <?php echo htmlspecialchars($a->keterangan_meninggal); ?></span>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <div class="mc-info-row">
                        <?php if(!empty($a->tempat_lahir) || !empty($a->tanggal_lahir)): ?>
                        <span class="mc-info-item">
                            <i class="bi bi-geo-alt"></i>
                            <?php
                                $ttl = [];
                                if(!empty($a->tempat_lahir)) $ttl[] = $a->tempat_lahir;
                                if(!empty($a->tanggal_lahir)) $ttl[] = date('d/m/Y', strtotime($a->tanggal_lahir));
                                echo implode(', ', $ttl);
                            ?>
                        </span>
                        <?php endif; ?>
                        <?php if(!empty($a->pekerjaan)): ?>
                        <span class="mc-info-item"><i class="bi bi-briefcase"></i><?php echo htmlspecialchars($a->pekerjaan); ?></span>
                        <?php endif; ?>
                        <?php if(!empty($a->agama)): ?>
                        <span class="mc-info-item"><i class="bi bi-star"></i><?php echo $a->agama; ?></span>
                        <?php endif; ?>
                        <?php if(!empty($a->no_hp)): ?>
                        <a href="tel:<?php echo $a->no_hp; ?>" class="mc-hp">
                            <i class="bi bi-telephone-fill"></i><?php echo $a->no_hp; ?>
                        </a>
                        <?php endif; ?>
                    </div>

                    <?php if(!empty($a->keterangan_domisili)): ?>
                    <div style="font-size:.73rem; color:#6b7280; margin-bottom:4px;">
                        <i class="bi bi-house me-1"></i><?php echo htmlspecialchars($a->keterangan_domisili); ?>
                    </div>
                    <?php endif; ?>

                    <?php if($_is_admin_rt): ?>
                    <div class="mc-actions">
                        <?php if(!$isMenuinggal): ?>
                        <button class="mc-btn mc-btn-edit"
                            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->pendidikan??''); ?>','<?php echo addslashes($a->pekerjaan??''); ?>','<?php echo $hub; ?>','<?php echo $dom; ?>','<?php echo addslashes($a->keterangan_domisili??''); ?>','<?php echo addslashes($a->no_hp??''); ?>')">
                            <i class="bi bi-pencil"></i> Edit
                        </button>
                        <button class="mc-btn mc-btn-death"
                            onclick="bukaModalMenuinggal(<?php echo $a->id; ?>, '<?php echo addslashes($a->nama_lengkap??''); ?>')">
                            <i class="bi bi-heartbreak"></i>
                        </button>
                        <button class="mc-btn mc-btn-upload"
                            onclick="bukaModalUploadKTP(<?php echo $a->id; ?>, '<?php echo addslashes($a->nama_lengkap??''); ?>', '<?php echo !empty($a->foto_ktp) ? base_url('assets/uploads/ktp/'.$a->foto_ktp) : ''; ?>')">
                            <i class="bi bi-person-vcard"></i>
                        </button>
                        <?php if(!$isKepala): ?>
                       <button class="mc-btn mc-btn-delete"
    onclick="konfirmasiHapus('<?php echo base_url('kartu-keluarga/hapus_anggota/'.$a->id); ?>','<?php echo addslashes($a->nama_lengkap??''); ?>')">
    <i class="bi bi-trash"></i>
</button>
                        <?php endif; ?>
                        <?php else: ?>
                       <button class="mc-btn mc-btn-del-meninggal"
    onclick="konfirmasiHapus('<?php echo base_url('kartu-keluarga/hapus_warga_meninggal/'.$a->id); ?>','<?php echo addslashes($a->nama_lengkap??''); ?>')">
    <i class="bi bi-trash me-1"></i> Hapus dari KK
</button>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                </div>
            </div>
        </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">Pendidikan</label>
                            <select name="pendidikan" class="form-select">
                                <option value="">-- Pilih Pendidikan --</option>
                                <?php foreach($list_pendidikan as $pnd): ?>
                                <option value="<?php echo htmlspecialchars($pnd->nama); ?>"><?php echo htmlspecialchars($pnd->nama); ?></option>
                                <?php endforeach; ?>
                            </select></div>
                        <div class="col-md-6"><label class="form-label">Pekerjaan</label>
                            <select name="pekerjaan" class="form-select">
                                <option value="">-- Pilih Pekerjaan --</option>
                                <?php foreach($list_pekerjaan as $pkj): ?>
                                <option value="<?php echo htmlspecialchars($pkj->nama); ?>"><?php echo htmlspecialchars($pkj->nama); ?></option>
                                <?php endforeach; ?>
                            </select></div>
                        <div class="col-md-6"><label class="form-label">No. HP / WhatsApp</label>
                            <div class="input-group">
                                <span class="input-group-text" style="background:#f0fdf4; border:1.5px solid #e5e7eb; border-right:none; border-radius:8px 0 0 8px; color:#20c997;"><i class="bi bi-telephone"></i></span>
                                <input type="text" name="no_hp" class="form-control" placeholder="08xxxxxxxxxx" style="border-left:none; border-radius:0 8px 8px 0;">
                            </div></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">Pendidikan</label>
                            <select name="pendidikan" id="e_pendidikan" class="form-select">
                                <option value="">-- Pilih Pendidikan --</option>
                                <?php foreach($list_pendidikan as $pnd): ?>
                                <option value="<?php echo htmlspecialchars($pnd->nama); ?>"><?php echo htmlspecialchars($pnd->nama); ?></option>
                                <?php endforeach; ?>
                            </select></div>
                        <div class="col-md-6"><label class="form-label">Pekerjaan</label>
                            <select name="pekerjaan" id="e_pekerjaan" class="form-select">
                                <option value="">-- Pilih Pekerjaan --</option>
                                <?php foreach($list_pekerjaan as $pkj): ?>
                                <option value="<?php echo htmlspecialchars($pkj->nama); ?>"><?php echo htmlspecialchars($pkj->nama); ?></option>
                                <?php endforeach; ?>
                            </select></div>
                        <div class="col-md-6"><label class="form-label">No. HP / WhatsApp</label>
                            <div class="input-group">
                                <span class="input-group-text" style="background:#fffbeb; border:1.5px solid #e5e7eb; border-right:none; border-radius:8px 0 0 8px; color:#f59e0b;"><i class="bi bi-telephone"></i></span>
                                <input type="text" name="no_hp" id="e_no_hp" class="form-control" placeholder="08xxxxxxxxxx" style="border-left:none; border-radius:0 8px 8px 0;">
                            </div></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>

<!-- ===== MODAL UPLOAD KK ===== -->
<div class="modal fade" id="modalUploadKK" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background:#f0fdf4; border-bottom:1.5px solid #bbf7d0;">
                <h6 class="modal-title fw-bold" style="color:#166534;"><i class="bi bi-file-earmark-arrow-up me-2"></i>Upload Kartu Keluarga</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="<?php echo base_url('kartu-keluarga/upload_kk/'.$kk->id); ?>" method="post" enctype="multipart/form-data">
                <div class="modal-body text-center">
                    <?php if(!empty($kk->scan_kk)): ?>
                    <div class="mb-3">
                        <p class="mb-2 text-success fw-bold"><i class="bi bi-check-circle-fill me-1"></i>KK Sudah Diupload</p>
                        <?php 
                        $ext = strtolower(pathinfo($kk->scan_kk, PATHINFO_EXTENSION));
                        if(in_array($ext, ['jpg','jpeg','png'])): ?>
                            <a href="<?php echo base_url('assets/uploads/kk/'.$kk->scan_kk); ?>" target="_blank" class="d-inline-block mb-2">
                                <img src="<?php echo base_url('assets/uploads/kk/'.$kk->scan_kk); ?>" alt="Scan KK" class="img-fluid rounded border shadow-sm" style="max-height: 200px; object-fit: cover;">
                            </a><br>
                        <?php endif; ?>
                        <div class="d-flex justify-content-center gap-2">
                            <a href="<?php echo base_url('assets/uploads/kk/'.$kk->scan_kk); ?>" target="_blank" class="btn btn-sm btn-outline-success"><i class="bi bi-eye me-1"></i>Lihat File</a>
                            <a href="<?php echo base_url('assets/uploads/kk/'.$kk->scan_kk); ?>" download class="btn btn-sm btn-success"><i class="bi bi-download me-1"></i>Download</a>
                            <a href="<?php echo base_url('kartu-keluarga/hapus_dokumen_kk/'.$kk->id); ?>" 
                               data-confirm="Yakin ingin menghapus dokumen scan Kartu Keluarga ini?" 
                               data-title="Hapus Dokumen" data-type="danger" class="btn btn-sm btn-danger">
                                <i class="bi bi-trash me-1"></i>Hapus
                            </a>
                        </div>
                    </div>
                    <?php endif; ?>
                    <div class="mb-3 text-start">
                        <label class="form-label">Pilih File KK (JPG/PNG/PDF, Max 5MB)</label>
                        <input type="file" name="scan_kk" class="form-control" accept=".jpg,.jpeg,.png,.pdf" required>
                    </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:#22c55e; color:#fff; border:none; border-radius:8px; padding:7px 20px;">
                        <i class="bi bi-cloud-upload me-1"></i>Upload
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ===== MODAL UPLOAD KTP ===== -->
<div class="modal fade" id="modalUploadKTP" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background:#eff6ff; border-bottom:1.5px solid #bfdbfe;">
                <h6 class="modal-title fw-bold" style="color:#1e3a8a;"><i class="bi bi-person-vcard me-2"></i>Upload KTP - <span id="ktpNamaWarga"></span></h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formUploadKTP" action="" method="post" enctype="multipart/form-data">
                <div class="modal-body text-center">
                    <div id="ktpSaatIniContainer" class="mb-3 d-none">
                        <p class="mb-2 text-primary fw-bold"><i class="bi bi-check-circle-fill me-1"></i>KTP Sudah Diupload</p>
                        <a id="linkPreviewKTP" href="#" target="_blank" class="d-none mb-2 d-inline-block">
                            <img id="imgPreviewKTP" src="" alt="KTP" class="img-fluid rounded border shadow-sm" style="max-height: 200px; object-fit: cover;">
                        </a><br>
                        <div class="d-flex justify-content-center gap-2">
                            <a id="btnLihatKTP" href="#" target="_blank" class="btn btn-sm btn-outline-primary"><i class="bi bi-eye me-1"></i>Lihat File</a>
                            <a id="btnDownloadKTP" href="#" download class="btn btn-sm btn-primary"><i class="bi bi-download me-1"></i>Download</a>
                            <a id="btnHapusKTP" href="#" 
                               data-confirm="Yakin ingin menghapus foto KTP ini?" 
                               data-title="Hapus KTP" data-type="danger" class="btn btn-sm btn-danger">
                                <i class="bi bi-trash me-1"></i>Hapus
                            </a>
                        </div>
                    </div>
                    <div class="mb-3 text-start">
                        <label class="form-label">Pilih File KTP (JPG/PNG/PDF, Max 5MB)</label>
                        <input type="file" name="foto_ktp" class="form-control" accept=".jpg,.jpeg,.png,.pdf" required>
                    </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:#3b82f6; color:#fff; border:none; border-radius:8px; padding:7px 20px;">
                        <i class="bi bi-cloud-upload me-1"></i>Upload
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
// ── Modal instances ──
var _bsModalHapus = null;

function konfirmasiHapus(url, nama) {
  var elNama   = document.getElementById('hapusAnggotaNama');
  var elAvatar = document.getElementById('hapusAnggotaAvatar');
  var elBtn    = document.getElementById('btnKonfirmasiHapus');
  if(elNama)   elNama.textContent   = nama || '-';
  if(elAvatar) elAvatar.textContent = nama ? nama.charAt(0).toUpperCase() : '?';
  if(elBtn)    elBtn.href           = url;

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

function bukaModalUploadKTP(wargaId, nama, fileUrl) {
    document.getElementById('ktpNamaWarga').textContent = nama;
    document.getElementById('formUploadKTP').action = "<?php echo base_url('kartu-keluarga/upload_ktp/'); ?>" + wargaId;
    
    var container = document.getElementById('ktpSaatIniContainer');
    var btnLihat = document.getElementById('btnLihatKTP');
    var btnDownload = document.getElementById('btnDownloadKTP');
    var btnHapus = document.getElementById('btnHapusKTP');
    var linkPreview = document.getElementById('linkPreviewKTP');
    var imgPreview = document.getElementById('imgPreviewKTP');
    
    if (fileUrl) {
        container.classList.remove('d-none');
        btnLihat.href = fileUrl;
        btnDownload.href = fileUrl;
        btnHapus.href = "<?php echo base_url('kartu-keluarga/hapus_dokumen_ktp/'); ?>" + wargaId;
        
        var ext = fileUrl.split('.').pop().toLowerCase();
        if (['jpg', 'jpeg', 'png'].includes(ext)) {
            linkPreview.href = fileUrl;
            imgPreview.src = fileUrl;
            linkPreview.classList.remove('d-none');
        } else {
            linkPreview.classList.add('d-none');
        }
    } else {
        container.classList.add('d-none');
        linkPreview.classList.add('d-none');
    }
    
    var modal = new bootstrap.Modal(document.getElementById('modalUploadKTP'));
    modal.show();
}

function editAnggota(id, nik, nama, jk, tempat, tgl, agama, kawin, pendidikan, pekerjaan, hub, dom, ket, no_hp) {
  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_ket').value       = ket;
  document.getElementById('e_no_hp').value     = no_hp || '';
  setVal('e_jk',          jk);
  setVal('e_agama',       agama);
  setVal('e_kawin',       kawin);
  setVal('e_pendidikan',  pendidikan);
  setVal('e_pekerjaan',   pekerjaan);
  setVal('e_hub',         hub);
  setVal('e_dom',         dom);
  new bootstrap.Modal(document.getElementById('modalEditAnggota')).show();
}

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) {
  var el = document.getElementById(id);
  if(!el) return;
  for(var i = 0; i < el.options.length; i++) {
    if(el.options[i].value == val) { el.selectedIndex = i; break; }
  }
}
</script>

<?php endif; ?>