<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/kependudukan_helpers.php';
include __DIR__.'/../includes/header.php';

$totalPenduduk = mambu_total_penduduk($mysqli);
$totalKk = mambu_total_kk($mysqli);
$dusunRows = mambu_group_counts($mysqli, 'dusun', 20);
$selectedKk = trim($_GET['kk'] ?? '');
$q = trim($_GET['q'] ?? '');
$qDusun = trim($_GET['dusun'] ?? '');
$where = ["nomor_kk IS NOT NULL", "TRIM(nomor_kk) <> ''"];
$params = [];
$types = '';
if ($q !== '') { $where[] = "(nomor_kk LIKE ? OR nama_lengkap LIKE ?)"; $params[] = "%$q%"; $params[] = "%$q%"; $types .= 'ss'; }
if ($qDusun !== '') { $where[] = "dusun = ?"; $params[] = $qDusun; $types .= 's'; }
$whereSql = ' WHERE '.implode(' AND ', $where);
$sql = "SELECT nomor_kk,
               COALESCE(NULLIF(MAX(CASE WHEN LOWER(status_dalam_keluarga) LIKE '%kepala%' THEN nama_lengkap END), ''), MIN(nama_lengkap)) kepala,
               COALESCE(NULLIF(MAX(dusun), ''), '-') dusun,
               COUNT(*) anggota,
               SUM(CASE WHEN LOWER(jenis_kelamin) LIKE '%laki%' OR LOWER(jenis_kelamin)='l' THEN 1 ELSE 0 END) laki,
               SUM(CASE WHEN LOWER(jenis_kelamin) LIKE '%perempuan%' OR LOWER(jenis_kelamin)='p' THEN 1 ELSE 0 END) perempuan,
               MAX(status_perkawinan) status_keluarga
        FROM infografis {$whereSql}
        GROUP BY nomor_kk
        ORDER BY nomor_kk ASC
        LIMIT 50";
$stmt = $mysqli->prepare($sql);
if ($params) $stmt->bind_param($types, ...$params);
$stmt->execute();
$families = $stmt->get_result();
if ($selectedKk === '' && $families && $first = $families->fetch_assoc()) {
    $selectedKk = $first['nomor_kk'];
    $families->data_seek(0);
}
$detail = null;
$members = [];
if ($selectedKk !== '') {
    $st = $mysqli->prepare("SELECT * FROM infografis WHERE nomor_kk = ? ORDER BY CASE WHEN LOWER(status_dalam_keluarga) LIKE '%kepala%' THEN 0 ELSE 1 END, tanggal_lahir ASC, nama_lengkap ASC");
    $st->bind_param('s', $selectedKk);
    $st->execute();
    $rs = $st->get_result();
    while ($r = $rs->fetch_assoc()) $members[] = $r;
    $st->close();
    if ($members) {
        $detail = [
            'nomor_kk' => $selectedKk,
            'kepala' => $members[0]['nama_lengkap'] ?? '-',
            'alamat' => trim(($members[0]['desa'] ?? 'Desa Mambu').' '.($members[0]['kecamatan'] ?? '')),
            'dusun' => $members[0]['dusun'] ?? '-',
        ];
        foreach ($members as $m) if (stripos($m['status_dalam_keluarga'] ?? '', 'kepala') !== false) { $detail['kepala'] = $m['nama_lengkap']; break; }
    }
}
?>

<section class="page-hero">
    <div class="page-title"><span class="page-title-icon"><i class="ri-booklet-fill"></i></span><div><h1>Data Kartu Keluarga (KK)</h1><p>Kelola data kartu keluarga desa secara lengkap dan terintegrasi.</p></div></div>
    <div class="page-actions"><a class="action-btn primary" href="infografis.php?a=form"><i class="ri-add-line"></i> Tambah KK</a><a class="action-btn secondary" href="infografis.php?a=export"><i class="ri-file-excel-2-line"></i> Export Excel</a><button class="action-btn secondary" onclick="window.print()"><i class="ri-printer-line"></i> Cetak</button></div>
</section>

<div class="stats-grid compact">
    <article class="stat-card tone-blue"><span class="stat-icon"><i class="ri-home-4-fill"></i></span><div><div class="stat-label">Jumlah KK</div><div class="stat-value"><?= mambu_fmt($totalKk) ?></div><div class="stat-sub">Kartu Keluarga</div></div></article>
    <article class="stat-card tone-green"><span class="stat-icon"><i class="ri-team-fill"></i></span><div><div class="stat-label">Total Anggota</div><div class="stat-value"><?= mambu_fmt($totalPenduduk) ?></div><div class="stat-sub">Jiwa</div></div></article>
    <article class="stat-card tone-purple"><span class="stat-icon"><i class="ri-map-pin-2-fill"></i></span><div><div class="stat-label">Dusun Terdata</div><div class="stat-value"><?= count($dusunRows) ?></div><div class="stat-sub">Wilayah</div></div></article>
    <article class="stat-card tone-pink"><span class="stat-icon"><i class="ri-women-fill"></i></span><div><div class="stat-label">Perempuan</div><div class="stat-value"><?= mambu_fmt(mambu_count_gender($mysqli,'perempuan')) ?></div><div class="stat-sub">Anggota KK</div></div></article>
    <article class="stat-card tone-blue"><span class="stat-icon"><i class="ri-men-fill"></i></span><div><div class="stat-label">Laki-laki</div><div class="stat-value"><?= mambu_fmt(mambu_count_gender($mysqli,'laki')) ?></div><div class="stat-sub">Anggota KK</div></div></article>
