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

if (!isset($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
    header('Location: index.php');
    exit;
}

$API = new RouterosAPI();
$API->debug = false;
$message = '';
$generatedScript = '';
$secretData = null;

try {
    if (!$API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
        throw new Exception("Gagal terhubung ke Mikrotik.");
    }

    // Ambil ID secret dari query string
    $id = $_GET['id'] ?? '';
    if ($id === '') throw new Exception("Parameter ID tidak ditemukan.");

    // Ambil data PPP Secret berdasarkan ID
    $API->write('/ppp/secret/print', false);
    $API->write('?=.id=' . $id);
    $secret = $API->read(false);
    $secret = $API->parseResponse($secret);

    if (count($secret) == 0) throw new Exception("PPP Secret tidak ditemukan.");
    $secretData = $secret[0];

    $currentName = $secretData['name'];
    $currentPassword = $secretData['password'] ?? '';
    $currentProfile = $secretData['profile'] ?? 'VPN-20mb';
    $remote = $secretData['remote-address'] ?? '';
    $currentComment = $secretData['comment'] ?? '';   // ← AMBIL COMMENT

    $dstAddress = "10.141.92.173";

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
        $nama = trim($_POST['nama']);
        $password = trim($_POST['password']);
        $profile = trim($_POST['profile']);
        $remoteNew = trim($_POST['remote']);
        $comment = trim($_POST['comment']);          // ← INPUT COMMENT

        if ($nama === '' || $password === '' || $remoteNew === '') {
            throw new Exception("Semua field wajib diisi.");
        }

        // Update PPP Secret (dengan comment)
        $API->comm('/ppp/secret/set', [
            '.id' => $id,
            'name' => $nama,
            'password' => $password,
            'profile' => $profile,
            'remote-address' => $remoteNew,
            'comment' => $comment              // ← UPDATE COMMENT
        ]);

        // Hapus NAT lama berdasarkan comment yang sesuai pola "nama - ..."
        $allNATs = $API->comm('/ip/firewall/nat/print');
        foreach ($allNATs as $rule) {
            if (isset($rule['comment']) && str_starts_with($rule['comment'], $currentName . ' - ')) {
                $API->comm('/ip/firewall/nat/remove', ['.id' => $rule['.id']]);
            }
        }

        // Tambah NAT baru sesuai pola tambah_ppp.php
        $parts = explode('.', $remoteNew);
        $last = intval(end($parts));

        $ports = [
            ['desc' => 'WEB', 'dst-port' => 12000 + $last, 'to-port' => 80],
            ['desc' => 'WINBOX', 'dst-port' => 22000 + $last, 'to-port' => 8291],
            ['desc' => 'API', 'dst-port' => 32000 + $last, 'to-port' => 8728]
        ];

        foreach ($ports as $p) {
            $API->comm('/ip/firewall/nat/add', [
                'action' => 'dst-nat',
                'chain' => 'dstnat',
                'comment' => $nama . ' - ' . $p['desc'],
                'dst-address' => $dstAddress,
                'dst-port' => $p['dst-port'],
                'protocol' => 'tcp',
                'to-addresses' => $remoteNew,
                'to-ports' => $p['to-port'],
                'disabled' => 'no'
            ]);
        }

        // Script update client
        $connectTo = $_SESSION['ip'] ?? '';

        if (preg_match('/^\[.*\]:\d+$/', $connectTo)) {
            $connectTo = preg_replace('/^\[(.*)\]:\d+$/', '$1', $connectTo);
        } else {
            $connectTo = preg_replace('/:\d+$/', '', $connectTo);
        }

        $escName = addslashes($nama);
        $escPass = addslashes($password);

        // Hitung expire berdasarkan profile
        $profile = strtoupper(trim($profile));
        $months = [
            '1-BULAN'  => 1,
            '3-BULAN'  => 3,
            '5-BULAN'  => 5,
            '6-BULAN'  => 6,
            '12-BULAN' => 12
        ];

        $expireDate = '';
        if (isset($months[$profile])) {
            $expire = strtotime("+{$months[$profile]} months");
            $expireDate = date('d/F/Y', $expire);
            $indoBulan = [
                'January'=>'Januari','February'=>'Februari','March'=>'Maret','April'=>'April',
                'May'=>'Mei','June'=>'Juni','July'=>'Juli','August'=>'Agustus',
                'September'=>'September','October'=>'Oktober','November'=>'November','December'=>'Desember'
            ];
            $expireDate = strtr($expireDate, $indoBulan);
        }

        $expLabel = $expireDate ? "Expire-$expireDate" : $profile;
        $escTunnel = addslashes("VPN remote - {$nama} ({$expLabel})");
        $akunvpn = "VPN remote - {$nama}";

        // Tambahkan catatan port otomatis
        $portNote1 = 12000 + intval(explode('.', $remoteNew)[3]);
        $portNote2 = 22000 + intval(explode('.', $remoteNew)[3]);
        $portNote3 = 32000 + intval(explode('.', $remoteNew)[3]);

$generatedScript = <<<EOT

# VPN Remote $nama ($expLabel)

#===Daftar port yang bisa digunakan===

# Webfix 80 : {$connectTo}:{$portNote1}
# Winbox 8291 : {$connectTo}:{$portNote2}
# API 8728 : {$connectTo}:{$portNote3}

#/interface l2tp-client set [find where comment~"$escName"] comment="$escTunnel"

# Update Interface L2TP Client
/interface l2tp-client remove [find comment~"$escName"]
/interface l2tp-client add disabled=no connect-to=$connectTo name="$akunvpn" user="$escName" password="$escPass" comment="$escTunnel"

# Update Netwatch
/tool netwatch remove [find comment="$akunvpn"]
/tool netwatch add interval=1m host=192.168.123.1 comment="$akunvpn"

EOT;

        $message = "✅ PPP Secret <strong>{$nama}</strong> berhasil diperbarui dan NAT diperbaharui.";

        // Simpan ulang data terbaru
        $secretData['name'] = $nama;
        $secretData['password'] = $password;
        $secretData['profile'] = $profile;
        $secretData['remote-address'] = $remoteNew;
        $secretData['comment'] = $comment;       // ← SIMPAN COMMENT BARU
    }

    $API->disconnect();
} catch (Exception $e) {
    $message = "❌ Terjadi kesalahan: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Edit PPP Secret</title>
<link rel="stylesheet" href="premium.css">
</head>
<body>
<div class="container">
<div class="form-container">
<h2>Edit PPP Secret</h2>

<?php if ($message): ?>
<p style="color: <?= (strpos($message, '✅') !== false) ? 'var(--success)' : 'var(--danger)' ?>; font-weight:600; text-align:center;">
<?= $message ?>
</p>
<?php endif; ?>

<?php if (!$generatedScript && $secretData): ?>
<form method="post" autocomplete="off">
  <label>Nama</label>
  <input type="text" name="nama" value="<?= htmlspecialchars($secretData['name']) ?>" required>

  <label>Password</label>
  <input type="text" name="password" value="<?= htmlspecialchars($secretData['password'] ?? '') ?>" required>

  <label>Profile</label>
  <select name="profile" required>
    <?php
    $profiles = ['1-BULAN', '3-BULAN', '5-BULAN', '6-BULAN', '12-BULAN'];
    $currentProfile = $secretData['profile'] ?? '';
    $found = false;

    foreach ($profiles as $p) {
        $selected = ($currentProfile === $p) ? 'selected' : '';
        if ($selected) $found = true;
        echo "<option value=\"$p\" $selected>$p</option>";
    }

    if (!$found && $currentProfile !== '') {
        echo "<option value=\"" . htmlspecialchars($currentProfile) . "\" selected>$currentProfile</option>";
    }
    ?>
  </select>

  <br><br>

  <label>Remote Address</label>
  <input type="text" name="remote" value="<?= htmlspecialchars($secretData['remote-address'] ?? '') ?>" required>

  <label>Comment</label>
  <input type="text" name="comment" value="<?= htmlspecialchars($secretData['comment'] ?? '') ?>">   <!-- INPUT COMMENT -->

  <div style="margin-top:16px; display:flex; gap:10px; flex-wrap:wrap;">
    <button type="submit" name="update">💾 Simpan Perubahan</button>
    <a href="ppp_secret.php" class="backup-button" style="background:#555;">⬅️ Kembali</a>
  </div>
</form>

<?php elseif ($generatedScript): ?>

<div style="display:flex; justify-content:space-between; align-items:center; gap:8px; margin-bottom:8px;">
  <div style="color:var(--text-dim); font-size:13px;">Script Mikrotik hasil pembaruan</div>
  <div>
    <button class="copy-btn" onclick="copyScript()">📋 Salin Script</button>
    <a href="ppp_secret.php" class="backup-button" style="background:#555;">⬅️ Kembali</a>
  </div>
</div>

<textarea id="scriptArea" readonly rows="18"><?= htmlspecialchars($generatedScript) ?></textarea>

<?php endif; ?>

</div>
</div>

<script>
function copyScript() {
    const ta = document.getElementById('scriptArea');
    if (!ta) return;
    ta.select();
    try {
        const ok = document.execCommand('copy');
        if (ok) alert('✅ Script berhasil disalin!');
        else alert('⚠️ Gagal menyalin otomatis — salin manual.');
    } catch (e) {
        alert('⚠️ Browser tidak mendukung copy otomatis.');
    }
}
</script>
</body>
</html>
