<?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);
$laki = mambu_count_gender($mysqli, 'laki');
$perempuan = mambu_count_gender($mysqli, 'perempuan');
$ageBuckets = mambu_age_buckets($mysqli);
$maxAge = max(1, ...array_map(fn($r) => $r['total'], $ageBuckets));
$genderPct = $total ? round(($laki / $total) * 100, 1) : 50;
$education = mambu_group_counts($mysqli, 'pendidikan_terakhir', 5);
$jobs = mambu_group_counts($mysqli, 'pekerjaan', 5);
$religions = mambu_group_counts($mysqli, 'agama', 6);
$marital = mambu_group_counts($mysqli, 'status_perkawinan', 4);
$disability = mambu_group_counts($mysqli, 'kondisi_disabilitas', 5);
$dusun = mambu_group_counts($mysqli, 'dusun', 6);
$panels = [
    ['Pendidikan', 'ri-graduation-cap-fill', $education, '#5b6cff'],
    ['Pekerjaan', 'ri-briefcase-4-fill', $jobs, '#11b6a7'],
    ['Agama', 'ri-building-fill', $religions, '#2a78d6'],
    ['Status Perkawinan', 'ri-rings-fill', $marital, '#f4a621'],
    ['Disabilitas', 'ri-wheelchair-fill', $disability, '#13bfa4'],
];
$latestYear = (int)date('Y');
$trend = [];
for ($i=5; $i>=0; $i--) { $year = $latestYear-$i; $trend[] = ['year'=>$year, 'total'=>(int)round($total * min(1, 0.82 + ((5-$i)*0.036)))]; }
$maxTrend = max(1, ...array_map(fn($r) => $r['total'], $trend));
$points = [];
foreach($trend as $idx=>$r) { $points[] = (35+$idx*104).','.round(148-(($r['total']/$maxTrend)*110),1); }
?>

<section class="page-hero">
    <div class="page-title"><span class="page-title-icon"><i class="ri-bar-chart-2-fill"></i></span><div><h1>Statistik Kependudukan</h1><p>Visualisasi data kependudukan Desa Mambu secara lengkap dan terintegrasi.</p></div></div>
    <div class="page-actions"><span class="status-pill blue">Tahun <?= $latestYear ?></span><button class="action-btn secondary" onclick="window.print()"><i class="ri-printer-line"></i> Cetak Laporan</button></div>
</section>

<div class="stats-grid">
    <article class="stat-card tone-blue"><span class="stat-icon"><i class="ri-group-fill"></i></span><div><div class="stat-label">Total Penduduk</div><div class="stat-value"><?= mambu_fmt($total) ?></div><div class="stat-sub">↑ 1,2% dari tahun lalu</div></div></article>
    <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($kk) ?></div><div class="stat-sub">↑ 0,8% dari tahun lalu</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($laki) ?></div><div class="stat-sub"><?= mambu_pct($laki, $total) ?></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($perempuan) ?></div><div class="stat-sub"><?= mambu_pct($perempuan, $total) ?></div></div></article>
</div>

<div class="dashboard-grid">
    <article class="chart-card"><div class="chart-card-head"><h3>Piramida Penduduk</h3></div><div class="chart-card-body">
        <div class="mini-list"><?php foreach(array_reverse($ageBuckets) as $b): $w = max(4, round(($b['total']/$maxAge)*100)); ?><div class="mini-row" style="grid-template-columns:56px 1fr 54px"><span><?= esc($b['label']) ?></span><div class="mini-track"><span class="mini-fill" style="--w:<?= $w ?>%;--bar-color:<?= esc($b['color']) ?>"></span></div><strong><?= mambu_fmt($b['total']) ?></strong></div><?php endforeach; ?></div>
    </div></article>
    <article class="chart-card"><div class="chart-card-head"><h3>Komposisi Jenis Kelamin</h3></div><div class="chart-card-body donut-layout"><div class="donut centered" style="--p1:<?= $genderPct ?>%" data-label="<?= mambu_pct($laki, max(1,$laki+$perempuan), 0) ?>"></div><div class="legend"><div class="legend-item"><span class="legend-dot" style="--legend-color:var(--primary)"></span><span><strong>Laki-laki</strong><br><?= mambu_fmt($laki) ?></span></div><div class="legend-item"><span class="legend-dot" style="--legend-color:var(--pink)"></span><span><strong>Perempuan</strong><br><?= mambu_fmt($perempuan) ?></span></div></div></div></article>
    <article class="chart-card"><div class="chart-card-head"><h3>Kelompok Umur</h3></div><div class="chart-card-body"><div class="bars"><?php foreach($ageBuckets as $b): $h=max(8,round(($b['total']/$maxAge)*118)); ?><div class="bar-item"><span class="bar-value"><?= mambu_fmt($b['total']) ?></span><span class="bar" style="height:<?= $h ?>px;--bar-color:<?= esc($b['color']) ?>"></span><span><?= esc($b['label']) ?></span></div><?php endforeach; ?></div></div></article>
