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

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

// ===== BACA FILE MIKROTIK =====
$dataFile = __DIR__.'/mikrotik_list.json';
$mikrotikList = [];
if(file_exists($dataFile)){
    $mikrotikList = json_decode(file_get_contents($dataFile), true) ?? [];
}

$errorMsg = "";

// ===== GANTI MIKROTIK =====
if(isset($_POST['change_mikrotik']) && isset($_POST['mikrotik_index'])){
    $index = intval($_POST['mikrotik_index']);
    if(isset($mikrotikList[$index])){
        $new = $mikrotikList[$index];

        // ===== CEK HOST CEPAT =====
        $host = $new['ip'];
        $port = 8728; // port API MikroTik
        $timeoutSec = 3; // timeout 1 detik
        $connection = @fsockopen($host, $port, $errno, $errstr, $timeoutSec);

        if($connection){
            fclose($connection);
            // lanjut koneksi API
            $API = new RouterosAPI();
            $API->debug = false;
            $API->timeout = 3; // timeout singkat
            if($API->connect($new['ip'], $new['user'], $new['pass'])){
                $_SESSION['ip']   = $new['ip'];
                $_SESSION['user'] = $new['user'];
                $_SESSION['pass'] = $new['pass'];
                $API->disconnect();
                header("Location: ".$_SERVER['PHP_SELF']);
                exit;
            } else {
                $errorMsg = "❌ Gagal terhubung ke MikroTik (API error): ".$new['name']." (".$new['ip'].")";
            }
        } else {
            $errorMsg = "❌ Gagal terhubung ke MikroTik (host down/port 8728): ".$new['name']." (".$new['ip'].")";
        }
    }
}

// ===== TAMPILKAN NAMA SESUAI SESSION IP =====
$mikrotikName = $_SESSION['ip']; // default IP
foreach($mikrotikList as $mt){
    if($mt['ip'] === $_SESSION['ip']){
        $mikrotikName = $mt['name'];
        break;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <title>Dashboard - <?= htmlspecialchars($mikrotikName) ?></title>
  <link rel="icon" href="favicon.png" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body { font-family: 'Orbitron', sans-serif; margin:0; padding:0; background:linear-gradient(135deg,#e0f7fa,#e1f5fe); color:#212121; display:flex; flex-direction:column; min-height:100vh; }
    .topbar { display:flex; justify-content:space-between; align-items:center; background:#0d47a1; color:#fff; padding:10px 20px; box-shadow:0 2px 6px rgba(0,0,0,0.2); }
    .topbar h2 { margin:0; font-size:12px; font-weight:600; }
    .topbar .actions { display:flex; align-items:center; gap:10px; }
    .topbar select { padding:6px 8px; border-radius:6px; border:1px solid #ccc; font-size:10px; }
    .logout-btn { padding:6px 12px; background:#f44336; color:#fff; border-radius:6px; text-decoration:none; font-size:10px; }
    .logout-btn:hover { background:#d32f2f; }

    .menu {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
        gap: 12px;
        width: 90%;
        max-width: 700px;
        margin: 25px auto 35px auto;
    }

    .menu a {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: #42a5f5;
        color: white;
        text-decoration: none;
        padding: 12px 8px;
        border-radius: 8px;
        box-shadow: 0 4px 10px rgba(0,0,0,0.15);
        font-size: 14px;
        text-align: center;
        transition: transform 0.2s, box-shadow 0.2s, background 0.3s;
    }

    .menu a span {
        font-size: 24px;
        margin-bottom: 6px;
        display: block;
    }

    .menu a:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.2);
        background: #1e88e5;
    }

    @media screen and (max-width:480px) {
        .menu a {
            padding: 10px 6px;
            font-size: 15px;
        }
        .menu a span {
            font-size: 50px;
        }
    }
  </style>
</head>
<body>

  <div class="topbar">
    <h2><?= htmlspecialchars($mikrotikName) ?></h2>
    <div class="actions">
      <form method="post" style="display:inline;">
        <select name="mikrotik_index" onchange="this.form.submit()">
          <?php foreach($mikrotikList as $i => $mt): ?>
            <option value="<?= $i ?>" <?= ($_SESSION['ip']===$mt['ip'])?'selected':'' ?>>
              <?= htmlspecialchars($mt['name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
        <input type="hidden" name="change_mikrotik" value="1">
      </form>
      <a href="index.php" class="logout-btn">Logout</a>
    </div>
  </div>

<?php if($errorMsg): ?>
<script>
if (confirm("<?= addslashes($errorMsg) ?>\nKlik OK untuk kembali ke halaman login.")) {
    window.location.href = 'index.php';
}
</script>
<?php endif; ?>


  <div class="menu">
    <a href="ppp_secret.php"><span>📋</span>User List</a>
    <a href="firewall_nat.php"><span>🔍</span>Pencarian User</a>

  </div>

</body>
</html>
