39 lines
1.8 KiB
PHP
39 lines
1.8 KiB
PHP
<?php
|
|
// api/roads.php — GET / POST / DELETE jalan (polyline)
|
|
require_once __DIR__ . '/config.php';
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
|
|
|
if ($method === 'GET') {
|
|
$rows = getDB()->query("SELECT * FROM roads ORDER BY created_at DESC")->fetchAll();
|
|
foreach ($rows as &$r) $r['length_m'] = (int)$r['length_m'];
|
|
echo json_encode(['success'=>true,'data'=>$rows]); exit;
|
|
}
|
|
|
|
if ($method === 'POST') {
|
|
$b = json_decode(file_get_contents('php://input'),true);
|
|
$name = trim($b['name'] ?? '');
|
|
$status = trim($b['status'] ?? 'kabupaten');
|
|
$len = (int)($b['length_m'] ?? 0);
|
|
$coords = $b['coords'] ?? '[]';
|
|
$allowed = ['nasional','provinsi','kabupaten'];
|
|
if (!$name){ http_response_code(400); echo json_encode(['error'=>'Nama wajib diisi']); exit; }
|
|
if (!in_array($status,$allowed)) $status='kabupaten';
|
|
$pdo = getDB();
|
|
$stmt = $pdo->prepare("INSERT INTO roads (name,status,length_m,coords) VALUES (:n,:s,:l,:c)");
|
|
$stmt->execute([':n'=>$name,':s'=>$status,':l'=>$len,':c'=>$coords]);
|
|
$id = $pdo->lastInsertId();
|
|
$row = $pdo->query("SELECT * FROM roads WHERE id=$id")->fetch();
|
|
$row['length_m']=(int)$row['length_m'];
|
|
http_response_code(201); echo json_encode(['success'=>true,'data'=>$row]); exit;
|
|
}
|
|
|
|
if ($method === 'DELETE') {
|
|
$id=(int)($_GET['id']??0);
|
|
if($id<=0){http_response_code(400);echo json_encode(['error'=>'ID tidak valid']);exit;}
|
|
$stmt=getDB()->prepare("DELETE FROM roads WHERE id=:id");
|
|
$stmt->execute([':id'=>$id]);
|
|
if($stmt->rowCount()===0){http_response_code(404);echo json_encode(['error'=>'Tidak ditemukan']);exit;}
|
|
echo json_encode(['success'=>true,'message'=>'Jalan dihapus']); exit;
|
|
}
|
|
|
|
http_response_code(405); echo json_encode(['error'=>'Method tidak diizinkan']); |