<?php
// api/iot_map.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *'); // Mengizinkan akses AJAX dari simulator
header('Access-Control-Allow-Methods: GET, POST');

include '../config/database.php';

$key = $_REQUEST['k'] ?? ''; // API Key
$dev = $_REQUEST['d'] ?? ''; // ID Device (misal: mobil_01)
$action = $_REQUEST['action'] ?? ''; // get_route, set_route, get_location, set_location

if (empty($key)) { die(json_encode(["error" => "API Key Kosong"])); }
if (empty($dev)) { die(json_encode(["error" => "Device ID Kosong"])); }
if (empty($action)) { die(json_encode(["error" => "Action Kosong"])); }

// 1. Cek Validitas API Key
$stmt_key = mysqli_prepare($conn, "SELECT user_id FROM user_api_keys WHERE key_string = ? LIMIT 1");
mysqli_stmt_bind_param($stmt_key, "s", $key);
mysqli_stmt_execute($stmt_key);
$res_key = mysqli_stmt_get_result($stmt_key);

if (mysqli_num_rows($res_key) == 0) {
    die(json_encode(["error" => "API Key Invalid"]));
}
$data = mysqli_fetch_assoc($res_key);
$owner_id = $data['user_id'];
mysqli_stmt_close($stmt_key);

// Folder penyimpanan file state
$data_dir = __DIR__ . '/data/';
if (!file_exists($data_dir)) {
    mkdir($data_dir, 0777, true);
}
$file_path = $data_dir . 'map_' . $owner_id . '_' . $dev . '.json';

// Inisialisasi file state jika belum ada
$state = [
    "route" => [], // Array of {lat, lng}
    "location" => ["lat" => 0, "lng" => 0],
    "last_updated" => time()
];

if (file_exists($file_path)) {
    $content = file_get_contents($file_path);
    if ($content) {
        $state = json_decode($content, true) ?: $state;
    }
}

// 2. Tangani Action
if ($action === 'set_route') {
    // Menerima raw JSON { "route": [ {"lat": -6.2, "lng": 106.8}, ... ] }
    $input = file_get_contents('php://input');
    $payload = json_decode($input, true);
    
    if (isset($payload['route']) && is_array($payload['route'])) {
        $state['route'] = $payload['route'];
        $state['last_updated'] = time();
        file_put_contents($file_path, json_encode($state));
        echo json_encode(["status" => "success", "message" => "Rute berhasil disimpan"]);
    } else {
        echo json_encode(["error" => "Format payload route salah"]);
    }
} 
elseif ($action === 'get_route') {
    echo json_encode(["route" => $state['route']]);
}
elseif ($action === 'set_location') {
    $input = file_get_contents('php://input');
    $payload = json_decode($input, true);
    
    if (isset($payload['lat']) && isset($payload['lng'])) {
        $state['location'] = [
            "lat" => (float)$payload['lat'],
            "lng" => (float)$payload['lng']
        ];
        $state['last_updated'] = time();
        file_put_contents($file_path, json_encode($state));
        echo json_encode(["status" => "success", "message" => "Lokasi diperbarui"]);
    } else {
        echo json_encode(["error" => "Format payload lat/lng salah"]);
    }
}
elseif ($action === 'get_location') {
    echo json_encode([
        "location" => $state['location'],
        "last_updated" => $state['last_updated']
    ]);
}
else {
    echo json_encode(["error" => "Action tidak dikenal"]);
}
?>
