<?php
session_start();
require 'routeros_api.class.php';
header('Content-Type: application/json');

// --- Step 1: pastikan sudah login ---
if(!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
    http_response_code(401);
    echo json_encode(['ok'=>false,'error'=>'not_authenticated']);
    exit;
}

// --- Step 2: ambil payload JSON ---
$raw = file_get_contents('php://input');
$data = json_decode($raw,true);
if(!$data || !isset($data['id'], $data['lat'], $data['lng'])){
    http_response_code(400);
    echo json_encode(['ok'=>false,'error'=>'invalid_payload']);
    exit;
}

$id  = $data['id'];
$lat = (float)$data['lat'];
$lng = (float)$data['lng'];

// --- Step 3: tentukan file JSON ---
$mt_ip = $_SESSION['ip'];
$safe_ip = preg_replace('/[^a-zA-Z0-9_\-\.]/','_',$mt_ip);
$dataFile = __DIR__ . "/ap_data_{$safe_ip}.json";

if(!file_exists($dataFile)){
    http_response_code(404);
    echo json_encode(['ok'=>false,'error'=>'file_not_found']);
    exit;
}

$apList = json_decode(file_get_contents($dataFile), true) ?: [];

// --- Step 4: update data di JSON ---
$found = false;
$targetAp = null;
foreach($apList as &$ap){
    if(isset($ap['id']) && $ap['id'] === $id){
        $ap['lat'] = $lat;
        $ap['lng'] = $lng;
        $found = true;
        $targetAp = $ap;
        break;
    }
}
unset($ap);

if(!$found){
    http_response_code(404);
    echo json_encode(['ok'=>false,'error'=>'ap_not_found']);
    exit;
}

// simpan JSON
if(false === file_put_contents($dataFile, json_encode($apList, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))){
    http_response_code(500);
    echo json_encode(['ok'=>false,'error'=>'gagal_simpan']);
    exit;
}

// --- Step 5: update ke Mikrotik comment supaya sinkron ---
$API = new RouterosAPI();
$API->debug = false;
if($API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
    if($targetAp && isset($targetAp['ip'])){
        $rows = $API->comm('/tool/netwatch/print', ['?host'=>$targetAp['ip']]);
        if($rows && isset($rows[0]['.id'])){
            $oldComment = $rows[0]['comment'] ?? '';
            $parts = explode('/', $oldComment);

            // ganti bagian koordinat kalau ada
            $replaced = false;
            foreach ($parts as &$p) {
                if (preg_match('/^-?\d+(\.\d+)?,-?\d+(\.\d+)?$/', trim($p))) {
                    $p = "{$lat},{$lng}";
                    $replaced = true;
                }
            }
            unset($p);

            if(!$replaced){
                // kalau belum ada koordinat, tambahkan di akhir
                $parts[] = "{$lat},{$lng}";
            }

            $newComment = implode('/', $parts);

            // update comment di netwatch
            $API->comm('/tool/netwatch/set', [
                '.id'     => $rows[0]['.id'],
                'comment' => $newComment
            ]);
        }
    }
    $API->disconnect();
}

// --- Step 6: response sukses ---
echo json_encode(['ok'=>true,'lat'=>$lat,'lng'=>$lng]);
