<?php
require 'db.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['id'])) {
    $id = $_POST['id'] ?? null;
    $nama = $_POST['nama'] ?? null;
    $nomor = $_POST['nomor'] ?? null;
    $status = $_POST['status'] ?? null;
    $lat = $_POST['latitude'] ?? null;
    $lng = $_POST['longitude'] ?? null;

    if ($id === null) {
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "Missing id."]);
        exit;
    }

    $fields = [];
    $values = [];

    if ($nama !== null) {
        $fields[] = "nama = ?";
        $values[] = $nama;
    }
    if ($nomor !== null) {
        $fields[] = "nomor = ?";
        $values[] = $nomor;
    }
    if ($status !== null) {
        $fields[] = "status = ?";
        $values[] = $status;
    }
    if ($lat !== null) {
        $fields[] = "Latitude = ?";
        $values[] = $lat;
    }
    if ($lng !== null) {
        $fields[] = "Longitude = ?";
        $values[] = $lng;
    }

    if (count($fields) === 0) {
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "No fields to update."]);
        exit;
    }

    $values[] = $id;

    $sql = "UPDATE SPBU SET " . implode(", ", $fields) . " WHERE id = ?";
    $stmt = $pdo->prepare($sql);

    if ($stmt->execute($values)) {
        echo json_encode(["status" => "success", "message" => "Data updated!"]);
    } else {
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Failed to update data."]);
    }
} else {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Method not allowed."]);
}
?>