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

$act = $_GET['a'] ?? 'list';

$fields = [
  'nama_lengkap','nik','nomor_kk','status_dalam_keluarga','jenis_kelamin',
  'tempat_lahir','tanggal_lahir','dusun','desa','kecamatan','kabupaten','provinsi',
  'akta_kelahiran','golongan_darah','agama','status_perkawinan',
  'pendidikan_terakhir','pendidikan_saat_ini','pekerjaan','kewarganegaraan','suku_etnis',
  'status_kepemilikan_rumah','jenis_bangunan_rumah','akses_listrik','akses_sanitasi',
  'penyakit_kronis','kondisi_disabilitas',
  'kepemilikan_bpjs','jenis_bpjs',
  'jenis_bantuan','akses_internet','kepemilikan_hp','kepemilikan_laptop',
  'jenis_kendaraan','jumlah_kendaraan',
  'kepemilikan_lahan','luas_lahan_m2','status_lahan','jenis_lahan','jenis_komoditas',
  'jenis_ternak','jumlah_ternak',
  'status_pendidikan','nama_sekolah','kelas_semester','jurusan',
  'prestasi_akademik','prestasi_non_akademik','beasiswa',
  'kepemilikan_ktp','dokumen_tanah',
  'sumber_air_minum','penghasilan_perbulan','kondisi_rumah','kepemilikan_buku_nikah',
  'jenis_status_penduduk','status_gizi_bayi_balita','jenis_rumah'
];

$fieldTypes = [];
foreach ($fields as $f) $fieldTypes[$f] = 's';
$fieldTypes['jumlah_kendaraan'] = 'i';
$fieldTypes['luas_lahan_m2'] = 'd';
$fieldTypes['penghasilan_perbulan'] = 'd';

$labels = [
  'nama_lengkap'=>'Nama Lengkap','nik'=>'NIK','nomor_kk'=>'No. KK',
  'status_dalam_keluarga'=>'Status dalam Keluarga','jenis_kelamin'=>'Jenis Kelamin',
  'tempat_lahir'=>'Tempat Lahir','tanggal_lahir'=>'Tanggal Lahir',
  'dusun'=>'Dusun','desa'=>'Desa','kecamatan'=>'Kecamatan','kabupaten'=>'Kabupaten','provinsi'=>'Provinsi',
  'akta_kelahiran'=>'Akta Kelahiran','golongan_darah'=>'Golongan Darah','agama'=>'Agama',
  'status_perkawinan'=>'Status Perkawinan','pendidikan_terakhir'=>'Pendidikan Terakhir',
  'pendidikan_saat_ini'=>'Pendidikan Saat Ini','pekerjaan'=>'Pekerjaan',
  'kewarganegaraan'=>'Kewarganegaraan','suku_etnis'=>'Suku/Etnis',
  'status_kepemilikan_rumah'=>'Status Kepemilikan Rumah','jenis_bangunan_rumah'=>'Jenis Bangunan Rumah',
  'jenis_rumah'=>'Jenis Rumah','akses_listrik'=>'Akses Listrik','akses_sanitasi'=>'Akses Sanitasi',
  'sumber_air_minum'=>'Sumber Air Minum','kondisi_rumah'=>'Kondisi Rumah',
  'penghasilan_perbulan'=>'Penghasilan Perbulan','penyakit_kronis'=>'Penyakit Kronis',
  'kondisi_disabilitas'=>'Kondisi Disabilitas','kepemilikan_bpjs'=>'Kepemilikan BPJS',
  'jenis_bpjs'=>'Jenis BPJS','jenis_bantuan'=>'Jenis Bantuan',
  'status_gizi_bayi_balita'=>'Status Gizi Bayi & Balita Dalam Keluarga',
  'akses_internet'=>'Akses Internet','kepemilikan_hp'=>'Kepemilikan HP',
  'kepemilikan_laptop'=>'Kepemilikan Laptop','jenis_kendaraan'=>'Jenis Kendaraan',
  'jumlah_kendaraan'=>'Jumlah Kendaraan','kepemilikan_lahan'=>'Kepemilikan Lahan',
  'luas_lahan_m2'=>'Luas Lahan (m2)','status_lahan'=>'Status Lahan',
  'jenis_lahan'=>'Jenis Lahan','jenis_komoditas'=>'Jenis Komoditas',
  'jenis_ternak'=>'Jenis Ternak','jumlah_ternak'=>'Jumlah Ternak',
  'status_pendidikan'=>'Status Pendidikan','nama_sekolah'=>'Nama Sekolah',
  'kelas_semester'=>'Kelas/Semester','jurusan'=>'Jurusan',
  'prestasi_akademik'=>'Prestasi Akademik','prestasi_non_akademik'=>'Prestasi Non Akademik',
  'beasiswa'=>'Beasiswa','kepemilikan_ktp'=>'Kepemilikan KTP',
  'dokumen_tanah'=>'Dokumen Tanah','kepemilikan_buku_nikah'=>'Kepemilikan Buku Nikah',
  'jenis_status_penduduk'=>'Jenis Status Penduduk',
];

function v($row, $key){ return esc($row[$key] ?? ''); }

function normalize_col($s){
  $s = trim(mb_strtolower((string)$s, 'UTF-8'));
  $s = str_replace(['.',',','/','&','(',')','-'], ' ', $s);
  $s = preg_replace('/\s+/', ' ', $s);
  $s = str_replace(' ', '_', $s);
  $s = preg_replace('/_+/', '_', $s);
  return $s;
}

