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

// 🛡️ Cek session login Mikrotik
if(!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
    http_response_code(401);
    echo json_encode(['success'=>false,'error'=>'not_authenticated']);
    exit;
}

// 📝 Ambil data dari body (JSON)
$data = json_decode(file_get_contents('php://input'), true);
if(!$data || empty($data['id']) || empty($data['name']) || empty($data['ip'])){
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'invalid_input']);
    exit;
}

// 📁 File JSON berdasarkan IP router
$safe_ip = preg_replace('/[^a-zA-Z0-9_\-\.]/','_', $_SESSION['ip']);
$dataFile = __DIR__."/ap_data_{$safe_ip}.json";
$apList = json_decode(file_get_contents($dataFile), true) ?: [];

// 🔍 Cari AP yang diedit
$idx = null;
foreach($apList as $k=>$ap){ 
    if($ap['id']===$data['id']){ 
        $idx=$k; 
        break; 
    } 
}
if($idx===null){ 
    http_response_code(404); 
    echo json_encode(['success'=>false,'error'=>'not_found']); 
    exit; 
}

// Simpan IP lama
$oldIp = $apList[$idx]['ip'];

// 🚫 Cek IP duplikat
foreach($apList as $k=>$ap){ 
    if($k!=$idx && $ap['ip']===$data['ip']){ 
        echo json_encode(['success'=>false,'error'=>'duplicate_ip']); 
        exit; 
    } 
}

// 🌈 Gunakan warna lama jika kosong
if(empty($data['lineColor']) && isset($apList[$idx]['lineColor'])){
    $data['lineColor'] = $apList[$idx]['lineColor'];
}

// 🧭 Update data lokal JSON
$apList[$idx] = [
    'id'        => $data['id'],
    'name'      => $data['name'],
    'ip'        => $data['ip'],
    'lat'       => (float)$data['lat'],
    'lng'       => (float)$data['lng'],
    'line'      => $data['line'] ?: null,
    'lineColor' => $data['lineColor'] ?? 'lime',
    'icon'      => $apList[$idx]['icon'] ?? 'wifi'
];

if(false === file_put_contents($dataFile, json_encode($apList, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))){
    http_response_code(500);
    echo json_encode(['success'=>false,'error'=>'failed_save']); 
    exit;
}

// 🌐 Update Netwatch & IP Binding MikroTik
$API = new RouterosAPI();
$status = 'not_connected';
$bindingStatus = 'not_connected';

if($API->connect($_SESSION['ip'],$_SESSION['user'],$_SESSION['pass'])){

    // ✅ Format comment: tulis parent sebagai NAMA jika tersedia di ap_data,
    // dan jika parent tidak ada maka jangan tulis 'none'
    $parentToken = null;
    if (!empty($data['line'])) {
        $foundParentName = null;
        foreach ($apList as $existingAp) {
            if (isset($existingAp['id']) && $existingAp['id'] === $data['line']) {
                $foundParentName = trim($existingAp['name']);
                break;
            }
        }
        // gunakan nama parent jika ditemukan, jika tidak gunakan apa yang diberikan (bisa jadi id atau ip)
        $parentToken = $foundParentName ?: $data['line'];
    }

    if ($parentToken) {
        $commentValue = $data['name']."//".$data['lineColor']."/".$parentToken."//".$data['lat'].",".$data['lng'];
    } else {
        $commentValue = $data['name']."//".$data['lineColor']."///".$data['lat'].",".$data['lng'];
    }

    // 🔁 Netwatch
    $entries = $API->comm('/tool/netwatch/print',['?host'=>$oldIp]);
    if(!empty($entries[0]['.id'])){
        $API->comm('/tool/netwatch/set', [
            '.id'     => $entries[0]['.id'],
            'host'    => $data['ip'],
            'comment' => $commentValue,
            'interval' => '10s',
            'timeout'  => '5s'
        ]);
        $status='ok';
    } else {
        $API->comm('/tool/netwatch/add',[
            'host'     => $data['ip'],
            'comment'  => $commentValue,
            'interval' => '10s',
            'timeout'  => '5s'
        ]);
        $status='added';
    }

    // 🔁 IP Binding Hotspot
    $binding = $API->comm('/ip/hotspot/ip-binding/print',['?address'=>$oldIp]);
    if(!empty($binding[0]['.id'])){
        $API->comm('/ip/hotspot/ip-binding/set',[
            '.id'       => $binding[0]['.id'],
            'address'   => $data['ip'],
            'to-address'=> $data['ip'],
            'comment'   => $commentValue,
            'type'      => 'bypassed'
        ]);
        $bindingStatus='updated';
    } else {
        $API->comm('/ip/hotspot/ip-binding/add',[
            'address'   => $data['ip'],
            'to-address'=> $data['ip'],
            'comment'   => $commentValue,
            'type'      => 'bypassed'
        ]);
        $bindingStatus='added';
    }

    $API->disconnect();
}

// ✅ Balikkan response
echo json_encode([
    'success'        => true,
    'ap'             => $apList[$idx],
    'mikrotik'       => $status,
    'hotspotBinding' => $bindingStatus
]);