<?php
declare(strict_types=1);

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

$input = get_json_input();

$id = (int) ($input['id'] ?? 0);
$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 ($id <= 0) {
    json_response(422, [
        'success' => false,
        'message' => 'ID jalan tidak valid.',
    ]);
}

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 = 'UPDATE jalan SET nama_jalan = :nama_jalan, status = :status, panjang_meter = :panjang_meter, geom = ST_GeomFromText(:wkt), updated_at = CURRENT_TIMESTAMP WHERE id = :id';
$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':id' => $id,
    ':nama_jalan' => $namaJalan,
    ':status' => $status,
    ':panjang_meter' => $panjangMeter,
    ':wkt' => $wkt,
]);

if ($stmt->rowCount() < 1) {
    $checkStmt = $pdo->prepare('SELECT id FROM jalan WHERE id = :id LIMIT 1');
    $checkStmt->execute([':id' => $id]);
    if (!$checkStmt->fetch()) {
        json_response(404, [
            'success' => false,
            'message' => 'Data jalan tidak ditemukan.',
        ]);
    }
}

json_response(200, [
    'success' => true,
    'message' => 'Data jalan berhasil diperbarui.',
]);
