<?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.");

$ap = $apList[$foundKey];
$apType = $ap['type'] ?? 'wifi';
$ip = $ap['ip'] ?? '';

// Hapus dari MikroTik
$API = new RouterosAPI();
$API->debug = false;
if($API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
    
    if ($apType === 'wifi') {
        // ===== HAPUS WIFI DATA =====
        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']]);
                }
            }
        }
        
    } else if ($apType === 'odp') {
        // ===== HAPUS ODP CERTIFICATE =====
        try {
            // Ambil semua certificate tanpa filter
            $allCerts = $API->comm('/certificate/print');
            
            // Cari certificate yang dimulai dengan ID
            foreach ($allCerts as $cert) {
                $certName = $cert['name'] ?? '';
                
                // Check jika cert name dimulai dengan ID AP
                if (strpos($certName, $id . '#') === 0) {
                    if (!empty($cert['.id'])) {
                        $API->comm('/certificate/remove', ['.id' => $cert['.id']]);
                        //error_log("Deleted ODP certificate: " . $certName);//
                    }
                }
            }
        } catch (Exception $e) {
            //error_log("Error deleting ODP certificate: " . $e->getMessage());//
        }
    }
    
    $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 | JSON_UNESCAPED_UNICODE));

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