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

$id = $_GET['id'] ?? '';
if (!$id) exit('ID tidak ditemukan');

$API = new RouterosAPI();
$API->debug = false;
if ($API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $API->comm("/ip/firewall/nat/set", [
            ".id" => $id,
            "chain" => $_POST['chain'],
            "src-address" => $_POST['src'],
            "dst-address" => $_POST['dst'],
            "action" => $_POST['action'],
            "to-addresses" => $_POST['toaddr'],
            "comment" => $_POST['comment']
        ]);
        $API->disconnect();
        echo "<script>alert('✅ NAT berhasil diupdate');window.location='firewall_nat.php';</script>";
        exit;
    }

    $data = $API->comm("/ip/firewall/nat/print", ["?=.id" => $id]);
    $API->disconnect();
    $nat = $data[0] ?? [];
} else exit("❌ Gagal konek ke Mikrotik");
?>
<!DOCTYPE html>
<html>
<head><title>Edit NAT</title>
<style>
body { font-family: Arial; background: #f9f9f9; }
.container { max-width: 500px; margin: 40px auto; background: #fff; padding: 20px; border-radius: 10px; }
input { width: 100%; padding: 8px; margin-bottom: 10px; }
button { padding: 8px 15px; border-radius: 5px; border: none; cursor: pointer; }
.btn-save { background: #007bff; color: #fff; }
.btn-cancel { background: #6c757d; color: #fff; }
</style>
</head>
<body>
<div class="container">
<h3>Edit NAT</h3>
<form method="post">
<label>Chain:</label>
<input type="text" name="chain" value="<?= htmlspecialchars($nat['chain']) ?>">
<label>Src. Address:</label>
<input type="text" name="src" value="<?= htmlspecialchars($nat['src-address']) ?>">
<label>Dst. Address:</label>
<input type="text" name="dst" value="<?= htmlspecialchars($nat['dst-address']) ?>">
<label>Action:</label>
<input type="text" name="action" value="<?= htmlspecialchars($nat['action']) ?>">
<label>To-Addresses:</label>
<input type="text" name="toaddr" value="<?= htmlspecialchars($nat['to-addresses']) ?>">
<label>Comment:</label>
<input type="text" name="comment" value="<?= htmlspecialchars($nat['comment']) ?>">
<button class="btn-save">💾 Simpan</button>
<button class="btn-cancel" type="button" onclick="window.location='firewall_nat.php'">Batal</button>
</form>
</div>
</body>
</html>
