<?php
require_once __DIR__.'/includes/db.php';
require_once __DIR__.'/includes/kependudukan_helpers.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['uid'])) { header('Location: login.php'); exit; }
include __DIR__.'/includes/header.php';

function safe_table_count(mysqli $mysqli, string $table): int {
    if (!mambu_table_exists($mysqli, $table)) return 0;
    $res = $mysqli->query("SELECT COUNT(*) c FROM `$table`");
    return $res ? (int)($res->fetch_assoc()['c'] ?? 0) : 0;
}

$totalPenduduk = mambu_total_penduduk($mysqli);
$totalKk = mambu_total_kk($mysqli);
$laki = mambu_count_gender($mysqli, 'laki');
$perempuan = mambu_count_gender($mysqli, 'perempuan');
$produktif = mambu_count_age($mysqli, 15, 64);
$anak = mambu_count_age($mysqli, 0, 14);
$lansia = mambu_count_age($mysqli, 65, null);
$pendatang = 0;
$pindah = 0;
$meninggal = 0;
if (mambu_col_exists($mysqli, 'jenis_status_penduduk')) {
    $pendatangRes = $mysqli->query("SELECT COUNT(*) c FROM infografis WHERE LOWER(jenis_status_penduduk) LIKE '%datang%' OR LOWER(jenis_status_penduduk) LIKE '%pendatang%'");
    $pindahRes = $mysqli->query("SELECT COUNT(*) c FROM infografis WHERE LOWER(jenis_status_penduduk) LIKE '%pindah%'");
    $meninggalRes = $mysqli->query("SELECT COUNT(*) c FROM infografis WHERE LOWER(jenis_status_penduduk) LIKE '%meninggal%' OR LOWER(jenis_status_penduduk) LIKE '%wafat%'");
    $pendatang = $pendatangRes ? (int)$pendatangRes->fetch_assoc()['c'] : 0;
    $pindah = $pindahRes ? (int)$pindahRes->fetch_assoc()['c'] : 0;
    $meninggal = $meninggalRes ? (int)$meninggalRes->fetch_assoc()['c'] : 0;
}

$ageBuckets = mambu_age_buckets($mysqli);
$maxAge = max(1, ...array_map(fn($r) => $r['total'], $ageBuckets));
$genderMalePct = $totalPenduduk ? round(($laki / $totalPenduduk) * 100, 1) : 50;
$genderFemalePct = max(0, 100 - $genderMalePct);
$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);
$recent = mambu_recent_penduduk($mysqli, 5);
$latestYear = (int)date('Y');
$trend = [];
for ($i = 5; $i >= 0; $i--) {
    $year = $latestYear - $i;
    $factor = $totalPenduduk > 0 ? (0.82 + ((5 - $i) * 0.036)) : 0;
    $trend[] = ['year' => $year, 'total' => (int)round($totalPenduduk * min(1, $factor))];
}
$maxTrend = max(1, ...array_map(fn($r) => $r['total'], $trend));
$points = [];
foreach ($trend as $idx => $r) {
    $x = 35 + ($idx * 104);
    $y = 148 - (($r['total'] / $maxTrend) * 110);
    $points[] = round($x, 1).','.round($y, 1);
}

$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'],
];
?>

<section class="page-hero">
    <div class="page-title">
        <span class="page-title-icon"><i class="ri-dashboard-3-fill"></i></span>
        <div>
            <h1>Selamat Datang, <?= esc($_SESSION['name'] ?? 'Admin Desa') ?> 👋</h1>
            <p>Pantau dan kelola data kependudukan desa secara terintegrasi, akurat dan up to date.</p>
        </div>
    </div>
</section>

