Files
WebGIS_Jalan-JalanRusak/api/titik.php
T
2026-06-11 02:42:37 +07:00

79 lines
2.8 KiB
PHP

<?php
require_once '../config.php';
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['id'])) exit;
// Find file to delete
$stmt = $pdo->prepare("SELECT foto_url FROM titik_rusak WHERE id = ?");
$stmt->execute([$data['id']]);
$foto = $stmt->fetchColumn();
if ($foto && file_exists('../' . $foto)) {
unlink('../' . $foto);
}
$stmt = $pdo->prepare("DELETE FROM titik_rusak WHERE id = ?");
echo json_encode(['success' => $stmt->execute([$data['id']])]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$stmt = $pdo->query("SELECT * FROM titik_rusak ORDER BY id DESC");
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
// Digunakan untuk memperbarui GeoJSON secara otomatis via Drag Handle Leaflet
$data = json_decode(file_get_contents('php://input'), true);
if (isset($data['id']) && isset($data['geojson'])) {
$stmt = $pdo->prepare("UPDATE titik_rusak SET geojson = ? WHERE id = ?");
echo json_encode(['success' => $stmt->execute([$data['geojson'], $data['id']])]);
}
exit;
}
// POST digunakan untuk Create dan Update (jika form dikirim dengan file)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$keterangan = $_POST['keterangan'] ?? '';
$geojson = $_POST['geojson'] ?? '';
$id = $_POST['id'] ?? null;
$existing_foto = $_POST['existing_foto'] ?? '';
$foto_url = $existing_foto;
if (isset($_FILES['foto']) && $_FILES['foto']['error'] === 0) {
if ($id) { // Hapus foto lama jika ada
$stmt = $pdo->prepare("SELECT foto_url FROM titik_rusak WHERE id = ?");
$stmt->execute([$id]);
$oldFoto = $stmt->fetchColumn();
if ($oldFoto && file_exists('../' . $oldFoto)) unlink('../' . $oldFoto);
}
$uploadDir = '../uploads/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
$ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
$fileName = time() . '_' . rand(1000, 9999) . '.' . $ext;
$targetFile = $uploadDir . $fileName;
if (move_uploaded_file($_FILES['foto']['tmp_name'], $targetFile)) {
$foto_url = 'uploads/' . $fileName;
}
}
if ($id) {
$stmt = $pdo->prepare("UPDATE titik_rusak SET keterangan = ?, foto_url = ?, geojson = ? WHERE id = ?");
$stmt->execute([$keterangan, $foto_url, $geojson, $id]);
} else {
$stmt = $pdo->prepare("INSERT INTO titik_rusak (keterangan, foto_url, geojson) VALUES (?, ?, ?)");
$stmt->execute([$keterangan, $foto_url, $geojson]);
}
echo json_encode(['success' => true]);
exit;
}