<?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);

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

$stmt = $connection->prepare('DELETE FROM spbu_points WHERE id = ?');

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

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

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

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

$stmt->close();

echo json_encode([
    'success' => true,
    'message' => 'Data berhasil dihapus.',
]);
