<?php
declare(strict_types=1);

header('Content-Type: application/json');

require_once __DIR__ . '/db.php';

$input = json_decode(file_get_contents('php://input'), true);

if (!is_array($input)) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Format request tidak valid.',
    ]);
    exit;
}

$id = (int) ($input['id'] ?? 0);
$latitude = (float) ($input['latitude'] ?? 0);
$longitude = (float) ($input['longitude'] ?? 0);

if ($id <= 0) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'ID titik tidak valid.',
    ]);
    exit;
}

if (!is_finite($latitude) || !is_finite($longitude)) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Koordinat latitude atau longitude tidak valid.',
    ]);
    exit;
}

$stmt = $connection->prepare('UPDATE spbu_points SET latitude = ?, longitude = ? WHERE id = ?');

if (!$stmt) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Gagal menyiapkan query update: ' . $connection->error,
    ]);
    exit;
}

$stmt->bind_param('ddi', $latitude, $longitude, $id);

if (!$stmt->execute()) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Gagal memperbarui posisi: ' . $stmt->error,
    ]);
    $stmt->close();
    exit;
}

if ($stmt->affected_rows < 1) {
    $stmt->close();

    $checkStmt = $connection->prepare('SELECT id FROM spbu_points WHERE id = ? LIMIT 1');

    if (!$checkStmt) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Gagal memverifikasi data titik: ' . $connection->error,
        ]);
        exit;
    }

    $checkStmt->bind_param('i', $id);

    if (!$checkStmt->execute()) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Gagal memverifikasi data titik: ' . $checkStmt->error,
        ]);
        $checkStmt->close();
        exit;
    }

    $checkResult = $checkStmt->get_result();

    if ($checkResult->num_rows < 1) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Data dengan ID tersebut tidak ditemukan.',
        ]);
        $checkStmt->close();
        exit;
    }

    $checkStmt->close();
}

$stmt->close();

echo json_encode([
    'success' => true,
    'message' => 'Posisi titik berhasil diperbarui.',
]);
