<?php
session_start();
require 'routeros_api.class.php';
header('Content-Type: text/html; charset=utf-8');

// --- Tentukan file JSON per router ---
$mt_ip = $_SESSION['ip'] ?? '';
if(!$mt_ip) die("Router tidak terdeteksi.");

$safe_ip = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $mt_ip);
$dataFile = __DIR__ . "/ap_data_{$safe_ip}.json";
$logFile  = __DIR__ . '/ap_update_log.txt';

// pastikan file ada
if(!file_exists($dataFile)) file_put_contents($dataFile, json_encode([]));
$apList = json_decode(file_get_contents($dataFile), true) ?: [];

// --- Ambil ID dari GET ---
$id = $_GET['id'] ?? '';
$found = null;
$idx   = null;
foreach($apList as $k => $ap){
    if(isset($ap['id']) && $ap['id'] === $id){
        $found = $ap;
        $idx = $k;
        break;
    }
}
if(!$found) die("AP tidak ditemukan.");

$oldData = $found;
$oldIp   = $oldData['ip'];

// --- Proses POST (update) ---
if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $name = trim($_POST['name']);
    $ip   = trim($_POST['ip']);
    $lat  = floatval($_POST['lat']);
    $lng  = floatval($_POST['lng']);
    $line      = $_POST['line'] ?? '';
    $lineColor = $_POST['lineColor'] ?? '#1e90ff';

    // --- Cek duplicate IP ---
    foreach($apList as $k => $ap){
        if($k !== $idx && $ap['ip'] === $ip){
            die("Gagal: IP sudah digunakan AP lain.");
        }
    }

    // --- Update JSON ---
    $apList[$idx] = [
        'id'        => $id,
        'name'      => $name,
        'ip'        => $ip,
        'lat'       => $lat,
        'lng'       => $lng,
        'line'      => $line ?: null,
        'lineColor' => $lineColor,
        'icon'      => $oldData['icon'] ?? 'wifi'
    ];

    if(false === file_put_contents($dataFile, json_encode($apList, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))){
        die("Gagal menyimpan JSON");
    }

    // --- Update ke MikroTik Netwatch ---
    $status = '';
    $API = new RouterosAPI();
    $API->debug = false;
    if($API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])){
        $entries = $API->comm("/tool/netwatch/print", ["?host"=>$oldIp]);

        // --------------------------------------------
        // Sesuai preferensi: 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
        // --------------------------------------------
        $parentToken = null;
        if (!empty($line)) {
            $foundParentName = null;
            foreach ($apList as $existingAp) {
                if (isset($existingAp['id']) && $existingAp['id'] === $line) {
                    $foundParentName = trim($existingAp['name']);
                    break;
                }
            }
            // gunakan nama parent jika ditemukan, jika tidak gunakan apa yang diberikan (bisa id atau ip)
            $parentToken = $foundParentName ?: $line;
        }

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

        if(!empty($entries[0]['.id'])){
            // update existing
            $API->comm("/tool/netwatch/set", [
                ".id"     => $entries[0]['.id'],
                "host"    => $ip,
                "comment" => $commentValue,
                // set interval 10s and timeout 5s as requested
                "interval" => "10s",
                "timeout"  => "5s"
            ]);
            $status = "UPDATE OK: {$oldIp} → {$ip} ({$name})";
        } else {
            // jika host hilang, tambahkan baru
            $API->comm("/tool/netwatch/add", [
                "host"     => $ip,
                "comment"  => $commentValue,
                // set interval 10s and timeout 5s as requested
                "interval" => "10s",
                "timeout"  => "5s"
            ]);
            $status = "ADD NEW: {$ip} ({$name})";
        }
        $API->disconnect();
    } else {
        $status = "FAILED: Tidak bisa konek ke MikroTik";
    }

    // --- Simpan log ---
    $logText  = "[".date("Y-m-d H:i:s")."]\n";
    $logText .= "OLD DATA: ".json_encode($oldData)."\n";
    $logText .= "NEW DATA: ".json_encode($apList[$idx])."\n";
    $logText .= "MIKROTIK: ".$status."\n\n";
    file_put_contents($logFile, $logText, FILE_APPEND);

    // --- Redirect ke peta.php ---
    header("Location: peta.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit AP</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{ background:#f9fafb; font-family:system-ui, sans-serif; padding:10px;}
.card{ max-width:480px; margin:auto; border-radius:12px; box-shadow:0 4px 12px rgba(0,0,0,0.1);}
.card-header{ display:flex; justify-content:space-between; align-items:center; background:#0ea5e9; color:#fff; font-weight:600; padding:12px 20px; border-top-left-radius:12px; border-top-right-radius:12px;}
.card-body{ padding:20px; }
input, select{width:100%; padding:8px; margin-bottom:12px; border-radius:6px; border:1px solid #ccc;}
.btn-primary{ background:#0ea5e9; border:none; width:100%;}
.btn-secondary{ background:#6b7280; border:none; color:#fff;}
</style>
</head>
<body>
<div class="card">
    <div class="card-header">
        <span>✏️ Edit AP</span>
        <a href="peta.php" class="btn btn-secondary btn-sm">⬅️ Kembali</a>
    </div>
    <div class="card-body">
        <form method="post">
            <label>Nama AP</label>
            <input type="text" name="name" value="<?= htmlspecialchars($oldData['name']) ?>" required>

            <label>IP</label>
            <input type="text" name="ip" value="<?= htmlspecialchars($oldData['ip']) ?>" required>

            <label>Latitude</label>
            <input type="text" name="lat" value="<?= htmlspecialchars($oldData['lat']) ?>" required>

            <label>Longitude</label>
            <input type="text" name="lng" value="<?= htmlspecialchars($oldData['lng']) ?>" required>

            <label>Parent (Line ke)</label>
            <select name="line">
                <option value="">— Tidak ada —</option>
                <?php foreach($apList as $ap): 
                    if($ap['id'] === $id) continue; // skip self
                    $selected = ($oldData['line'] ?? '') === $ap['id'] ? 'selected' : '';
                    echo '<option value="'.htmlspecialchars($ap['id']).'" '.$selected.'>'.htmlspecialchars($ap['name']).'</option>';
                endforeach; ?>
            </select>

            <label>Warna Garis</label>
            <input type="color" name="lineColor" value="<?= htmlspecialchars($oldData['lineColor'] ?? '#1e90ff') ?>">

            <button type="submit" class="btn btn-primary">💾 Simpan Perubahan</button>
        </form>
    </div>
</div>
</body>
</html>