<?php
declare(strict_types=1);

require_once __DIR__ . '/db_pdo.php';
require_once __DIR__ . '/spatial_helpers.php';

$input = get_json_input();

$namaJalan = trim((string) ($input['nama_jalan'] ?? ''));
$status = trim((string) ($input['status'] ?? ''));
$panjangMeter = (float) ($input['panjang_meter'] ?? 0);
$wkt = sanitize_wkt((string) ($input['wkt'] ?? ''), 'LINESTRING');

$allowedStatus = ['nasional', 'provinsi', 'kabupaten'];

if ($namaJalan === '' || !in_array($status, $allowedStatus, true)) {
    json_response(422, [
        'success' => false,
        'message' => 'Nama jalan wajib diisi dan status harus nasional/provinsi/kabupaten.',
    ]);
}

if ($panjangMeter <= 0) {
    json_response(422, [
        'success' => false,
        'message' => 'Panjang jalan harus lebih dari 0 meter.',
    ]);
}

$sql = 'INSERT INTO jalan (nama_jalan, status, panjang_meter, geom) VALUES (:nama_jalan, :status, :panjang_meter, ST_GeomFromText(:wkt))';
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':nama_jalan' => $namaJalan,
    ':status' => $status,
    ':panjang_meter' => $panjangMeter,
    ':wkt' => $wkt,
]);

json_response(201, [
    'success' => true,
    'message' => 'Data jalan berhasil disimpan.',
    'id' => (int) $pdo->lastInsertId(),
]);