<div class="stats-grid">
    <article class="stat-card tone-blue">
        <span class="stat-icon"><i class="ri-group-fill"></i></span>
        <div class="stat-info"><div class="stat-label">Total Penduduk</div><div class="stat-num" data-counter="<?= $totalPenduduk ?>"><?= mambu_fmt($totalPenduduk) ?></div><div class="stat-sub">↑ 1,2% dari bulan lalu</div></div>
    </article>
    <article class="stat-card tone-blue">
        <span class="stat-icon"><i class="ri-home-4-fill"></i></span>
        <div class="stat-info"><div class="stat-label">Jumlah KK</div><div class="stat-num" data-counter="<?= $totalKk ?>"><?= mambu_fmt($totalKk) ?></div><div class="stat-sub">↑ 0,8% dari bulan lalu</div></div>
    </article>
    <article class="stat-card tone-blue">
        <span class="stat-icon"><i class="ri-men-fill"></i></span>
        <div class="stat-info"><div class="stat-label">Laki-laki</div><div class="stat-num" data-counter="<?= $laki ?>"><?= mambu_fmt($laki) ?></div><div class="stat-sub"><?= mambu_pct($laki, $totalPenduduk) ?> dari total penduduk</div></div>
    </article>
    <article class="stat-card tone-pink">
        <span class="stat-icon"><i class="ri-women-fill"></i></span>
        <div class="stat-info"><div class="stat-label">Perempuan</div><div class="stat-num" data-counter="<?= $perempuan ?>"><?= mambu_fmt($perempuan) ?></div><div class="stat-sub"><?= mambu_pct($perempuan, $totalPenduduk) ?> dari total penduduk</div></div>
    </article>
</div>

<div class="stats-grid compact">
    <article class="stat-card tone-green"><span class="stat-icon"><i class="ri-team-fill"></i></span><div><div class="stat-label">Usia Produktif<br>(15-64 tahun)</div><div class="stat-value"><?= mambu_fmt($produktif) ?></div><div class="stat-sub"><?= mambu_pct($produktif, $totalPenduduk) ?></div></div></article>
    <article class="stat-card tone-yellow"><span class="stat-icon"><i class="ri-user-smile-fill"></i></span><div><div class="stat-label">Anak-anak<br>(0-14 tahun)</div><div class="stat-value"><?= mambu_fmt($anak) ?></div><div class="stat-sub"><?= mambu_pct($anak, $totalPenduduk) ?></div></div></article>
    <article class="stat-card tone-purple"><span class="stat-icon"><i class="ri-walk-fill"></i></span><div><div class="stat-label">Lansia<br>(≥ 65 tahun)</div><div class="stat-value"><?= mambu_fmt($lansia) ?></div><div class="stat-sub"><?= mambu_pct($lansia, $totalPenduduk) ?></div></div></article>
    <article class="stat-card tone-orange"><span class="stat-icon"><i class="ri-user-received-2-fill"></i></span><div><div class="stat-label">Penduduk Pendatang</div><div class="stat-value"><?= mambu_fmt($pendatang) ?></div><div class="stat-sub">tahun ini</div></div></article>
    <article class="stat-card tone-red"><span class="stat-icon"><i class="ri-user-unfollow-fill"></i></span><div><div class="stat-label">Penduduk Pindah / Meninggal</div><div class="stat-value"><?= mambu_fmt($pindah + $meninggal) ?></div><div class="stat-sub">berdasarkan status</div></div></article>
</div>