$aliases = [
  'nama_lengkap'=>'nama_lengkap','nama'=>'nama_lengkap','nik'=>'nik',
  'no_kk'=>'nomor_kk','no._kk'=>'nomor_kk','nomor_kk'=>'nomor_kk',
  'status_dalam_keluarga'=>'status_dalam_keluarga','jenis_kelamin'=>'jenis_kelamin',
  'tempat_lahir'=>'tempat_lahir','tanggal_lahir'=>'tanggal_lahir',
  'dusun'=>'dusun','desa'=>'desa','kecamatan'=>'kecamatan','kabupaten'=>'kabupaten','provinsi'=>'provinsi',
  'akta_kelahiran'=>'akta_kelahiran','golongan_darah'=>'golongan_darah','agama'=>'agama',
  'status_perkawinan'=>'status_perkawinan','pendidikan_terakhir'=>'pendidikan_terakhir',
  'pendidikan_saat_ini'=>'pendidikan_saat_ini','pekerjaan'=>'pekerjaan',
  'kewarganegaraan'=>'kewarganegaraan','suku_etnis'=>'suku_etnis',
  'status_kepemilikan_rumah'=>'status_kepemilikan_rumah','jenis_bangunan_rumah'=>'jenis_bangunan_rumah',
  'akses_listrik'=>'akses_listrik','akses_sanitasi'=>'akses_sanitasi',
  'penyakit_kronis'=>'penyakit_kronis','kondisi_disabilitas'=>'kondisi_disabilitas',
  'kepemilikan_bpjs'=>'kepemilikan_bpjs','jenis_bpjs'=>'jenis_bpjs','jenis_bantuan'=>'jenis_bantuan',
  'akses_internet'=>'akses_internet','kepemilikan_hp'=>'kepemilikan_hp','kepemilikan_laptop'=>'kepemilikan_laptop',
  'jenis_kendaraan'=>'jenis_kendaraan','jumlah_kendaraan'=>'jumlah_kendaraan',
  'kepemilikan_lahan'=>'kepemilikan_lahan',
  'luas_lahan_(meter_persegi)'=>'luas_lahan_m2','luas_lahan_meter_persegi'=>'luas_lahan_m2',
  'luas_lahan'=>'luas_lahan_m2','luas_lahan_m2'=>'luas_lahan_m2',
  'status_lahan'=>'status_lahan','jenis_lahan'=>'jenis_lahan','jenis_komoditas'=>'jenis_komoditas',
  'jenis_ternak'=>'jenis_ternak','jumlah_ternak'=>'jumlah_ternak',
  'status_pendidikan'=>'status_pendidikan','nama_sekolah'=>'nama_sekolah',
  'kelas_semester'=>'kelas_semester','jurusan'=>'jurusan',
  'prestasi_akademik'=>'prestasi_akademik','prestasi_non_akademik'=>'prestasi_non_akademik',
  'beasiswa'=>'beasiswa','kepemilikan_ktp'=>'kepemilikan_ktp','dokumen_tanah'=>'dokumen_tanah',
  'sumber_air_minum'=>'sumber_air_minum','penghasilan_perbulan'=>'penghasilan_perbulan',
  'kondisi_rumah'=>'kondisi_rumah','kepemilikan_buku_nikah'=>'kepemilikan_buku_nikah',
  'jenis_status_penduduk'=>'jenis_status_penduduk',
  'status_gizi_bayi_&_balita_dalam_keluarga'=>'status_gizi_bayi_balita',
  'status_gizi_bayi_balita_dalam_keluarga'=>'status_gizi_bayi_balita',
  'status_gizi_bayi_balita'=>'status_gizi_bayi_balita','jenis_rumah'=>'jenis_rumah',
];

function post_val($key, $type){
  $v = trim($_POST[$key] ?? '');
  if($v === '') return null;
  if($type === 'i') return (int)$v;
  if($type === 'd') return (float)$v;
  return $v;
}

/* ========== EXPORT ========== */
if ($act === 'export') {
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=data_penduduk_infografis.csv');
  $out = fopen('php://output', 'w');
  $exportFields = mambu_existing_cols($mysqli, $fields);
  $exportCols = array_merge(['id'], $exportFields);
  if (mambu_col_exists($mysqli, 'created_at')) $exportCols[] = 'created_at';
  fputcsv($out, $exportCols);
  $selectCols = '`'.implode('`,`', $exportCols).'`';
  $res = $mysqli->query("SELECT {$selectCols} FROM infografis ORDER BY id DESC");
  if($res){ while($r = $res->fetch_assoc()){ $row = []; foreach($exportCols as $f){ $row[] = $r[$f] ?? ''; } fputcsv($out, $row); } }
  fclose($out); exit;
}

/* ========== TEMPLATE ========== */
if ($act === 'template') {
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=template_data_penduduk_infografis.csv');
  $out = fopen('php://output', 'w');
  fputcsv($out, $fields);
  fclose($out); exit;
}

/* ========== IMPORT ========== */
if ($act === 'import' && $_SERVER['REQUEST_METHOD'] === 'POST') {
  $msg = '';
  if(!isset($_FILES['csv']) || $_FILES['csv']['error'] !== 0){ $msg = "File CSV tidak valid."; header("Location: infografis.php?msg=".urlencode($msg)); exit; }
  $tmp = $_FILES['csv']['tmp_name'];
  $fh = fopen($tmp, 'r');
  if(!$fh){ $msg = "Gagal membaca file CSV."; header("Location: infografis.php?msg=".urlencode($msg)); exit; }
  $header = fgetcsv($fh);
  if(!$header){ fclose($fh); $msg = "CSV kosong / tidak terbaca."; header("Location: infografis.php?msg=".urlencode($msg)); exit; }
  $normalized = array_map('normalize_col', $header);
  $mappedHeader = []; $matchCount = 0;
  foreach($normalized as $col){ $col = $aliases[$col] ?? $col; $mappedHeader[] = $col; if(in_array($col, $fields, true)) $matchCount++; }
  $hasHeader = ($matchCount >= 3);
  if(!$hasHeader){ rewind($fh); $mappedHeader = $fields; }
  $dbFields = mambu_existing_cols($mysqli, $fields);
  if (!in_array('nama_lengkap', $dbFields, true) || !in_array('nik', $dbFields, true)) { fclose($fh); header("Location: infografis.php?msg=".urlencode("Gagal import: kolom nama_lengkap dan nik wajib tersedia.")); exit; }
  $cols = '`'.implode('`,`', $dbFields).'`';
  $placeholders = implode(',', array_fill(0, count($dbFields), '?'));
  $stmt = $mysqli->prepare("INSERT INTO infografis ($cols) VALUES ($placeholders)");
  if (!$stmt) { fclose($fh); header("Location: infografis.php?msg=".urlencode("Gagal import: struktur tabel infografis tidak sesuai.")); exit; }
  $types = ''; foreach($dbFields as $f) $types .= ($GLOBALS['fieldTypes'][$f] ?? 's');
  $inserted = 0; $skipped = 0;
  while(($data = fgetcsv($fh)) !== false){
    if(!is_array($data) || count($data) === 0){ $skipped++; continue; }
    $rowAssoc = []; foreach($fields as $f){ $rowAssoc[$f] = null; }
    foreach($mappedHeader as $i => $col){ if(in_array($col, $fields, true)){ $val = trim($data[$i] ?? ''); $rowAssoc[$col] = ($val === '') ? null : $val; } }
    if(empty($rowAssoc['nama_lengkap']) || empty($rowAssoc['nik'])){ $skipped++; continue; }
    if($rowAssoc['jumlah_kendaraan'] !== null) $rowAssoc['jumlah_kendaraan'] = (int)$rowAssoc['jumlah_kendaraan'];
    if($rowAssoc['luas_lahan_m2'] !== null) $rowAssoc['luas_lahan_m2'] = (float)$rowAssoc['luas_lahan_m2'];
    if($rowAssoc['penghasilan_perbulan'] !== null) $rowAssoc['penghasilan_perbulan'] = (float)$rowAssoc['penghasilan_perbulan'];
    $params = []; foreach($dbFields as $f){ $params[] = $rowAssoc[$f] ?? null; }
    $stmt->bind_param($types, ...$params);
    if($stmt->execute()){ $inserted++; } else { $skipped++; }
  }
  $stmt->close(); fclose($fh);
  header("Location: infografis.php?msg=".urlencode("Import selesai. Masuk: $inserted baris. Dilewati: $skipped baris (kosong/duplikat/error).")); exit;
}

