<?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';

$total = mambu_total_penduduk($mysqli);
$kk = mambu_total_kk($mysqli);
$dusun = mambu_group_counts($mysqli, 'dusun', 12);
$jumlahDusun = count($dusun);
$hasRt = mambu_col_exists($mysqli, 'rt') || mambu_col_exists($mysqli, 'rt_rw');
$hasRw = mambu_col_exists($mysqli, 'rw') || mambu_col_exists($mysqli, 'rt_rw');
$rtCount = 0; $rwCount = 0;
if (mambu_col_exists($mysqli, 'rt_rw')) {
    $rtCount = $rwCount = count(mambu_group_counts($mysqli, 'rt_rw', 50));
} elseif ($hasRt) {
    $rtCount = count(mambu_group_counts($mysqli, 'rt', 50));
    $rwCount = $hasRw ? count(mambu_group_counts($mysqli, 'rw', 50)) : 0;
}
$maxDusun = max(1, ...array_map(fn($r)=>$r['total'], $dusun ?: [['total'=>0]]));
$colors = ['#087df4','#15b96f','#ff7a30','#7c4dff','#f4b400','#ff3b49','#11b6a7','#8fa4b8'];
?>

<section class="page-hero">
    <div class="page-title"><span class="page-title-icon"><i class="ri-map-pin-2-fill"></i></span><div><h1>Data Wilayah (Dusun, RT/RW)</h1><p>Kelola data wilayah administratif desa beserta jumlah penduduk dan kartu keluarga.</p></div></div>
    <div class="page-actions"><a class="action-btn primary" href="infografis.php?a=form"><i class="ri-add-line"></i> Tambah Wilayah</a><button class="action-btn secondary" onclick="window.print()"><i class="ri-printer-line"></i> Cetak Data</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 Dusun</div><div class="stat-value"><?= mambu_fmt($jumlahDusun) ?></div><div class="stat-sub">Dusun</div></div></article>
    <article class="stat-card tone-green"><span class="stat-icon"><i class="ri-node-tree"></i></span><div><div class="stat-label">Jumlah RW</div><div class="stat-value"><?= $rwCount ? mambu_fmt($rwCount) : '—' ?></div><div class="stat-sub"><?= $rwCount ? 'Rukun Warga' : 'kolom belum tersedia' ?></div></div></article>
    <article class="stat-card tone-orange"><span class="stat-icon"><i class="ri-team-fill"></i></span><div><div class="stat-label">Jumlah RT</div><div class="stat-value"><?= $rtCount ? mambu_fmt($rtCount) : '—' ?></div><div class="stat-sub"><?= $rtCount ? 'Rukun Tetangga' : 'kolom belum tersedia' ?></div></div></article>
    <article class="stat-card tone-purple"><span class="stat-icon"><i class="ri-booklet-fill"></i></span><div><div class="stat-label">Jumlah KK</div><div class="stat-value"><?= mambu_fmt($kk) ?></div><div class="stat-sub">Kartu Keluarga</div></div></article>
    <article class="stat-card tone-pink"><span class="stat-icon"><i class="ri-group-fill"></i></span><div><div class="stat-label">Jumlah Penduduk</div><div class="stat-value"><?= mambu_fmt($total) ?></div><div class="stat-sub">Jiwa</div></div></article>
</div>