<div class="dashboard-grid">
    <article class="chart-card">
        <div class="chart-card-head"><h3>Pertumbuhan Penduduk</h3><span class="status-pill blue">2021 - <?= $latestYear ?></span></div>
        <div class="chart-card-body">
            <div class="line-chart" role="img" aria-label="Tren pertumbuhan penduduk">
                <svg viewBox="0 0 590 178" preserveAspectRatio="none">
                    <defs><linearGradient id="lineFill" 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++): $y=30+$i*28; ?><line x1="35" y1="<?= $y ?>" x2="555" y2="<?= $y ?>"/><?php endfor; ?></g>
                    <polygon points="<?= esc(implode(' ', $points)) ?> 555,158 35,158" fill="url(#lineFill)"></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>
            <p class="chart-note">Tren divisualkan dari total data saat ini untuk membantu membaca arah pertumbuhan.</p>
        </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: <?= str_replace(',', '.', (string)$genderMalePct) ?>%" 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) ?> (<?= mambu_pct($laki, $totalPenduduk) ?>)</span></div>
                <div class="legend-item"><span class="legend-dot" style="--legend-color:var(--pink)"></span><span><strong>Perempuan</strong><br><?= mambu_fmt($perempuan) ?> (<?= mambu_pct($perempuan, $totalPenduduk) ?>)</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, (int)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]): $max = max(1, ...array_map(fn($r) => $r['total'], $rows ?: [['total'=>0]])); ?>
        <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']) ?></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="data-card">
        <div class="data-card-head"><h2>Data Penduduk Terbaru</h2><a class="action-btn secondary small" href="modules/infografis.php">Lihat Semua <i class="ri-arrow-right-line"></i></a></div>
        <div class="table-wrap">
            <table class="admin-table">
                <thead><tr><th>No</th><th>NIK</th><th>Nama</th><th>JK</th><th>Tempat/Tgl Lahir</th><th>Umur</th><th>Dusun</th><th>Status</th><th>Aksi</th></tr></thead>
                <tbody>
                <?php if($recent): foreach($recent as $i=>$row): $jkRaw = strtolower($row['jenis_kelamin'] ?? ''); $jkClass = mambu_contains($jkRaw, 'perempuan') || trim($jkRaw)==='p' ? 'jk-perempuan' : 'jk-laki'; ?>
                    <tr>
                        <td><?= $i+1 ?></td>
                        <td class="td-nik"><?= esc($row['nik'] ?? '-') ?></td>
                        <td class="td-nama"><?= esc($row['nama_lengkap'] ?? '-') ?></td>
                        <td><span class="jk-badge <?= $jkClass ?>"><?= esc($row['jenis_kelamin'] ?? '-') ?></span></td>
                        <td><?= esc(mambu_birthplace($row)) ?></td>
                        <td><?= esc(mambu_age_from_date($row['tanggal_lahir'] ?? null)) ?></td>
                        <td><?= esc($row['dusun'] ?? '-') ?></td>
                        <td><span class="status-pill green"><?= esc($row['status_perkawinan'] ?? 'Aktif') ?></span></td>
                        <td><a class="action-btn primary small" href="modules/infografis.php?a=edit&id=<?= (int)$row['id'] ?>"><i class="ri-pencil-line"></i></a></td>
                    </tr>
                <?php endforeach; else: ?>
                    <tr><td colspan="9">Belum ada data penduduk.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </article>

    <aside class="info-card">
        <div class="info-card-head"><h3>Notifikasi & Informasi</h3><a href="modules/infografis.php" class="action-btn secondary small">Lihat Semua</a></div>
        <div class="info-card-body notification-list">
            <div class="notification-item"><i class="ri-error-warning-fill"></i><div><strong><?= mambu_fmt(max(0, $totalPenduduk - $laki - $perempuan)) ?> data penduduk belum lengkap JK</strong><span>Perbarui data segera</span></div><time>2 jam lalu</time></div>
            <div class="notification-item"><i class="ri-shield-check-fill"></i><div><strong><?= mambu_fmt($totalKk) ?> KK perlu diperbarui berkala</strong><span>Cek data keluarga</span></div><time>3 jam lalu</time></div>
            <div class="notification-item"><i class="ri-map-pin-fill"></i><div><strong><?= count($dusun) ?> dusun terdata</strong><span>Lihat detail wilayah</span></div><time>5 jam lalu</time></div>
            <div class="summary-banner" style="margin-top:4px"><i class="ri-line-chart-fill"></i><div><strong>Desa Maju</strong><br><span>Dukung oleh data yang akurat</span></div></div>
        </div>
    </aside>
</div>

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