<?php
session_start();
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'petugas'])) {
    header('Content-Type: application/json');
    http_response_code(403);
    echo json_encode(['status'=>'error','message'=>'Akses ditolak.']);
    exit;
}

include '../koneksi.php';
header('Content-Type: application/json');

$nama_jalan    = trim($_POST['nama_jalan']    ?? '');
$status_jalan  = trim($_POST['status_jalan']  ?? '');
$panjang_meter = trim($_POST['panjang_meter'] ?? '0');
$koordinat     = trim($_POST['koordinat']     ?? '');

if (!$nama_jalan || !$status_jalan || !$koordinat) {
    echo json_encode(['status'=>'error','message'=>'Field wajib tidak boleh kosong.']);
    exit;
}

$decoded = json_decode($koordinat, true);
if (!$decoded || ($decoded['geometry']['type'] ?? '') !== 'LineString') {
    echo json_encode(['status'=>'error','message'=>'Format GeoJSON tidak valid.']);
    exit;
}

$valid_status = ['Jalan Nasional','Jalan Provinsi','Jalan Kabupaten'];
if (!in_array($status_jalan, $valid_status)) {
    echo json_encode(['status'=>'error','message'=>'Status jalan tidak valid.']);
    exit;
}

try {
    $stmt = $pdo->prepare(
        "INSERT INTO jalan (nama_jalan, status_jalan, panjang_meter, koordinat)
         VALUES (?, ?, ?, ?)"
    );
    $stmt->execute([$nama_jalan, $status_jalan, $panjang_meter, $koordinat]);
    $id   = $pdo->lastInsertId();
    
    $stmtSelect = $pdo->prepare("SELECT * FROM jalan WHERE id=?");
    $stmtSelect->execute([$id]);
    $data = $stmtSelect->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode(['status'=>'success','data'=>$data]);
} catch (PDOException $e) {
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>
