<?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 = '';
$nextIP = '';

try {
    // konek untuk membaca daftar yang sudah ada
    if (!$API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {
        throw new Exception("Gagal terhubung ke Mikrotik.");
    }

    // ambil semua PPP Secret
    $API->write('/ppp/secret/print');
    $secrets = $API->parseResponse($API->read(false));
    $usedIPs = [];
    foreach ($secrets as $s) {
        if (!empty($s['remote-address'])) {
            $usedIPs[] = trim($s['remote-address']);
        }
    }

    // cari next IP (2..254) yang belum terpakai
    for ($i = 2; $i <= 254; $i++) {
        $candidate = "192.168.123.$i";
        if (!in_array($candidate, $usedIPs)) {
            $nextIP = $candidate;
            break;
        }
    }

    // proses submit
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['simpan'])) {
        $nama = trim($_POST['nama'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $profile = trim($_POST['profile'] ?? '');
        $remote = trim($_POST['remote'] ?? $nextIP);

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

        // Cek lagi apakah remote sudah ada
        if (in_array($remote, $usedIPs)) {
            throw new Exception("Remote address {$remote} sudah digunakan. Silakan coba lagi.");
        }

        // Tambah PPP Secret
        $API->comm('/ppp/secret/add', [
            'name' => $nama,
            'password' => $password,
            'profile' => $profile,
            'local-address' => '192.168.123.1',
            'remote-address' => $remote,
            'service' => 'l2tp'
        ]);

        // =========================
        // 🔧 Penambahan NAT otomatis
        // =========================
        $dstAddress = "10.141.92.173";
        $parts = explode('.', $remote);
        $last = intval(end($parts));

        $port1 = 12000 + $last;
        $port2 = 22000 + $last;
        $port3 = 32000 + $last;

        $natRules = [
            ['desc' => 'WEB',    'dst-port' => $port1, 'to-ports' => 80],
            ['desc' => 'WINBOX', 'dst-port' => $port2, 'to-ports' => 8291],
            ['desc' => 'API',    'dst-port' => $port3, 'to-ports' => 8728],
        ];

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

        // === Tambahan: Hitung tanggal 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);
            // Ubah ke format nama bulan Indonesia
            $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;

        // siapkan script pelanggan
        $connectTo = $_SESSION['ip'];
        if (strpos($connectTo, ':') !== false) {
            $connectTo = explode(':', $connectTo)[0];
        }

        $escName = addslashes($nama);
        $escPass = addslashes($password);
        $escTunnel = addslashes("VPN remote - {$nama} ({$expLabel})");
        $akunvpn = "VPN remote - {$nama}";

        $portNote1 = 12000 + $last;
        $portNote2 = 22000 + $last;
        $portNote3 = 32000 + $last;

        $generatedScript = <<<EOT
# VPN Remote $nama ($expLabel)

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

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

# Tambah 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"

# 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> dengan profile <strong>{$profile}</strong> berhasil dibuat.";
    }

    $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>Tambah PPP Secret</title>
<link rel="stylesheet" href="premium.css">
</head>
<body>
  <div class="container">
    <div class="form-container">
      <h2>Tambah 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): ?>
        <form method="post" autocomplete="off">
          <label>Nama</label>
          <input type="text" name="nama" placeholder="Contoh: client_10" required>

          <label>Password</label>
          <input type="text" name="password" placeholder="Masukkan password" required>

          <label>Profile</label>
          <select name="profile" required>
            <option value="1-BULAN">1-BULAN</option>
            <option value="3-BULAN">3-BULAN</option>
            <option value="5-BULAN">5-BULAN</option>
            <option value="6-BULAN">6-BULAN</option>
            <option value="12-BULAN">12-BULAN</option>
          </select>
<br><br>
          <label>Local Address</label>
          <input type="text" value="192.168.123.1" disabled>

          <label>Remote Address</label>
          <input type="text" name="remote" value="<?= htmlspecialchars($nextIP) ?>" readonly>

          <div style="margin-top:16px; display:flex; gap:10px; flex-wrap:wrap;">
            <button type="submit" name="simpan">💾 Simpan</button>
            <a href="ppp_secret.php" class="backup-button" style="background:#555;">❌ Batal</a>
          </div>
        </form>
      <?php else: ?>
        <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 pelanggan & catatan</div>
          <div>
            <button class="copy-btn" onclick="copyScript()">📋 Salin Script</button>
            <a href="tambah_ppp.php" class="backup-button" style="background:#333;">➕ Tambah Lagi</a>
            <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 ke clipboard!');
        } else {
            alert('⚠️ Gagal menyalin otomatis — silakan blok & salin manual.');
        }
    } catch (e) {
        alert('⚠️ Browser tidak mendukung copy otomatis — silakan blok & salin manual.');
    }
}
</script>
</body>
</html>
