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

$nama = trim((string) ($input['nama'] ?? ''));
$no = trim((string) ($input['no'] ?? ''));
$status24jam = trim((string) ($input['status_24jam'] ?? ''));
$latitude = (float) ($input['latitude'] ?? 0);
$longitude = (float) ($input['longitude'] ?? 0);

if ($nama === '' || $no === '' || $status24jam === '') {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Nama, no, dan status wajib diisi.',
    ]);
    exit;
}

if (!in_array($status24jam, ['24jam', 'tidak'], true)) {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Status harus 24jam atau tidak.',
    ]);
    exit;
}

$stmt = $connection->prepare('INSERT INTO spbu_points (nama, no, status_24jam, latitude, longitude) VALUES (?, ?, ?, ?, ?)');

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

$stmt->bind_param('sssdd', $nama, $no, $status24jam, $latitude, $longitude);

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

$stmt->close();

echo json_encode([
    'success' => true,
    'message' => 'Data berhasil disimpan.',
    'id' => $connection->insert_id,
]);