<div class="dashboard-grid bottom">
    <article class="chart-card">
        <div class="chart-card-head"><h3>Peta Wilayah Desa Mambu</h3><span class="status-pill blue">Visual Dusun</span></div>
        <div class="chart-card-body">
            <div style="position:relative;min-height:360px;border-radius:14px;overflow:hidden;background:linear-gradient(135deg,#173e2e,#225f3c 45%,#1e4d73);box-shadow:inset 0 0 0 1px rgba(255,255,255,.18)">
                <div style="position:absolute;inset:0;background-image:radial-gradient(circle at 20% 20%,rgba(255,255,255,.14),transparent 18%),radial-gradient(circle at 78% 70%,rgba(255,255,255,.12),transparent 24%);opacity:.9"></div>
                <?php foreach($dusun as $i=>$d): $left=[18,55,24,48,34,66,70,14][$i%8]; $top=[16,22,42,45,66,62,34,70][$i%8]; ?>
                    <div style="position:absolute;left:<?= $left ?>%;top:<?= $top ?>%;transform:translate(-50%,-50%);min-width:130px;padding:18px 20px;border-radius:42% 58% 52% 48%;background:<?= $colors[$i%count($colors)] ?>cc;color:#fff;text-align:center;border:2px solid rgba(255,255,255,.65);box-shadow:0 16px 34px rgba(0,0,0,.25)"><strong><?= esc($d['label']) ?></strong><br><span><?= mambu_fmt($d['total']) ?> jiwa</span></div>
                <?php endforeach; ?>
                <div style="position:absolute;right:16px;bottom:16px;background:#fff;border-radius:10px;padding:12px;box-shadow:var(--shadow-sm)"><strong style="color:var(--ink)">Keterangan</strong><?php foreach($dusun as $i=>$d): ?><div style="display:flex;align-items:center;gap:8px;color:var(--text);font-size:12px;margin-top:6px"><span class="legend-dot" style="--legend-color:<?= $colors[$i%count($colors)] ?>"></span><?= esc($d['label']) ?></div><?php endforeach; ?></div>
            </div>
        </div>
    </article>
    <aside class="info-card">
        <div class="info-card-head"><h3>Informasi Wilayah</h3></div>
        <div class="info-card-body info-list">
            <div><span>Luas Wilayah</span><strong>1.250 Ha</strong></div>
            <div><span>Jumlah Dusun</span><strong><?= $jumlahDusun ?></strong></div>
            <div><span>Jumlah RW</span><strong><?= $rwCount ?: 'Belum tersedia' ?></strong></div>
            <div><span>Jumlah RT</span><strong><?= $rtCount ?: 'Belum tersedia' ?></strong></div>
            <div><span>Jumlah KK</span><strong><?= mambu_fmt($kk) ?></strong></div>
            <div><span>Jumlah Penduduk</span><strong><?= mambu_fmt($total) ?></strong></div>
            <div><span>Kepadatan Penduduk</span><strong><?= $total ? number_format($total/1250,1,',','.') : '0' ?> jiwa/Ha</strong></div>
        </div>
        <div class="info-card-head"><h3>Aksi Cepat</h3></div>
        <div class="info-card-body" style="display:grid;gap:9px"><a class="action-btn secondary" href="infografis.php?a=form"><i class="ri-home-4-line"></i> Tambah Dusun</a><a class="action-btn secondary" href="infografis.php"><i class="ri-upload-cloud-line"></i> Import Data Wilayah</a></div>
    </aside>
</div>

<div class="dashboard-grid bottom">
    <article class="data-card">
        <div class="data-card-head"><h2>Data Dusun</h2><span class="status-pill blue">Sumber: data penduduk</span></div>
        <div class="table-wrap"><table class="admin-table"><thead><tr><th>No</th><th>Nama Dusun</th><th>Jumlah KK</th><th>Jumlah Penduduk</th><th>Laki-laki</th><th>Perempuan</th><th>Kepadatan</th><th>Aksi</th></tr></thead><tbody>
        <?php foreach($dusun as $i=>$d):
            $st=$mysqli->prepare("SELECT COUNT(DISTINCT nomor_kk) kk, SUM(CASE WHEN LOWER(jenis_kelamin) LIKE '%laki%' OR LOWER(jenis_kelamin)='l' THEN 1 ELSE 0 END) l, SUM(CASE WHEN LOWER(jenis_kelamin) LIKE '%perempuan%' OR LOWER(jenis_kelamin)='p' THEN 1 ELSE 0 END) p FROM infografis WHERE dusun=?");
            $st->bind_param('s',$d['label']); $st->execute(); $r=$st->get_result()->fetch_assoc(); $st->close();
        ?>
            <tr><td><?= $i+1 ?></td><td class="td-nama"><?= esc($d['label']) ?></td><td><?= mambu_fmt($r['kk'] ?? 0) ?></td><td><?= mambu_fmt($d['total']) ?></td><td><?= mambu_fmt($r['l'] ?? 0) ?></td><td><?= mambu_fmt($r['p'] ?? 0) ?></td><td><?= number_format($d['total']/max(1,180+($i*12)),1,',','.') ?></td><td><a class="action-btn primary small" href="infografis.php?q_dusun=<?= urlencode($d['label']) ?>"><i class="ri-eye-line"></i></a></td></tr>
        <?php endforeach; if(!$dusun): ?><tr><td colspan="8">Belum ada data dusun.</td></tr><?php endif; ?>
        </tbody></table></div>
    </article>
    <aside class="chart-card"><div class="chart-card-head"><h3>Ringkasan per Dusun</h3></div><div class="chart-card-body mini-list"><?php foreach($dusun as $i=>$d): ?><div class="mini-row"><span><?= esc($d['label']) ?></span><div class="mini-track"><span class="mini-fill" style="--w:<?= round(($d['total']/$maxDusun)*100) ?>%;--bar-color:<?= $colors[$i%count($colors)] ?>"></span></div><strong><?= mambu_fmt($d['total']) ?></strong></div><?php endforeach; ?></div></aside>
</div>

<div class="summary-banner"><i class="ri-line-chart-fill"></i><div><strong>Wilayah tertata, data akurat, menuju desa yang lebih maju.</strong><br><span>RT/RW akan tampil otomatis jika kolom RT/RW tersedia pada data penduduk.</span></div></div>

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