<?php
require __DIR__ . '/db.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }

$action = $_GET['action'] ?? '';
if ($action === '') {
    $input  = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
}

try {
    switch ($action) {
        case 'list':
            $rows = $db->query("SELECT * FROM jalan ORDER BY createdat DESC")->fetchAll();
            echo json_encode(['status' => 'success', 'data' => $rows]);
            break;

        case 'create':
            $input      = json_decode(file_get_contents('php://input'), true);
            $nama       = trim($input['nama'] ?? '');
            $status     = $input['status'] ?? 'kabupaten';
            $panjang    = isset($input['panjang_meter']) ? (float)$input['panjang_meter'] : null;
            $geom       = $input['geom'] ?? null;

            if (!$nama) {
                echo json_encode(['status' => 'error', 'message' => 'Nama jalan wajib diisi.']);
                break;
            }
            if (!in_array($status, ['nasional','provinsi','kabupaten'])) $status = 'kabupaten';

            // Validasi dan konversi geometri LineString
            $geojson = null;
            if (is_array($geom)) {
                if (isset($geom['type']) && $geom['type'] === 'LineString' && isset($geom['coordinates'])) {
                    $geojson = json_encode($geom);
                } elseif (isset($geom[0]) && is_array($geom[0])) {
                    // array of points [[lng,lat],...]
                    $geojson = json_encode([
                        'type' => 'LineString',
                        'coordinates' => $geom
                    ]);
                }
            } elseif (is_string($geom)) {
                $decoded = json_decode($geom, true);
                if ($decoded && isset($decoded['type']) && $decoded['type'] === 'LineString') {
                    $geojson = $geom;
                } else {
                    echo json_encode(['status'=>'error','message'=>'Format geometri tidak valid.']);
                    break;
                }
            }

            if (!$geojson) {
                echo json_encode(['status' => 'error', 'message' => 'Geometri tidak valid. Harus berupa GeoJSON LineString atau array koordinat.']);
                break;
            }

            $stmt = $db->prepare("INSERT INTO jalan (nama, status, panjang_meter, geom) VALUES (?, ?, ?, ?)");
            $stmt->execute([$nama, $status, $panjang, $geojson]);
            echo json_encode(['status'=>'success','message'=>'Data jalan berhasil disimpan!','id'=>$db->lastInsertId()]);
            break;

        case 'update':
            $input      = json_decode(file_get_contents('php://input'), true);
            $id         = (int)($input['id'] ?? 0);
            $nama       = trim($input['nama'] ?? '');
            $status     = $input['status'] ?? 'kabupaten';

            if (!$id)   { echo json_encode(['status'=>'error','message'=>'ID tidak valid.']); break; }
            if (!$nama) { echo json_encode(['status'=>'error','message'=>'Nama jalan wajib diisi.']); break; }
            if (!in_array($status, ['nasional','provinsi','kabupaten'])) $status = 'kabupaten';

            $stmt = $db->prepare("UPDATE jalan SET nama=?, status=?, updatedat=NOW() WHERE id=?");
            $stmt->execute([$nama, $status, $id]);
            echo json_encode(['status'=>'success','message'=>'Data jalan berhasil diperbarui.']);
            break;

        case 'delete':
            $input = json_decode(file_get_contents('php://input'), true);
            $id    = (int)($input['id'] ?? 0);
            if (!$id) { echo json_encode(['status'=>'error','message'=>'ID tidak valid.']); break; }
            $stmt = $db->prepare("DELETE FROM jalan WHERE id=?");
            $stmt->execute([$id]);
            echo json_encode(['status'=>'success','message'=>'Data jalan berhasil dihapus.']);
            break;

        default:
            echo json_encode(['status'=>'error','message'=>'Aksi tidak dikenali.']);
    }
} catch (PDOException $e) {
    echo json_encode(['status'=>'error','message'=>'Database error: '.$e->getMessage()]);
}