<?php
session_start();
require 'routeros_api.class.php';

// harus login
if (!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
    die("Belum login.");
}

// ambil ID dari query string
$id = isset($_GET['id']) ? $_GET['id'] : '';
if ($id === '') {
    die("ID AP tidak ditemukan.");
}

// tentukan file JSON per router
$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)) die("File data AP tidak ditemukan.");

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

// cari AP by id
$foundKey = null;
foreach($apList as $k => $ap){
    if(isset($ap['id']) && $ap['id'] === $id){
        $foundKey = $k;
        break;
    }
}
if($foundKey === null) die("AP tidak ditemukan.");

// ambil IP AP yang akan dihapus
$ip = $apList[$foundKey]['ip'] ?? '';

// Hapus dari MikroTik Netwatch & IP Binding
$API = new RouterosAPI();
$API->debug = false;
if($API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
    if($ip){
        // Netwatch
        $entries = $API->comm("/tool/netwatch/print", ["?host" => $ip]);
        foreach($entries as $e){
            if(!empty($e['.id'])){
                $API->comm("/tool/netwatch/remove", [".id"=>$e['.id']]);
            }
        }

        // IP Binding Hotspot
        $bindings = $API->comm("/ip/hotspot/ip-binding/print", ["?address"=>$ip]);
        foreach($bindings as $b){
            if(!empty($b['.id'])){
                $API->comm("/ip/hotspot/ip-binding/remove", [".id"=>$b['.id']]);
            }
        }
    }
    $API->disconnect();
}

// Hapus dari array dan simpan kembali
unset($apList[$foundKey]);
$apList = array_values($apList);
file_put_contents($dataFile, json_encode($apList, JSON_PRETTY_PRINT));

// redirect kembali ke peta
header("Location: peta.php");
exit;
