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

// ===== GANTI SESSION MIKROTIK =====
$dataFile = __DIR__.'/mikrotik_list.json';
$mikrotikList = file_exists($dataFile) ? json_decode(file_get_contents($dataFile), true) : [];

if(isset($_POST['change_mikrotik']) && isset($_POST['mikrotik_index'])){
    $index = $_POST['mikrotik_index'];
    if(isset($mikrotikList[$index])){
        $_SESSION['ip']   = $mikrotikList[$index]['ip'];
        $_SESSION['user'] = $mikrotikList[$index]['user'];
        $_SESSION['pass'] = $mikrotikList[$index]['pass'];
    }
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

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

$API = new RouterosAPI();
$API->debug = false;
$errorMsg = '';
$natList = [];

try {
    $API->connect_timeout = 4;
    $API->read_timeout = 7;

    if ($API->connect($_SESSION['ip'], $_SESSION['user'], $_SESSION['pass'])) {

        // 🔹 Ambil data Firewall NAT
        $API->write('/ip/firewall/nat/print');
        $natList = $API->parseResponse($API->read(false));

        // 🔹 Backup
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['backup'])) {
            $tgl = date('d');
            $bln = date('M');
            $thn = date('Y');
            $blnIndo = str_ireplace(
                ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
                ['januari','februari','maret','april','mei','juni','juli','agustus','september','oktober','november','desember'],
                $bln
            );
            $namaFile = "Backup_NAT_{$tgl}{$blnIndo}{$thn}";

            $API->write('/ip/firewall/nat/export', false);
            $API->write('=file=' . $namaFile);
            $API->read();

            $_SESSION['backup_msg'] = "✅ Backup Firewall NAT berhasil disimpan di Mikrotik dengan nama: {$namaFile}.rsc";
            header('Location: firewall_nat.php');
            exit;
        }

        $API->disconnect();
    } else {
        $errorMsg = "❌ Tidak bisa terhubung ke Mikrotik.";
    }
} catch (Exception $e) {
    $errorMsg = "❌ Terjadi kesalahan: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Firewall NAT - Monitoring</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="icon" href="favicon.png" />
</head>
<body class="dark-mode">
<?php if (isset($_SESSION['backup_msg'])): ?>
<script>alert("<?php echo $_SESSION['backup_msg']; ?>");</script>
<?php unset($_SESSION['backup_msg']); endif; ?>

<div class="container">
    <center>
    <div class="form-container" style="position:relative;">
        <?php
        $networkName = 'Firewall NAT';
        if(!empty($mikrotikList) && isset($_SESSION['ip'])){
            foreach($mikrotikList as $mt){
                if($mt['ip'] === $_SESSION['ip']){
                    $networkName = $mt['name'];
                    break;
                }
            }
        }
        ?>
        <h2><?= htmlspecialchars($networkName) ?> - Firewall NAT</h2>

        <!-- Dropdown Mikrotik -->
        <div style="position:absolute; top:10px; left:10px;">
            <form method="post" style="margin:0;">
                <select name="mikrotik_index" onchange="this.form.submit()"
                        style="padding:5px 10px; border-radius:5px; background:#555; color:#fff; border:none; cursor:pointer;">
                    <?php foreach($mikrotikList as $index => $mikrotik): ?>
                        <option value="<?= $index ?>" <?= ($_SESSION['ip']===$mikrotik['ip'])?'selected':'' ?>>
                            <?= htmlspecialchars($mikrotik['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <input type="hidden" name="change_mikrotik" value="1">
            </form>
        </div>

        <!-- Tombol kembali -->
        <div style="position:absolute; top:10px; right:10px;">
            <a href="dashboard.php"
               style="padding:5px 10px; background:linear-gradient(135deg, #42a5f5, #1e88e5); color:#fff; border-radius:5px; text-decoration:none;">
               <i class="fas fa-arrow-left"></i> Kembali
            </a>
        </div>

        <!-- Tombol tambah -->
        <form action="tambah_nat.php" method="get" style="margin-top:20px;">
            <button type="submit" class="backup-button">
                <i class="fas fa-plus-circle"></i> Tambah Rule NAT
            </button>
        </form>
    </div>
    </center>

    <div class="table-container">
        <h1>Daftar Firewall NAT</h1>
        <small style="float:right; margin-top:-45px; margin-right:2px;">
            <form method="post">
                <button type="submit" name="backup" class="backup-button"
                    onclick="return confirm('Yakin ingin backup seluruh Firewall NAT sekarang?')">
                    <i class="fas fa-download"></i> Backup ke Mikrotik
                </button>
            </form>
        </small>

        <?php if ($errorMsg): ?>
            <p style="color:red;font-weight:bold;"><?= $errorMsg ?></p>
        <?php endif; ?>

        <?php if (!empty($natList)) { ?>
            <table>
                <thead>
                    <tr>
                        <th><center>Edit</center></th>
                        <th>Comment</th>
                        <th>Dst Address</th>
                        <th>Dst Port</th>
                        <th>To Address</th>
                        <th>To Port</th>
                        <th><center>Hapus</center></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($natList as $nat): ?>
                        <tr>
                            <td>
                                <a href="edit_nat.php?id=<?= urlencode($nat['.id']) ?>" style="color:#00fdff;">
                                    <i class="fas fa-edit"></i>
                                </a>
                            </td>
                            <td><?= htmlspecialchars($nat['comment'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($nat['dst-address'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($nat['dst-port'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($nat['to-addresses'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($nat['to-ports'] ?? '-') ?></td>
                            <td>
                                <a href="hapus_nat.php?id=<?= urlencode($nat['.id']) ?>"
                                   onclick="return confirm('Yakin ingin hapus rule NAT ini?')"
                                   style="color:#ff6b6b;">
                                   <i class="fas fa-trash-alt"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php } else if (!$errorMsg) { ?>
            <p class="no-data">Tidak ada rule NAT ditemukan.</p>
        <?php } ?>
    </div>
</div>
</body>
</html>
