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

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

    $id = $_GET['id'] ?? '';
    if ($id === '') throw new Exception("ID tidak ditemukan.");

    $API->write('/ppp/secret/print', false);
    $API->write('?=.id=' . $id);
    $res = $API->parseResponse($API->read(false));
    if (count($res) == 0) throw new Exception("Secret tidak ditemukan.");

    $nama = $res[0]['name'];
    $password = $res[0]['password'] ?? '';
    $remote = $res[0]['remote-address'] ?? '';
    $profile = $res[0]['profile'] ?? '1-BULAN';

    if ($remote === '') throw new Exception("Remote address tidak ditemukan.");

    // ===== Hitung Expire berdasarkan profile =====
    $bulanTambah = match($profile) {
        '1-BULAN' => 1,
        '3-BULAN' => 3,
        '5-BULAN' => 5,
        '6-BULAN' => 6,
        '12-BULAN' => 12,
        default => 1
    };

    $expireDate = date('d-m-Y', strtotime("+$bulanTambah month"));
    $bulanNama = [
        "01" => "Januari", "02" => "Februari", "03" => "Maret",
        "04" => "April", "05" => "Mei", "06" => "Juni",
        "07" => "Juli", "08" => "Agustus", "09" => "September",
        "10" => "Oktober", "11" => "November", "12" => "Desember"
    ];
    [$tgl, $bln, $thn] = explode('-', $expireDate);
    $expireText = "Expire-{$tgl}/" . $bulanNama[$bln] . "/{$thn}";

    // ===== Port NAT =====
    $parts = explode('.', $remote);
    $last = intval(end($parts));
    $port1 = 12000 + $last;
    $port2 = 22000 + $last;
    $port3 = 32000 + $last;

    $connectTo = $_SESSION['ip'] ?? '';
    if (preg_match('/^\[.*\]:\d+$/', $connectTo)) {
        // [IPv6]:port → ambil isi di dalam []
        $connectTo = preg_replace('/^\[(.*)\]:\d+$/', '$1', $connectTo);
    } else {
        // IPv4:port atau hostname:port → hapus :port di akhir
        $connectTo = preg_replace('/:\d+$/', '', $connectTo);
    }

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

    // ===== Script hasil generate =====
    $script = <<<EOT
# VPN Remote $nama ($expireText)

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

# Webfix 80 : {$connectTo}:{$port1}
# Winbox 8291 : {$connectTo}:{$port2}
# API 8728 : {$connectTo}:{$port3}

# 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;

    $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>Script PPP Secret</title>
<link rel="stylesheet" href="premium.css">
</head>
<body>
<div class="container">
<div class="form-container">
<h2>Script PPP Secret</h2>

<?php if ($message): ?>
<p style="color:red; font-weight:600; text-align:center;"><?= $message ?></p>
<?php else: ?>
<textarea id="scriptArea" readonly rows="18"><?= htmlspecialchars($script) ?></textarea>
<div style="margin-top:10px;">
<button onclick="copyScript()">📋 Salin Script</button>
<a href="ppp_secret.php" style="margin-left:10px;">⬅️ Kembali</a>
</div>
<script>
function copyScript() {
    const ta = document.getElementById('scriptArea');
    ta.select();
    try { 
        document.execCommand('copy'); 
        alert('✅ Script berhasil disalin!');
    } catch(e){ 
        alert('⚠️ Gagal salin otomatis, salin manual.');
    }
}
</script>
<?php endif; ?>

</div>
</div>
</body>
</html>
