<?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 = '';
$data = [];

$netwatchDomain = 'apmon.id';

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

    // Hapus secret jika diminta
    if (isset($_GET['hapus'])) {
        $id = $_GET['hapus'];
        $API->write('/ppp/secret/print', false);
        $API->write('?=.id=' . $id);
        $secret = $API->parseResponse($API->read(false));

        if (count($secret) > 0) {
            $nama = $secret[0]['name'];
            $remoteAddr = $secret[0]['remote-address'] ?? '';

            // Hapus PPP secret
            $API->comm('/ppp/secret/remove', ['.id'=>$id]);

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

            // Hapus Netwatch
            $allNetwatch = $API->comm('/tool/netwatch/print');
            $netwatchCommentOld = $remoteAddr ? 'tunnel-gateway-'.$remoteAddr : '';
            $netwatchCommentNew = $netwatchDomain.' - '.$nama;
            foreach ($allNetwatch as $nw) {
                if (!isset($nw['comment'])) continue;
                $c = $nw['comment'];
                if (($remoteAddr && $c === $netwatchCommentOld) || $c === $netwatchCommentNew) {
                    $API->comm('/tool/netwatch/remove', ['.id'=>$nw['.id']]);
                }
            }

            // Hapus L2TP interface
            if ($remoteAddr) {
                $ifs = $API->comm('/interface/print', ['?comment'=>'tunnel-'.$remoteAddr]);
                foreach ($ifs as $ifc) $API->comm('/interface/remove', ['.id'=>$ifc['.id']]);
                // Hapus scheduler
                $schedules = $API->comm('/system/scheduler/print', ['?name'=>'tunnel-scheduler-'.$remoteAddr]);
                foreach ($schedules as $s) $API->comm('/system/scheduler/remove', ['.id'=>$s['.id']]);
            }

            $message = "✅ PPP Secret <strong>{$nama}</strong> dan resource terkait berhasil dihapus.";
        } else {
            $message = "❌ Data tidak ditemukan.";
        }
    }

    // Ambil semua PPP Secret
    $API->write('/ppp/secret/print');
    $data = $API->parseResponse($API->read(false));

    $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>VPN Remote MIKROTIK</title>
<link rel="stylesheet" href="premium.css">
</head>
<body>
<div class="container">
<div class="form-container">
<h2>VPN Remote MIKROTIK</h2>
<?php if($message): ?>
<p style="color: <?= (strpos($message,'✅')!==false)?'var(--success)':'var(--danger)' ?>; text-align:center; font-weight:600;"><?= $message ?></p>
<?php endif; ?>

<div style="display:flex;justify-content:space-between;gap:8px;margin-bottom:10px;">
<a href="index.php" class="backup-button" style="width:80px;background:#fff;">⬅️ Kembali</a>
<input type="text" id="searchSecret" placeholder="🔍 Cari Secret..." style="width:120px; padding:4px 8px; border-radius:6px; border:1px solid #ccd0d5; font-size:13px;">

<a href="tambah_ppp.php" class="backup-button" style="background:var(--primary);">➕ Tambah</a>


</div>

<table id="pppTable">
<thead>
<tr><th>Nama</th><th>Remote IP</th><th style="text-align:center;">Aksi</th></tr>
</thead>
<tbody>
<?php if(empty($data)): ?>
<tr><td colspan="3" style="text-align:center; color:var(--text-dim)">Tidak ada data PPP Secret.</td></tr>
<?php else: foreach($data as $s): ?>
<tr>
<td><?= htmlspecialchars($s['name']) ?></td>
<td><?= htmlspecialchars($s['remote-address'] ?? '-') ?></td>
<td style="text-align:center;white-space:nowrap;">
<a class="action-btn" href="edit_ppp.php?id=<?= urlencode($s['.id']) ?>">✏️ Edit</a>
<a class="action-btn delete-btn" href="?hapus=<?= urlencode($s['.id']) ?>" onclick="return confirm('Yakin ingin menghapus <?= htmlspecialchars($s['name']) ?>?')">🗑️ Hapus</a>
<a class="action-btn" href="generate_script.php?id=<?= urlencode($s['.id']) ?>">📜 Script</a>
</td>
</tr>
<?php endforeach; endif; ?>
</tbody>
</table>
<script>
// Cari secret secara real-time
document.getElementById('searchSecret').addEventListener('input', function(){
    const filter = this.value.toLowerCase();
    const rows = document.querySelectorAll('#pppTable tbody tr');
    rows.forEach(row => {
        const nameCell = row.cells[0].textContent.toLowerCase();
        const ipCell = row.cells[1].textContent.toLowerCase();
        if(nameCell.includes(filter) || ipCell.includes(filter)){
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
});
</script>
</div>
</div>
</body>
</html>