/* ========== SAVE ========== */
if ($act === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
  $id = (int)($_POST['id'] ?? 0);
  $data = []; foreach ($fields as $f) { $data[$f] = post_val($f, $fieldTypes[$f] ?? 's'); }
  if(($data['nama_lengkap'] ?? '') === null || ($data['nik'] ?? '') === null){ header("Location: infografis.php?msg=".urlencode("Nama Lengkap dan NIK wajib diisi.")); exit; }
  $dbFields = mambu_existing_cols($mysqli, $fields);
  if (!in_array('nama_lengkap', $dbFields, true) || !in_array('nik', $dbFields, true)) { header("Location: infografis.php?msg=".urlencode("Gagal simpan: kolom nama_lengkap dan nik wajib tersedia.")); exit; }
  if ($id > 0) {
    $setParts = []; foreach ($dbFields as $f) $setParts[] = "`$f` = ?";
    if (!$setParts) { header("Location: infografis.php?msg=".urlencode("Gagal update: struktur tabel infografis tidak sesuai.")); exit; }
    $stmt = $mysqli->prepare("UPDATE infografis SET ".implode(',', $setParts)." WHERE id = ?");
    if (!$stmt) { header("Location: infografis.php?msg=".urlencode("Gagal update: ".$mysqli->error)); exit; }
    $types = ''; $params = [];
    foreach($dbFields as $f){ $types .= ($fieldTypes[$f] ?? 's'); $params[] = $data[$f] ?? null; }
    $types .= 'i'; $params[] = $id;
    $stmt->bind_param($types, ...$params); $ok = $stmt->execute(); $err = $stmt->error; $stmt->close();
    if(!$ok){ header("Location: infografis.php?msg=".urlencode("Gagal update: ".$err)); exit; }
  } else {
    $cols = '`'.implode('`,`', $dbFields).'`';
    $placeholders = implode(',', array_fill(0, count($dbFields), '?'));
    $stmt = $mysqli->prepare("INSERT INTO infografis ($cols) VALUES ($placeholders)");
    if (!$stmt) { header("Location: infografis.php?msg=".urlencode("Gagal simpan: ".$mysqli->error)); exit; }
    $types = ''; $params = [];
    foreach($dbFields as $f){ $types .= ($fieldTypes[$f] ?? 's'); $params[] = $data[$f] ?? null; }
    $stmt->bind_param($types, ...$params); $ok = $stmt->execute(); $err = $stmt->error; $stmt->close();
    if(!$ok){ header("Location: infografis.php?msg=".urlencode("Gagal simpan: ".$err." (cek kemungkinan NIK duplikat)")); exit; }
  }
  header('Location: infografis.php'); exit;
}

