real_escape_string($_POST['nama'] ?? ''); $kategori = $conn->real_escape_string($_POST['kategori_bantuan'] ?? 'Makan'); $jumlah_jiwa = (int)($_POST['jumlah_jiwa'] ?? 1); $lat = (float)($_POST['lat'] ?? 0); $lng = (float)($_POST['lng'] ?? 0); } else { $data = json_decode(file_get_contents("php://input")); if ($data) { $id = (int)($data->id ?? 0); $nama = $conn->real_escape_string($data->nama ?? ''); $kategori = $conn->real_escape_string($data->kategori_bantuan ?? 'Makan'); $jumlah_jiwa = (int)($data->jumlah_jiwa ?? 1); $lat = (float)($data->lat ?? 0); $lng = (float)($data->lng ?? 0); } } if ($id > 0) { // Get current files to delete them if updated $old_foto_rumah = null; $old_foto_kk = null; $res = $conn->query("SELECT foto_rumah, foto_kk FROM penduduk_miskin WHERE id=$id"); if ($res && $row = $res->fetch_assoc()) { $old_foto_rumah = $row['foto_rumah']; $old_foto_kk = $row['foto_kk']; } $upload_dir = "../../uploads/"; if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); } $foto_rumah = null; $foto_kk = null; function uploadFile($fileKey, $upload_dir) { if (isset($_FILES[$fileKey]) && $_FILES[$fileKey]['error'] === UPLOAD_ERR_OK) { $fileTmpPath = $_FILES[$fileKey]['tmp_name']; $fileName = $_FILES[$fileKey]['name']; $fileNameCmps = explode(".", $fileName); $fileExtension = strtolower(end($fileNameCmps)); $allowedfileExtensions = array('jpg', 'jpeg', 'png', 'gif'); if (in_array($fileExtension, $allowedfileExtensions)) { $newFileName = uniqid() . '_' . preg_replace('/[^a-zA-Z0-9\._-]/', '_', $fileName); $dest_path = $upload_dir . $newFileName; if (move_uploaded_file($fileTmpPath, $dest_path)) { return $newFileName; } } } return null; } $foto_rumah = uploadFile('foto_rumah', $upload_dir); $foto_kk = uploadFile('foto_kk', $upload_dir); // Build update fields $update_fields = [ "nama='$nama'", "kategori_bantuan='$kategori'", "jumlah_jiwa=$jumlah_jiwa", "lat=$lat", "lng=$lng" ]; if ($foto_rumah !== null) { $update_fields[] = "foto_rumah='$foto_rumah'"; if ($old_foto_rumah && file_exists($upload_dir . $old_foto_rumah)) { unlink($upload_dir . $old_foto_rumah); } } if ($foto_kk !== null) { $update_fields[] = "foto_kk='$foto_kk'"; if ($old_foto_kk && file_exists($upload_dir . $old_foto_kk)) { unlink($upload_dir . $old_foto_kk); } } $query = "UPDATE penduduk_miskin SET " . implode(", ", $update_fields) . " WHERE id=$id"; if ($conn->query($query)) { echo json_encode(["status" => "success", "message" => "Update berhasil."]); } else { echo json_encode(["status" => "error", "message" => "Gagal update: " . $conn->error]); } } else { echo json_encode(["status" => "error", "message" => "ID tidak diberikan."]); } ?>