<?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 || $nama === null || $nomor === null || $status === null) {
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "Missing required fields."]);
        exit;
    }

    $params = [$nama, $nomor, $status];
    $sql = "UPDATE SPBU SET nama = ?, nomor = ?, status = ?";

    // Optional location update (used for drag-to-move)
    if ($lat !== null && $lng !== null && is_numeric($lat) && is_numeric($lng)) {
        $sql .= ", Latitude = ?, Longitude = ?";
        $params[] = $lat;
        $params[] = $lng;
    }

    $sql .= " WHERE id = ?";
    $params[] = $id;

    $stmt = $pdo->prepare($sql);

    if ($stmt->execute($params)) {
        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."]);
}
?>