Files
2026-06-11 14:02:22 +07:00

87 lines
3.1 KiB
PHP

<?php
// api/spbu.php — CRUD untuk data SPBU (Point)
require_once 'config.php';
$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
switch ($method) {
// ── GET all or single ─────────────────────────────────────
case 'GET':
if ($id) {
$stmt = $db->prepare("SELECT * FROM spbu WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
echo json_encode($row ?: ['error' => 'Data tidak ditemukan']);
} else {
$res = $db->query("SELECT * FROM spbu ORDER BY id DESC");
$rows = [];
while ($r = $res->fetch_assoc()) $rows[] = $r;
echo json_encode($rows);
}
break;
// ── POST create ───────────────────────────────────────────
case 'POST':
$body = json_decode(file_get_contents('php://input'), true);
$stmt = $db->prepare(
"INSERT INTO spbu (nama_spbu, nomor_wa, buka_24jam, latitude, longitude)
VALUES (?, ?, ?, ?, ?)"
);
$stmt->bind_param(
'ssidd',
$body['nama_spbu'], $body['nomor_wa'],
$body['buka_24jam'],
$body['latitude'], $body['longitude']
);
if ($stmt->execute()) {
echo json_encode(['success' => true, 'id' => $db->insert_id]);
} else {
http_response_code(500);
echo json_encode(['error' => $db->error]);
}
break;
// ── PUT update ────────────────────────────────────────────
case 'PUT':
$body = json_decode(file_get_contents('php://input'), true);
$stmt = $db->prepare(
"UPDATE spbu SET nama_spbu=?, nomor_wa=?, buka_24jam=?, latitude=?, longitude=?
WHERE id=?"
);
$stmt->bind_param(
'ssiddi',
$body['nama_spbu'], $body['nomor_wa'],
$body['buka_24jam'],
$body['latitude'], $body['longitude'],
$body['id']
);
if ($stmt->execute()) {
echo json_encode(['success' => true]);
} else {
http_response_code(500);
echo json_encode(['error' => $db->error]);
}
break;
// ── DELETE ────────────────────────────────────────────────
case 'DELETE':
$stmt = $db->prepare("DELETE FROM spbu WHERE id=?");
$stmt->bind_param('i', $id);
if ($stmt->execute()) {
echo json_encode(['success' => true]);
} else {
http_response_code(500);
echo json_encode(['error' => $db->error]);
}
break;
default:
http_response_code(405);
echo json_encode(['error' => 'Method tidak diizinkan']);
}
$db->close();