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

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

$data = json_decode(file_get_contents('php://input'), true);
if(!$data || empty($data['name']) || empty($data['ip']) || !isset($data['lat']) || !isset($data['lng'])){
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'invalid_input']);
    exit;
}

$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)) file_put_contents($dataFile,json_encode([]));

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

// Cek duplicate IP
foreach($apList as $ap){ 
    if($ap['ip']===$data['ip']){
        http_response_code(400);
        echo json_encode(['success'=>false,'error'=>'duplicate_ip']); 
        exit;
    }
}

$apId = uniqid('ap_');
$new = [
    'id'        => $apId,
    'name'      => $data['name'],
    'ip'        => $data['ip'],
    'lat'       => (float)$data['lat'],
    'lng'       => (float)$data['lng'],
    'line'      => !empty($data['line']) ? $data['line'] : null,
    'lineColor' => $data['lineColor'] ?? '#00ff00', // default lime hex (tetap seperti semula)
    'icon'      => $data['icon'] ?? 'wifi'
];

$apList[] = $new;
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'=>'gagal_simpan']); 
    exit;
}

// Netwatch & IP Binding MikroTik
$API = new RouterosAPI();
$mkStatus = 'not_connected';
$bindingStatus = 'not_connected';
if($API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
    try{
        // --------------------------------------------
        // Sesuai permintaan: tulis parent sebagai NAMA (jika tersedia)
        // dan jika parent tidak ada -> jangan tulis 'none', sehingga format menjadi:
        //  - tanpa parent: NAME//COLOR//LAT,LNG
        //  - dengan parent: NAME//COLOR//PARENT_NAME/LAT,LNG
        // (fungsi lain tidak diubah)
        // --------------------------------------------
        $parentToken = null;
        if (!empty($new['line'])) {
            // jika line berisi id ap_xxx, coba cari nama parent dari $apList
            $foundParentName = null;
            foreach ($apList as $existingAp) {
                if (isset($existingAp['id']) && $existingAp['id'] === $new['line']) {
                    $foundParentName = trim($existingAp['name']);
                    break;
                }
            }
            // jika ditemukan nama parent gunakan nama, jika tidak gunakan apa yang diberikan (bisa jadi nama/ip)
            $parentToken = $foundParentName ?: $new['line'];
        }

        if ($parentToken) {
            $commentValue = $new['name'] . "//" . $new['lineColor'] . "/" . $parentToken . "//" . $new['lat'] . "," . $new['lng'];
        } else {
            // tanpa parent: tidak menulis 'none'
            $commentValue = $new['name'] . "//" . $new['lineColor'] . "///" . $new['lat'] . "," . $new['lng'];
        }

        // Netwatch
        $existing = $API->comm('/tool/netwatch/print',['?host'=>$new['ip']]);
        if(count($existing)===0){
            $API->comm('/tool/netwatch/add', [
                'host'     => $new['ip'], 
                'comment'  => $commentValue, 
                // change interval to 10s and add timeout 5s per request
                'interval' => '10s',
                'timeout'  => '5s'
            ]);
        } else {
            // kalau sudah ada, update biar komentarnya sesuai format
            $API->comm('/tool/netwatch/set', [
                '.id'     => $existing[0]['.id'],
                'comment' => $commentValue,
                // ensure interval and timeout updated as requested
                'interval' => '10s',
                'timeout'  => '5s'
            ]);
        }
        $mkStatus = 'ok';

        // IP Binding (Hotspot)
        $existsBinding = $API->comm('/ip/hotspot/ip-binding/print', ['?address'=>$new['ip']]);
        if(count($existsBinding)===0){
            $API->comm('/ip/hotspot/ip-binding/add', [
                'address'    => $new['ip'],
                'to-address' => $new['ip'],
                'comment'    => $commentValue,
                'type'       => 'bypassed',
            ]);
        } else {
            $API->comm('/ip/hotspot/ip-binding/set', [
                '.id'       => $existsBinding[0]['.id'],
                'comment'   => $commentValue,
                'type'      => 'bypassed'
            ]);
        }
        $bindingStatus = 'ok';
    }catch(Exception $e){ 
        $mkStatus = 'error: '.$e->getMessage(); 
        $bindingStatus = 'error: '.$e->getMessage();
    }
    $API->disconnect();
}

echo json_encode([
    'success'   => true,
    'ap'        => $new,
    'mikrotik'  => $mkStatus,
    'ipBinding' => $bindingStatus
]);