</div>

<div class="filter-card" style="margin-bottom:14px"><div class="filter-card-body"><form class="filter-grid" method="get">
    <div class="filter-field"><label>Cari Data</label><input class="input" name="q" value="<?= esc($q) ?>" placeholder="Cari nomor KK atau kepala keluarga..."></div>
    <div class="filter-field"><label>Dusun</label><select name="dusun"><option value="">Semua Dusun</option><?php foreach($dusunRows as $d): ?><option value="<?= esc($d['label']) ?>" <?= $qDusun===$d['label']?'selected':'' ?>><?= esc($d['label']) ?></option><?php endforeach; ?></select></div>
    <div class="filter-field"><button class="action-btn primary" type="submit"><i class="ri-filter-3-fill"></i> Filter</button> <a class="action-btn secondary" href="kartu_keluarga.php">Reset</a></div>
</form></div></div>

<div class="dashboard-grid bottom">
    <article class="data-card">
        <div class="data-card-head"><h2>Total Data: <?= mambu_fmt($totalKk) ?> Kartu Keluarga</h2><span class="status-pill blue">Tampilkan 50 data</span></div>
        <div class="table-wrap"><table class="admin-table"><thead><tr><th>No</th><th>No. KK</th><th>Kepala Keluarga</th><th>Dusun</th><th>Jumlah Anggota</th><th>Status Keluarga</th><th>Aksi</th></tr></thead><tbody>
        <?php $no=1; if($families && $families->num_rows): while($f=$families->fetch_assoc()): ?>
            <tr><td><?= $no++ ?></td><td class="td-nik"><?= esc($f['nomor_kk']) ?></td><td class="td-nama"><?= esc($f['kepala']) ?></td><td><?= esc($f['dusun']) ?></td><td><?= (int)$f['anggota'] ?></td><td><span class="status-pill green">Aktif</span></td><td><a class="action-btn primary small" href="?kk=<?= urlencode($f['nomor_kk']) ?>"><i class="ri-eye-line"></i></a> <a class="action-btn success small" href="infografis.php?q_kk=<?= urlencode($f['nomor_kk']) ?>"><i class="ri-pencil-line"></i></a></td></tr>
        <?php endwhile; else: ?><tr><td colspan="7">Belum ada data kartu keluarga.</td></tr><?php endif; ?>
        </tbody></table></div>
    </article>

    <aside class="data-card">
        <div class="data-card-head"><h2>Detail Kartu Keluarga</h2><i class="ri-close-line" style="color:var(--muted)"></i></div>
        <div class="data-card-body">
            <?php if($detail): ?>
            <h2 style="margin:0 0 12px;color:var(--ink)">No. KK <span class="td-nik"><?= esc($detail['nomor_kk']) ?></span></h2>
            <div class="info-list" style="margin-bottom:16px"><div><span>Kepala Keluarga</span><strong><?= esc($detail['kepala']) ?></strong></div><div><span>Alamat</span><strong><?= esc($detail['alamat']) ?></strong></div><div><span>Dusun</span><strong><?= esc($detail['dusun']) ?></strong></div><div><span>Jumlah Anggota</span><strong><?= count($members) ?> Orang</strong></div></div>
            <h3 style="color:var(--ink)"><i class="ri-group-fill" style="color:var(--primary)"></i> Anggota Keluarga</h3>
            <div class="table-wrap"><table class="admin-table" style="min-width:520px"><thead><tr><th>No</th><th>NIK</th><th>Nama</th><th>JK</th><th>Hubungan</th></tr></thead><tbody><?php foreach($members as $i=>$m): ?><tr><td><?= $i+1 ?></td><td class="td-nik"><?= esc($m['nik']) ?></td><td><?= esc($m['nama_lengkap']) ?></td><td><?= esc($m['jenis_kelamin']) ?></td><td><?= esc($m['status_dalam_keluarga']) ?></td></tr><?php endforeach; ?></tbody></table></div>
            <a class="action-btn primary" style="width:100%;margin-top:14px" href="infografis.php?q_kk=<?= urlencode($detail['nomor_kk']) ?>">Lihat Detail Lengkap <i class="ri-arrow-right-line"></i></a>
            <?php else: ?><p>Belum ada KK yang dipilih.</p><?php endif; ?>
        </div>
    </aside>
</div>

<?php include __DIR__.'/../includes/footer.php'; ?>
