query($sql); $features = []; while ($r = $stmt->fetch()) { $penduduk = (int)$r['jumlah_penduduk']; $miskin = (int)$r['jumlah_miskin']; $persen = $penduduk > 0 ? round($miskin / $penduduk * 100, 2) : 0; $features[] = [ 'type' => 'Feature', 'geometry' => json_decode($r['geojson']), 'properties' => [ 'id' => (int)$r['id'], 'nama' => $r['nama'], 'jenis' => $r['jenis'], 'kode_wilayah' => $r['kode_wilayah'], 'jumlah_penduduk' => $penduduk, 'jumlah_miskin' => $miskin, 'persentase_miskin' => $persen, ], ]; } sendSuccess(['type' => 'FeatureCollection', 'features' => $features], 'Data Wilayah'); break; case 'POST': $d = getInput(); if (empty($d['nama']) || empty($d['geometry'])) sendError('Nama & geometri wajib diisi'); $pdo->prepare("INSERT INTO wilayah (nama, kode_wilayah, jenis, jumlah_penduduk, geom) VALUES (?,?,?,?, ST_GeomFromGeoJSON(?))") ->execute([ $d['nama'], nnw($d['kode_wilayah'] ?? null), $d['jenis'] ?? 'kelurahan', (int)($d['jumlah_penduduk'] ?? 0), json_encode($d['geometry']), ]); $id = (int)$pdo->lastInsertId(); logActivity($pdo, 'create', 'wilayah', $id, "Tambah wilayah {$d['nama']}"); sendSuccess(['id' => $id], 'Wilayah disimpan', 201); break; case 'PUT': $d = getInput(); $id = $_GET['id'] ?? null; if (!$id) sendError('ID wajib'); if (!empty($d['geometry'])) { $pdo->prepare("UPDATE wilayah SET nama=?, kode_wilayah=?, jenis=?, jumlah_penduduk=?, geom=ST_GeomFromGeoJSON(?) WHERE id=?") ->execute([$d['nama'], nnw($d['kode_wilayah'] ?? null), $d['jenis'] ?? 'kelurahan', (int)($d['jumlah_penduduk'] ?? 0), json_encode($d['geometry']), $id]); } else { $pdo->prepare("UPDATE wilayah SET nama=?, kode_wilayah=?, jenis=?, jumlah_penduduk=? WHERE id=?") ->execute([$d['nama'], nnw($d['kode_wilayah'] ?? null), $d['jenis'] ?? 'kelurahan', (int)($d['jumlah_penduduk'] ?? 0), $id]); } logActivity($pdo, 'update', 'wilayah', (int)$id, 'Ubah wilayah'); sendSuccess(null, 'Wilayah diperbarui'); break; case 'DELETE': $id = $_GET['id'] ?? null; if (!$id) sendError('ID wajib'); $pdo->prepare("DELETE FROM wilayah WHERE id=?")->execute([$id]); logActivity($pdo, 'delete', 'wilayah', (int)$id, 'Hapus wilayah'); sendSuccess(null, 'Wilayah dihapus'); break; default: sendError('Method not allowed', 405); }