81 lines
2.8 KiB
PHP
81 lines
2.8 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
include __DIR__ . '/../db_config.php';
|
|
|
|
function distanceMeters($lat1, $lng1, $lat2, $lng2) {
|
|
$earthRadius = 6371000;
|
|
$toRadians = function ($value) {
|
|
return $value * M_PI / 180;
|
|
};
|
|
|
|
$deltaLat = $toRadians($lat2 - $lat1);
|
|
$deltaLng = $toRadians($lng2 - $lng1);
|
|
$a = sin($deltaLat / 2) * sin($deltaLat / 2) + cos($toRadians($lat1)) * cos($toRadians($lat2)) * sin($deltaLng / 2) * sin($deltaLng / 2);
|
|
|
|
return 2 * $earthRadius * atan2(sqrt($a), sqrt(1 - $a));
|
|
}
|
|
|
|
function findNearestRumahIbadah($conn, $lat, $lng) {
|
|
$result = $conn->query("SELECT id, nama, latitude, longitude FROM rumah_ibadah ORDER BY created_at DESC");
|
|
if (!$result || $result->num_rows === 0) {
|
|
return null;
|
|
}
|
|
|
|
$nearest = null;
|
|
while ($row = $result->fetch_assoc()) {
|
|
$distance = distanceMeters($lat, $lng, (float)$row['latitude'], (float)$row['longitude']);
|
|
if ($nearest === null || $distance < $nearest['distance']) {
|
|
$nearest = [
|
|
'id' => (int)$row['id'],
|
|
'nama' => $row['nama'],
|
|
'distance' => $distance
|
|
];
|
|
}
|
|
}
|
|
|
|
return $nearest;
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$namaKetuaKk = trim($_POST['nama_ketua_kk'] ?? '');
|
|
$jumlahAnggota = (int)($_POST['jumlah_anggota'] ?? 0);
|
|
$lat = $_POST['latitude'] ?? null;
|
|
$lng = $_POST['longitude'] ?? null;
|
|
$rumahIbadahId = $_POST['rumah_ibadah_id'] ?? null;
|
|
$rumahIbadahNama = trim($_POST['rumah_ibadah_nama'] ?? '');
|
|
$jarak = $_POST['jarak_ke_rumah_ibadah_m'] ?? null;
|
|
|
|
if ($namaKetuaKk === '' || $jumlahAnggota <= 0 || $lat === null || $lng === null) {
|
|
echo json_encode(['status' => 'error', 'message' => 'Data penduduk miskin tidak lengkap']);
|
|
$conn->close();
|
|
exit;
|
|
}
|
|
|
|
$lat = (float)$lat;
|
|
$lng = (float)$lng;
|
|
$nearest = findNearestRumahIbadah($conn, $lat, $lng);
|
|
|
|
if (!$nearest) {
|
|
echo json_encode(['status' => 'error', 'message' => 'Tambahkan rumah ibadah terlebih dahulu']);
|
|
$conn->close();
|
|
exit;
|
|
}
|
|
|
|
$jarak = $nearest['distance'];
|
|
$rumahIbadahId = $nearest['id'];
|
|
$rumahIbadahNama = $nearest['nama'];
|
|
|
|
$stmt = $conn->prepare("INSERT INTO penduduk_miskin (nama_ketua_kk, jumlah_anggota, latitude, longitude, rumah_ibadah_id, rumah_ibadah_nama, jarak_ke_rumah_ibadah_m) VALUES (?, ?, ?, ?, ?, ?, ?)");
|
|
$stmt->bind_param("siddisd", $namaKetuaKk, $jumlahAnggota, $lat, $lng, $rumahIbadahId, $rumahIbadahNama, $jarak);
|
|
|
|
if ($stmt->execute()) {
|
|
echo json_encode(['status' => 'success', 'message' => 'Penduduk miskin berhasil disimpan']);
|
|
} else {
|
|
echo json_encode(['status' => 'error', 'message' => $stmt->error]);
|
|
}
|
|
|
|
$stmt->close();
|
|
}
|
|
$conn->close();
|
|
?>
|