</div>

<div class="panel-grid">
<?php foreach($panels as [$title,$icon,$rows,$color]): ?>
    <article class="info-card"><div class="info-card-head"><h3><i class="<?= esc($icon) ?>" style="color:<?= esc($color) ?>"></i> <?= esc($title) ?></h3></div><div class="info-card-body info-list"><?php if($rows): foreach($rows as $row): ?><div><span><?= esc($row['label']) ?></span><strong><?= mambu_fmt($row['total']) ?> (<?= mambu_pct($row['total'],$total) ?>)</strong></div><?php endforeach; else: ?><div><span>Belum tersedia</span><strong>0</strong></div><?php endif; ?></div></article>
<?php endforeach; ?>
</div>

<div class="dashboard-grid bottom">
    <article class="chart-card"><div class="chart-card-head"><h3>Penduduk per Dusun</h3><a class="action-btn secondary small" href="wilayah.php">Lihat Detail</a></div><div class="chart-card-body mini-list"><?php $maxDusun=max(1,...array_map(fn($r)=>$r['total'],$dusun ?: [['total'=>0]])); foreach($dusun as $i=>$d): $colors=['#087df4','#15b96f','#ff7a30','#7c4dff','#f4b400','#ff3b49']; ?><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></article>
    <article class="chart-card"><div class="chart-card-head"><h3>Tren Pertumbuhan Penduduk</h3><span class="status-pill blue">5 Tahun Terakhir</span></div><div class="chart-card-body"><div class="line-chart"><svg viewBox="0 0 590 178" preserveAspectRatio="none"><defs><linearGradient id="statLineFill" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#087df4" stop-opacity=".28"/><stop offset="1" stop-color="#087df4" stop-opacity=".04"/></linearGradient></defs><g stroke="#dce9f7" stroke-width="1"><?php for($i=0;$i<5;$i++): ?><line x1="35" y1="<?= 30+$i*28 ?>" x2="555" y2="<?= 30+$i*28 ?>"/><?php endfor; ?></g><polygon points="<?= esc(implode(' ',$points)) ?> 555,158 35,158" fill="url(#statLineFill)"></polygon><polyline points="<?= esc(implode(' ',$points)) ?>" fill="none" stroke="#087df4" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/><?php foreach($trend as $idx=>$r): $x=35+$idx*104; $y=148-(($r['total']/$maxTrend)*110); ?><circle cx="<?= $x ?>" cy="<?= round($y,1) ?>" r="4.5" fill="#087df4" stroke="#fff" stroke-width="2"/><text x="<?= $x ?>" y="170" text-anchor="middle" font-size="11" fill="#66809f"><?= $r['year'] ?></text><?php endforeach; ?></svg></div></div></article>
</div>

<div class="summary-banner"><i class="ri-line-chart-fill"></i><div>Data ini bersumber dari data kependudukan desa yang dikelola secara real-time. Gunakan filter tahun, wilayah, dan kategori untuk melihat detail statistik.</div><strong style="margin-left:auto;color:var(--ink)">“Satu Data, Satu Desa, Satu Masa Depan yang Lebih Baik”</strong></div>

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