Files
UAS-SIG-WebGIS-Poverty-Mapping/save_improved.php
T
2026-06-13 13:38:52 +07:00

107 lines
2.8 KiB
PHP

<?php
/**
* WebGIS API - Save/Create Data Endpoint (Improved Version)
* Version: 1.0
* Method: POST
* Description: Create new feature data with validation
*/
require_once 'api_utils.php';
// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
sendError('Method not allowed', 405);
}
// Get JSON input
$json = file_get_contents('php://input');
$data = json_decode($json, true);
if ($data === null) {
sendError('Invalid JSON input', 400);
}
$conn = getConnection();
// Validation rules
$rules = [
'tipe' => ['required' => true, 'type' => 'enum', 'values' => ['point', 'worship', 'poor_house', 'jalan', 'parsil']],
'nama' => ['type' => 'string', 'maxLength' => 200],
'alamat' => ['type' => 'string', 'maxLength' => 255],
'latitude' => ['type' => 'double'],
'longitude' => ['type' => 'double'],
];
// Validate
$errors = validateInput($data, $rules);
if (!empty($errors)) {
sendError('Validation failed', 400, $errors);
}
// Sanitize
$data = sanitizeInput($data, $conn);
// Build INSERT query
$fields = [];
$values = [];
$allowed_fields = [
'tipe', 'nama', 'jenis', 'alamat', 'kontak', 'no_wa', 'kegiatan', 'kapasitas',
'radius_meter', 'nama_kepala_keluarga', 'jumlah_anggota', 'kondisi_rumah',
'sumber_penghasilan', 'kebutuhan_prioritas', 'status_bantuan', 'latitude',
'longitude', 'status', 'panjang', 'luas', 'geom'
];
foreach ($allowed_fields as $field) {
if (isset($data[$field]) && $data[$field] !== null && $data[$field] !== '') {
$fields[] = $field;
if ($field === 'geom') {
// GeoJSON should be stored as-is
if (is_array($data[$field])) {
$geom_json = json_encode($data[$field]);
} else {
$geom_json = $data[$field];
}
$values[] = "'" . $conn->real_escape_string($geom_json) . "'";
} else if (is_numeric($data[$field]) && $field !== 'nama_kepala_keluarga') {
$values[] = $data[$field];
} else {
$values[] = "'" . $data[$field] . "'";
}
}
}
// Add default values
$fields[] = 'created_at';
$values[] = "NOW()";
if (!isset($data['status'])) {
$fields[] = 'status';
$values[] = "'aktif'";
}
$sql = "INSERT INTO data_unified (" . implode(',', $fields) . ") VALUES (" . implode(',', $values) . ")";
try {
if ($conn->query($sql) === TRUE) {
$id = $conn->insert_id;
// Log activity
logActivity($conn, 'INSERT', [
'table' => 'data_unified',
'id' => $id,
'tipe' => $data['tipe']
]);
sendResponse(true, 'Data saved successfully', ['id' => $id], 200);
} else {
sendError('Failed to save data: ' . $conn->error, 500);
}
} catch (Exception $e) {
sendError('Server error: ' . $e->getMessage(), 500);
} finally {
$conn->close();
}
?>