/* ========== DELETE 1 ========== */
if ($act === 'del') {
  $id = (int)($_GET['id'] ?? 0);
  if ($id > 0) { $stmt = $mysqli->prepare("DELETE FROM infografis WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->execute(); $stmt->close(); }
  header('Location: infografis.php'); exit;
}

/* ========== DELETE ALL ========== */
if ($act === 'del_all' && $_SERVER['REQUEST_METHOD'] === 'POST') {
  $confirm = trim($_POST['confirm'] ?? '');
  if (mb_strtolower($confirm, 'UTF-8') !== 'hapus semua') { header("Location: infografis.php?msg=".urlencode("Gagal: ketik 'hapus semua' untuk konfirmasi.")); exit; }
  $mysqli->query("DELETE FROM infografis");
  $mysqli->query("ALTER TABLE infografis AUTO_INCREMENT = 1");
  header("Location: infografis.php?msg=".urlencode("Semua data penduduk berhasil dihapus.")); exit;
}

/* ========== EDIT ========== */
$row = null;
if ($act === 'edit') {
  $id = (int)($_GET['id'] ?? 0);
  $stmt = $mysqli->prepare("SELECT * FROM infografis WHERE id = ?");
  $stmt->bind_param("i", $id); $stmt->execute();
  $res = $stmt->get_result(); $row = $res ? $res->fetch_assoc() : null; $stmt->close();
}

include __DIR__ . '/../includes/header.php';
$msg = $_GET['msg'] ?? '';
?>

<div class="inf-wrap">

    <!-- ===== HEADER ===== -->
    <div class="inf-header">
        <div class="inf-header-left">
            <p class="inf-eyebrow"><i class="ri-bar-chart-box-fill"></i> Kependudukan</p>
            <h2><i class="ri-group-fill"></i> Data Penduduk</h2>
            <p class="inf-header-sub">Kelola data penduduk desa secara lengkap, akurat dan terintegrasi.</p>
        </div>
        <div class="inf-actions">
            <a class="btn btn-default" href="infografis.php?a=template">
                <i class="ri-file-download-line"></i> Template CSV
            </a>
            <a class="btn btn-default" href="infografis.php?a=export">
                <i class="ri-download-2-line"></i> Export CSV
            </a>
            <a class="btn btn-primary" href="infografis.php?a=form">
                <i class="ri-user-add-fill"></i> Tambah Penduduk
            </a>
            <form method="post" action="infografis.php?a=del_all" style="margin:0"
                  onsubmit="return confirmHapusSemua();">
                <input type="hidden" name="confirm" id="confirmHapusSemuaInput" value="">
                <button type="submit" class="btn btn-danger">
                    <i class="ri-delete-bin-6-fill"></i> Hapus Semua
                </button>
            </form>
        </div>
    </div>

    <!-- ===== ALERT ===== -->
    <?php if($msg): ?>
    <div class="inf-alert">
        <i class="ri-information-fill"></i>
        <?= esc($msg) ?>
    </div>
    <?php endif; ?>


    <?php if ($act === 'list'): ?>

    <?php
    $q_nama   = trim($_GET['q_nama'] ?? '');
    $q_nik    = trim($_GET['q_nik'] ?? '');
    $q_kk     = trim($_GET['q_kk'] ?? '');
    $q_jk     = trim($_GET['q_jk'] ?? '');
    $q_umur   = trim($_GET['q_umur'] ?? '');
    $q_dusun  = trim($_GET['q_dusun'] ?? '');
    $q_status_kawin   = trim($_GET['q_status_kawin'] ?? '');
    $q_pend_tr        = trim($_GET['q_pend_tr'] ?? '');
    $q_job    = trim($_GET['q_job'] ?? '');
    $q_bantu  = trim($_GET['q_bantu'] ?? '');
    $q_lahan  = trim($_GET['q_lahan'] ?? '');
    $q_komod  = trim($_GET['q_komod'] ?? '');
    $q_ternak = trim($_GET['q_ternak'] ?? '');
    $q_bpjs   = trim($_GET['q_bpjs'] ?? '');
    $q_status_keluarga = trim($_GET['q_status_keluarga'] ?? '');

    $where=[]; $params=[]; $types="";
    if($q_nama!=="" && mambu_col_exists($mysqli, 'nama_lengkap')){  $where[]="nama_lengkap LIKE ?"; $params[]="%$q_nama%"; $types.="s"; }
    if($q_nik!=="" && mambu_col_exists($mysqli, 'nik')){   $where[]="nik LIKE ?";           $params[]="%$q_nik%";  $types.="s"; }
    if($q_kk!=="" && mambu_col_exists($mysqli, 'nomor_kk')){    $where[]="nomor_kk LIKE ?";      $params[]="%$q_kk%";   $types.="s"; }
    if($q_jk!=="" && mambu_col_exists($mysqli, 'jenis_kelamin')){    $where[]="jenis_kelamin = ?";    $params[]=$q_jk;       $types.="s"; }
    if($q_dusun!=="" && mambu_col_exists($mysqli, 'dusun')){          $where[]="dusun = ?";                   $params[]=$q_dusun;         $types.="s"; }
    if($q_status_kawin!=="" && mambu_col_exists($mysqli, 'status_perkawinan')){   $where[]="status_perkawinan = ?";       $params[]=$q_status_kawin;  $types.="s"; }
    if($q_pend_tr!=="" && mambu_col_exists($mysqli, 'pendidikan_terakhir')){        $where[]="pendidikan_terakhir = ?";     $params[]=$q_pend_tr;       $types.="s"; }
    if($q_job!=="" && mambu_col_exists($mysqli, 'pekerjaan')){            $where[]="pekerjaan = ?";               $params[]=$q_job;           $types.="s"; }
    if($q_bantu!=="" && mambu_col_exists($mysqli, 'jenis_bantuan')){          $where[]="jenis_bantuan LIKE ?";        $params[]="%$q_bantu%";     $types.="s"; }
    if($q_lahan!=="" && mambu_col_exists($mysqli, 'jenis_lahan')){          $where[]="jenis_lahan = ?";             $params[]=$q_lahan;         $types.="s"; }
    if($q_komod!=="" && mambu_col_exists($mysqli, 'jenis_komoditas')){          $where[]="jenis_komoditas = ?";         $params[]=$q_komod;         $types.="s"; }
    if($q_ternak!=="" && mambu_col_exists($mysqli, 'jenis_ternak')){         $where[]="jenis_ternak = ?";            $params[]=$q_ternak;        $types.="s"; }
    if($q_status_keluarga!=="" && mambu_col_exists($mysqli, 'status_dalam_keluarga')){$where[]="status_dalam_keluarga = ?";   $params[]=$q_status_keluarga;$types.="s";}
    if($q_bpjs!=="" && mambu_col_exists($mysqli, 'kepemilikan_bpjs')){           $where[]="kepemilikan_bpjs = ?";        $params[]=$q_bpjs;          $types.="s"; }
    if($q_umur!=="" && mambu_col_exists($mysqli, 'tanggal_lahir')){
        switch($q_umur){
            case '0-5':   $where[]="TIMESTAMPDIFF(YEAR,tanggal_lahir,CURDATE()) BETWEEN 0 AND 5"; break;
            case '6-12':  $where[]="TIMESTAMPDIFF(YEAR,tanggal_lahir,CURDATE()) BETWEEN 6 AND 12"; break;
            case '13-18': $where[]="TIMESTAMPDIFF(YEAR,tanggal_lahir,CURDATE()) BETWEEN 13 AND 18"; break;
            case '19-30': $where[]="TIMESTAMPDIFF(YEAR,tanggal_lahir,CURDATE()) BETWEEN 19 AND 30"; break;
            case '31-45': $where[]="TIMESTAMPDIFF(YEAR,tanggal_lahir,CURDATE()) BETWEEN 31 AND 45"; break;
            case '46-60': $where[]="TIMESTAMPDIFF(YEAR,tanggal_lahir,CURDATE()) BETWEEN 46 AND 60"; break;
            case '60+':   $where[]="TIMESTAMPDIFF(YEAR,tanggal_lahir,CURDATE()) >= 60"; break;
        }
    }

    $whereSql = count($where) ? " WHERE ".implode(" AND ", $where) : "";
    $page = max(1, (int)($_GET['page'] ?? 1));
    $perPage = (int)($_GET['per_page'] ?? 10);
    if (!in_array($perPage, [10,25,50,100], true)) $perPage = 10;
    $countSql = "SELECT COUNT(*) c FROM infografis".$whereSql;
    $countStmt = $mysqli->prepare($countSql);
    $totalFiltered = 0;
    if($countStmt){
        if($params){ $countStmt->bind_param($types,...$params); }
        $countStmt->execute();
        $totalFiltered = (int)($countStmt->get_result()->fetch_assoc()['c'] ?? 0);
        $countStmt->close();
    }
    $totalPages = max(1, (int)ceil($totalFiltered / $perPage));
    $page = min($page, $totalPages);
    $offset = ($page - 1) * $perPage;

    $sqlList = "SELECT * FROM infografis".$whereSql." ORDER BY id DESC LIMIT ? OFFSET ?";
    $stmt = $mysqli->prepare($sqlList);
    $res = false;
    if($stmt){
        $listTypes = $types.'ii';
        $listParams = $params;
        $listParams[] = $perPage;
        $listParams[] = $offset;
        $stmt->bind_param($listTypes, ...$listParams);
        $stmt->execute();
        $res = $stmt->get_result();
    }

    function inf_option_rows(mysqli $mysqli, string $column): array {
        if (!mambu_col_exists($mysqli, $column)) return [];
        $q = $mysqli->query("SELECT DISTINCT `{$column}` val FROM infografis WHERE `{$column}`<>'' ORDER BY `{$column}` ASC");
        $rows = [];
        if($q) while($r = $q->fetch_assoc()) $rows[] = $r['val'];
        return $rows;
    }
    $optDusun  = inf_option_rows($mysqli, 'dusun');
    $optJK     = inf_option_rows($mysqli, 'jenis_kelamin');
    $optKawin  = inf_option_rows($mysqli, 'status_perkawinan');
    $optPendTr = inf_option_rows($mysqli, 'pendidikan_terakhir');
    $optJob    = inf_option_rows($mysqli, 'pekerjaan');
    $optBantu  = inf_option_rows($mysqli, 'jenis_bantuan');
    $optLahan  = inf_option_rows($mysqli, 'jenis_lahan');
    $optKomod  = inf_option_rows($mysqli, 'jenis_komoditas');
    $optTernak = inf_option_rows($mysqli, 'jenis_ternak');
    $optBPJS   = inf_option_rows($mysqli, 'kepemilikan_bpjs');
    $optStatusKeluarga = inf_option_rows($mysqli, 'status_dalam_keluarga');
    ?>

    <!-- ===== FILTER CARD ===== -->
    <div class="filter-card">
        <div class="filter-card-body">
            <form method="get">
                <input type="hidden" name="a" value="list">
                <div class="filter-grid">
                    <div class="filter-field"><label>Cari Data</label><input class="inf-input" name="q_nama"  placeholder="Cari NIK, nama, nomor KK..." value="<?= esc($q_nama) ?>"></div>
                    <div class="filter-field"><label>NIK</label><input class="inf-input" name="q_nik"   placeholder="Cari NIK..." value="<?= esc($q_nik) ?>"></div>
                    <div class="filter-field"><label>No. KK</label><input class="inf-input" name="q_kk"    placeholder="Cari No. KK..." value="<?= esc($q_kk) ?>"></div>

                    <div class="filter-field"><label>Jenis Kelamin</label><select class="inf-input" name="q_jk">
                        <option value="">Semua</option>
                        <?php foreach($optJK as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_jk==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Kelompok Umur</label><select class="inf-input" name="q_umur" <?= mambu_col_exists($mysqli, 'tanggal_lahir') ? '' : 'disabled' ?>>
                        <option value="">Semua</option>
                        <?php foreach(['0-5','6-12','13-18','19-30','31-45','46-60','60+'] as $u): ?>
                        <option value="<?= $u ?>" <?= $q_umur==$u?'selected':'' ?>><?= $u ?> tahun</option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Dusun</label><select class="inf-input" name="q_dusun">
                        <option value="">Semua Dusun</option>
                        <?php foreach($optDusun as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_dusun==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Status Perkawinan</label><select class="inf-input" name="q_status_kawin">
                        <option value="">Semua</option>
                        <?php foreach($optKawin as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_status_kawin==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Pendidikan</label><select class="inf-input" name="q_pend_tr">
                        <option value="">Semua</option>
                        <?php foreach($optPendTr as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_pend_tr==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Pekerjaan</label><select class="inf-input" name="q_job">
                        <option value="">Semua</option>
                        <?php foreach($optJob as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_job==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Agama / Bantuan</label><select class="inf-input" name="q_bantu">
                        <option value="">Semua Bantuan</option>
                        <?php foreach($optBantu as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_bantu==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Lahan</label><select class="inf-input" name="q_lahan">
                        <option value="">Semua</option>
                        <?php foreach($optLahan as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_lahan==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Komoditas</label><select class="inf-input" name="q_komod">
                        <option value="">Semua</option>
                        <?php foreach($optKomod as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_komod==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div class="filter-field"><label>Status Keluarga</label><select class="inf-input" name="q_status_keluarga">
                        <option value="">Semua</option>
                        <?php foreach($optStatusKeluarga as $optVal): ?>
                        <option value="<?= esc($optVal) ?>" <?= $q_status_keluarga==$optVal?'selected':'' ?>><?= esc($optVal) ?></option>
                        <?php endforeach; ?>
                    </select></div>

                    <div style="grid-column:1/-1;display:flex;gap:8px;padding-top:4px;justify-content:flex-end">
                        <button class="action-btn primary" type="submit"><i class="ri-filter-3-fill"></i> Filter</button>
                        <a class="action-btn secondary" href="infografis.php"><i class="ri-refresh-line"></i> Reset</a>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- ===== IMPORT CARD ===== -->
    <div class="filter-card">
        <div class="filter-card-body">
            <form method="post" enctype="multipart/form-data" action="infografis.php?a=import">
                <div class="import-bar">
                    <strong><i class="ri-upload-cloud-2-fill" style="color:var(--primary)"></i> Import Data Excel/CSV</strong>
                    <input type="file" name="csv" accept=".csv" required>
                    <button class="action-btn success" type="submit"><i class="ri-upload-2-line"></i> Import CSV</button>
                </div>
            </form>
        </div>
    </div>

    <!-- ===== DATA TABLE ===== -->
    <div class="data-card">
        <div class="data-card-head">
            <h2>Total Data: <strong><?= number_format($totalFiltered,0,',','.') ?></strong> penduduk</h2>
            <form method="get" style="display:flex;align-items:center;gap:8px">
                <input type="hidden" name="a" value="list">
                <?php foreach($_GET as $k=>$v): if(in_array($k,['a','per_page','page'],true)) continue; ?>
                    <input type="hidden" name="<?= esc($k) ?>" value="<?= esc($v) ?>">
                <?php endforeach; ?>
                <span style="color:var(--muted);font-size:12px">Tampilkan</span>
                <select class="inf-input" name="per_page" onchange="this.form.submit()" style="width:76px">
                    <?php foreach([10,25,50,100] as $pp): ?><option value="<?= $pp ?>" <?= $perPage===$pp?'selected':'' ?>><?= $pp ?></option><?php endforeach; ?>
                </select>
            </form>
        </div>
        <div class="data-card-body" style="padding:0">
            <div class="inf-table-wrap">
                <table class="inf-table">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>NIK</th>
                            <th>Nama</th>
                            <th>JK</th>
                            <th>Tempat/Tgl Lahir</th>
                            <th>Umur</th>
                            <th>No. KK</th>
                            <th>Dusun</th>
                            <th>Pendidikan</th>
                            <th>Pekerjaan</th>
                            <th>Status Kawin</th>
                            <th>Agama</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php $loopIndex = 0; if($res): while($r = $res->fetch_assoc()): ?>
                        <?php
                        $jkRaw = strtolower(trim($r['jenis_kelamin'] ?? ''));
                        $jkClass = mambu_contains($jkRaw,'laki') ? 'jk-laki' : (mambu_contains($jkRaw,'perempuan') ? 'jk-perempuan' : 'jk-other');
                        $jkIcon  = mambu_contains($jkRaw,'laki') ? 'ri-men-fill' : (mambu_contains($jkRaw,'perempuan') ? 'ri-women-fill' : 'ri-user-fill');
                        $birthText = mambu_birthplace($r);
                        $ageText = mambu_age_from_date($r['tanggal_lahir'] ?? null);
                        ?>
                        <tr>
                            <td><?= $offset + $loopIndex + 1 ?></td>
                            <td class="td-nik"><?= esc($r['nik'] ?? '-') ?></td>
                            <td class="td-nama"><?= esc($r['nama_lengkap'] ?? '-') ?></td>
                            <td><span class="jk-badge <?= $jkClass ?>"><i class="<?= $jkIcon ?>"></i><?= esc($r['jenis_kelamin'] ?? '-') ?></span></td>
                            <td><?= esc($birthText) ?></td>
                            <td><?= esc($ageText) ?></td>
                            <td class="td-nik"><?= esc($r['nomor_kk'] ?? '-') ?></td>
                            <td><?= esc($r['dusun'] ?? '-') ?></td>
                            <td><?= esc($r['pendidikan_terakhir'] ?? '-') ?></td>
                            <td><?= esc($r['pekerjaan'] ?? '-') ?></td>
                            <td><span class="status-pill <?= stripos($r['status_perkawinan'] ?? '', 'kawin') !== false ? 'green' : 'gray' ?>"><?= esc($r['status_perkawinan'] ?? '-') ?></span></td>
                            <td><?= esc($r['agama'] ?? '-') ?></td>
                            <td style="white-space:nowrap">
                                <a class="action-btn primary small" title="Detail/Edit" href="infografis.php?a=edit&id=<?= (int)$r['id'] ?>"><i class="ri-eye-line"></i></a>
                                <a class="action-btn success small" title="Edit" href="infografis.php?a=edit&id=<?= (int)$r['id'] ?>"><i class="ri-pencil-line"></i></a>
                                <a class="action-btn danger small" title="Hapus" href="infografis.php?a=del&id=<?= (int)$r['id'] ?>" onclick="return confirm('Hapus data penduduk ini?')"><i class="ri-delete-bin-line"></i></a>
                            </td>
                        </tr>
                    <?php $loopIndex++; endwhile; else: ?><tr><td colspan="13">Belum ada data penduduk.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="table-footer">
                <span>Menampilkan <?= $totalFiltered ? ($offset + 1) : 0 ?> - <?= min($offset + $perPage, $totalFiltered) ?> dari <?= number_format($totalFiltered,0,',','.') ?> data</span>
                <div class="pagination">
                    <?php $baseParams = $_GET; $baseParams['a']='list'; $baseParams['per_page']=$perPage; ?>
                    <?php $baseParams['page']=max(1,$page-1); ?><a href="?<?= http_build_query($baseParams) ?>">&laquo;</a>
                    <?php for($p=max(1,$page-2); $p<=min($totalPages,$page+2); $p++): $baseParams['page']=$p; ?>
                        <a class="<?= $p===$page?'active':'' ?>" href="?<?= http_build_query($baseParams) ?>"><?= $p ?></a>
                    <?php endfor; ?>
                    <?php $baseParams['page']=min($totalPages,$page+1); ?><a href="?<?= http_build_query($baseParams) ?>">&raquo;</a>
                </div>
            </div>
        </div>
    </div>

    <?php $stmt->close(); ?>


    <?php else: /* ===== FORM ADD / EDIT ===== */ ?>

    <?php $isEdit = ($act === 'edit' && $row); ?>

    <div class="inf-card">
        <div class="inf-card-head">
            <div class="inf-card-head-icon"><i class="<?= $isEdit ? 'ri-edit-2-fill' : 'ri-user-add-fill' ?>"></i></div>
            <div>
                <h3><?= $isEdit ? 'Edit Data Penduduk' : 'Tambah Data Penduduk' ?></h3>
                <p><?= $isEdit ? 'Perbarui informasi penduduk di bawah ini' : 'Isi formulir lengkap berikut untuk menambah data penduduk baru' ?></p>
            </div>
        </div>
        <div class="inf-card-body">
            <form method="post" action="infografis.php?a=save">
                <input type="hidden" name="id" value="<?= (int)($row['id'] ?? 0) ?>">

                <!-- A. Identitas -->
                <div class="form-section-title"><i class="ri-id-card-fill"></i> A. Identitas &amp; Wilayah</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['nama_lengkap'] ?></label><input class="inf-input" name="nama_lengkap" value="<?= v($row,'nama_lengkap') ?>" required placeholder="Nama lengkap sesuai KTP"></div>
                    <div class="form-field"><label><?= $labels['nik'] ?></label><input class="inf-input" name="nik" value="<?= v($row,'nik') ?>" required placeholder="16 digit NIK"></div>
                    <div class="form-field"><label><?= $labels['nomor_kk'] ?></label><input class="inf-input" name="nomor_kk" value="<?= v($row,'nomor_kk') ?>"></div>
                    <div class="form-field"><label><?= $labels['status_dalam_keluarga'] ?></label><input class="inf-input" name="status_dalam_keluarga" value="<?= v($row,'status_dalam_keluarga') ?>"></div>
                    <div class="form-field"><label><?= $labels['jenis_kelamin'] ?></label>
                        <select class="inf-input" name="jenis_kelamin">
                            <option value="">-- Pilih --</option>
                            <?php foreach(['Laki-laki','Perempuan'] as $jk): ?>
                            <option value="<?= $jk ?>" <?= v($row,'jenis_kelamin')==$jk?'selected':'' ?>><?= $jk ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-field"><label><?= $labels['tempat_lahir'] ?></label><input class="inf-input" name="tempat_lahir" value="<?= v($row,'tempat_lahir') ?>"></div>
                    <div class="form-field"><label><?= $labels['tanggal_lahir'] ?></label><input class="inf-input" type="date" name="tanggal_lahir" value="<?= v($row,'tanggal_lahir') ?>"></div>
                    <div class="form-field"><label><?= $labels['dusun'] ?></label><input class="inf-input" name="dusun" value="<?= v($row,'dusun') ?>"></div>
                    <div class="form-field"><label><?= $labels['desa'] ?></label><input class="inf-input" name="desa" value="<?= v($row,'desa') ?>"></div>
                    <div class="form-field"><label><?= $labels['kecamatan'] ?></label><input class="inf-input" name="kecamatan" value="<?= v($row,'kecamatan') ?>"></div>
                    <div class="form-field"><label><?= $labels['kabupaten'] ?></label><input class="inf-input" name="kabupaten" value="<?= v($row,'kabupaten') ?>"></div>
                    <div class="form-field"><label><?= $labels['provinsi'] ?></label><input class="inf-input" name="provinsi" value="<?= v($row,'provinsi') ?>"></div>
                    <div class="form-field"><label><?= $labels['akta_kelahiran'] ?></label><input class="inf-input" name="akta_kelahiran" value="<?= v($row,'akta_kelahiran') ?>" placeholder="Ada / Tidak"></div>
                    <div class="form-field"><label><?= $labels['golongan_darah'] ?></label><input class="inf-input" name="golongan_darah" value="<?= v($row,'golongan_darah') ?>"></div>
                    <div class="form-field"><label><?= $labels['agama'] ?></label><input class="inf-input" name="agama" value="<?= v($row,'agama') ?>"></div>
                    <div class="form-field"><label><?= $labels['status_perkawinan'] ?></label><input class="inf-input" name="status_perkawinan" value="<?= v($row,'status_perkawinan') ?>"></div>
                    <div class="form-field"><label><?= $labels['pendidikan_terakhir'] ?></label><input class="inf-input" name="pendidikan_terakhir" value="<?= v($row,'pendidikan_terakhir') ?>"></div>
                    <div class="form-field"><label><?= $labels['pendidikan_saat_ini'] ?></label><input class="inf-input" name="pendidikan_saat_ini" value="<?= v($row,'pendidikan_saat_ini') ?>"></div>
                    <div class="form-field"><label><?= $labels['pekerjaan'] ?></label><input class="inf-input" name="pekerjaan" value="<?= v($row,'pekerjaan') ?>"></div>
                    <div class="form-field"><label><?= $labels['kewarganegaraan'] ?></label><input class="inf-input" name="kewarganegaraan" value="<?= v($row,'kewarganegaraan') ?>"></div>
                    <div class="form-field"><label><?= $labels['suku_etnis'] ?></label><input class="inf-input" name="suku_etnis" value="<?= v($row,'suku_etnis') ?>"></div>
                </div>

                <!-- B. Rumah -->
                <div class="form-section-title"><i class="ri-home-4-fill"></i> B. Rumah &amp; Lingkungan</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['status_kepemilikan_rumah'] ?></label><input class="inf-input" name="status_kepemilikan_rumah" value="<?= v($row,'status_kepemilikan_rumah') ?>"></div>
                    <div class="form-field"><label><?= $labels['jenis_bangunan_rumah'] ?></label><input class="inf-input" name="jenis_bangunan_rumah" value="<?= v($row,'jenis_bangunan_rumah') ?>"></div>
                    <div class="form-field"><label><?= $labels['jenis_rumah'] ?></label><input class="inf-input" name="jenis_rumah" value="<?= v($row,'jenis_rumah') ?>"></div>
                    <div class="form-field"><label><?= $labels['akses_listrik'] ?></label><input class="inf-input" name="akses_listrik" value="<?= v($row,'akses_listrik') ?>"></div>
                    <div class="form-field"><label><?= $labels['akses_sanitasi'] ?></label><input class="inf-input" name="akses_sanitasi" value="<?= v($row,'akses_sanitasi') ?>"></div>
                    <div class="form-field"><label><?= $labels['sumber_air_minum'] ?></label><input class="inf-input" name="sumber_air_minum" value="<?= v($row,'sumber_air_minum') ?>"></div>
                    <div class="form-field"><label><?= $labels['kondisi_rumah'] ?></label><input class="inf-input" name="kondisi_rumah" value="<?= v($row,'kondisi_rumah') ?>"></div>
                    <div class="form-field"><label><?= $labels['penghasilan_perbulan'] ?></label><input class="inf-input" type="number" step="0.01" name="penghasilan_perbulan" value="<?= v($row,'penghasilan_perbulan') ?>" placeholder="contoh: 2500000"></div>
                    <div class="form-field"><label><?= $labels['kepemilikan_buku_nikah'] ?></label><input class="inf-input" name="kepemilikan_buku_nikah" value="<?= v($row,'kepemilikan_buku_nikah') ?>"></div>
                </div>

                <!-- C. Kesehatan -->
                <div class="form-section-title"><i class="ri-heart-pulse-fill"></i> C. Kesehatan &amp; Program</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['penyakit_kronis'] ?></label><input class="inf-input" name="penyakit_kronis" value="<?= v($row,'penyakit_kronis') ?>"></div>
                    <div class="form-field"><label><?= $labels['kondisi_disabilitas'] ?></label><input class="inf-input" name="kondisi_disabilitas" value="<?= v($row,'kondisi_disabilitas') ?>"></div>
                    <div class="form-field"><label><?= $labels['kepemilikan_bpjs'] ?></label><input class="inf-input" name="kepemilikan_bpjs" value="<?= v($row,'kepemilikan_bpjs') ?>" placeholder="Ya / Tidak"></div>
                    <div class="form-field"><label><?= $labels['jenis_bpjs'] ?></label><input class="inf-input" name="jenis_bpjs" value="<?= v($row,'jenis_bpjs') ?>"></div>
                    <div class="form-field"><label><?= $labels['jenis_bantuan'] ?></label><input class="inf-input" name="jenis_bantuan" value="<?= v($row,'jenis_bantuan') ?>"></div>
                    <div class="form-field"><label><?= $labels['status_gizi_bayi_balita'] ?></label><input class="inf-input" name="status_gizi_bayi_balita" value="<?= v($row,'status_gizi_bayi_balita') ?>"></div>
                </div>

                <!-- D. Teknologi -->
                <div class="form-section-title"><i class="ri-smartphone-fill"></i> D. Akses Teknologi</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['akses_internet'] ?></label><input class="inf-input" name="akses_internet" value="<?= v($row,'akses_internet') ?>"></div>
                    <div class="form-field"><label><?= $labels['kepemilikan_hp'] ?></label><input class="inf-input" name="kepemilikan_hp" value="<?= v($row,'kepemilikan_hp') ?>"></div>
                    <div class="form-field"><label><?= $labels['kepemilikan_laptop'] ?></label><input class="inf-input" name="kepemilikan_laptop" value="<?= v($row,'kepemilikan_laptop') ?>"></div>
                </div>

                <!-- E. Transportasi -->
                <div class="form-section-title"><i class="ri-car-fill"></i> E. Transportasi</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['jenis_kendaraan'] ?></label><input class="inf-input" name="jenis_kendaraan" value="<?= v($row,'jenis_kendaraan') ?>"></div>
                    <div class="form-field"><label><?= $labels['jumlah_kendaraan'] ?></label><input class="inf-input" type="number" name="jumlah_kendaraan" value="<?= v($row,'jumlah_kendaraan') ?>"></div>
                </div>

                <!-- F. Lahan -->
                <div class="form-section-title"><i class="ri-plant-fill"></i> F. Lahan &amp; Pertanian</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['kepemilikan_lahan'] ?></label><input class="inf-input" name="kepemilikan_lahan" value="<?= v($row,'kepemilikan_lahan') ?>"></div>
                    <div class="form-field"><label><?= $labels['luas_lahan_m2'] ?></label><input class="inf-input" type="number" step="0.01" name="luas_lahan_m2" value="<?= v($row,'luas_lahan_m2') ?>"></div>
                    <div class="form-field"><label><?= $labels['status_lahan'] ?></label><input class="inf-input" name="status_lahan" value="<?= v($row,'status_lahan') ?>"></div>
                    <div class="form-field"><label><?= $labels['jenis_lahan'] ?></label><input class="inf-input" name="jenis_lahan" value="<?= v($row,'jenis_lahan') ?>"></div>
                    <div class="form-field"><label><?= $labels['jenis_komoditas'] ?></label><input class="inf-input" name="jenis_komoditas" value="<?= v($row,'jenis_komoditas') ?>"></div>
                </div>

                <!-- G. Ternak -->
                <div class="form-section-title"><i class="ri-fish-fill"></i> G. Ternak</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['jenis_ternak'] ?></label><input class="inf-input" name="jenis_ternak" value="<?= v($row,'jenis_ternak') ?>"></div>
                    <div class="form-field"><label><?= $labels['jumlah_ternak'] ?></label><input class="inf-input" name="jumlah_ternak" value="<?= v($row,'jumlah_ternak') ?>"></div>
                </div>

                <!-- H. Pendidikan Detail -->
                <div class="form-section-title"><i class="ri-graduation-cap-fill"></i> H. Pendidikan Detail</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['status_pendidikan'] ?></label><input class="inf-input" name="status_pendidikan" value="<?= v($row,'status_pendidikan') ?>"></div>
                    <div class="form-field"><label><?= $labels['nama_sekolah'] ?></label><input class="inf-input" name="nama_sekolah" value="<?= v($row,'nama_sekolah') ?>"></div>
                    <div class="form-field"><label><?= $labels['kelas_semester'] ?></label><input class="inf-input" name="kelas_semester" value="<?= v($row,'kelas_semester') ?>"></div>
                    <div class="form-field"><label><?= $labels['jurusan'] ?></label><input class="inf-input" name="jurusan" value="<?= v($row,'jurusan') ?>"></div>
                    <div class="form-field"><label><?= $labels['prestasi_akademik'] ?></label><input class="inf-input" name="prestasi_akademik" value="<?= v($row,'prestasi_akademik') ?>"></div>
                    <div class="form-field"><label><?= $labels['prestasi_non_akademik'] ?></label><input class="inf-input" name="prestasi_non_akademik" value="<?= v($row,'prestasi_non_akademik') ?>"></div>
                    <div class="form-field"><label><?= $labels['beasiswa'] ?></label><input class="inf-input" name="beasiswa" value="<?= v($row,'beasiswa') ?>"></div>
                </div>

                <!-- I. Dokumen -->
                <div class="form-section-title"><i class="ri-file-shield-2-fill"></i> I. Dokumen &amp; Status Penduduk</div>
                <div class="form-grid">
                    <div class="form-field"><label><?= $labels['kepemilikan_ktp'] ?></label><input class="inf-input" name="kepemilikan_ktp" value="<?= v($row,'kepemilikan_ktp') ?>"></div>
                    <div class="form-field"><label><?= $labels['dokumen_tanah'] ?></label><input class="inf-input" name="dokumen_tanah" value="<?= v($row,'dokumen_tanah') ?>"></div>
                    <div class="form-field"><label><?= $labels['jenis_status_penduduk'] ?></label><input class="inf-input" name="jenis_status_penduduk" value="<?= v($row,'jenis_status_penduduk') ?>"></div>
                </div>

                <!-- ACTIONS -->
                <div class="form-actions">
                    <button class="btn btn-green" type="submit">
                        <i class="ri-save-3-fill"></i> <?= $isEdit ? 'Simpan Perubahan' : 'Simpan Data' ?>
                    </button>
                    <a class="btn btn-default" href="infografis.php" style="background:#f3faf6;color:var(--muted);border:1.5px solid var(--line)">
                        <i class="ri-arrow-left-line"></i> Batal
                    </a>
                </div>
            </form>
        </div>
    </div>

    <?php endif; ?>

</div><!-- /.inf-wrap -->


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