<?php
session_start();

// ===== LOGOUT =====
if(isset($_POST['logout'])){
    session_destroy();
    header("Location:index.php");
    exit;
}

// ===== ADMIN DEFAULT =====
$adminFile = __DIR__ . '/admin.json';
if (!file_exists($adminFile)) {
    file_put_contents($adminFile, json_encode(['user'=>'APMON','pass'=>'1234']));
}
$adminData = json_decode(file_get_contents($adminFile), true);

// PROSES LOGIN
$error = '';
if(isset($_POST['login'])){
    $inputUser = $_POST['username'] ?? '';
    $inputPass = $_POST['password'] ?? '';
    if($inputUser === $adminData['user'] && $inputPass === $adminData['pass']){
        $_SESSION['loggedin'] = true;
    } else {
        $error = 'Username atau password salah!';
    }
}

if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true):
?>


<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Netwatch AP Monitoring</title>
<link rel="icon" href="favicon.png" />
<link rel="stylesheet" href="admin.css">
</head>
<body class="dashboard">
<main>
    <div class="panel" style="max-width:360px;margin:auto;">
        <h3>🔐 Admin Login</h3>
        <?php if($error) echo "<p class='msg' style='color:#ff5555;'>$error</p>"; ?>
        <form method="post" style="display:flex;flex-direction:column;gap:15px;">
            <input type="text" name="username" placeholder="👤 Username" required>
            <input type="password" name="password" placeholder="🔑 Password" required>
            <div class="login">
                <center><button type="submit" name="login" style="width:250px;"><i class="fas fa-sign-in-alt"></i> Login</button></center>
            </div>
        </form>
    </div>
</main>
</body>
</html>
<?php exit; endif; ?>

<?php
// ===== MIKROTIK DATA =====
$dataFile = __DIR__.'/mikrotik_list.json';
if(!file_exists($dataFile)) file_put_contents($dataFile,json_encode([]));
$mikrotikList = json_decode(file_get_contents($dataFile),true);

// Tambah Mikrotik
if(isset($_POST['add_mikrotik'])){
    $mikrotikList[] = [
        'name'=>$_POST['name'],
        'ip'=>$_POST['ip'],
        'user'=>$_POST['user'],
        'pass'=>$_POST['pass']
    ];
    file_put_contents($dataFile,json_encode($mikrotikList,JSON_PRETTY_PRINT));
    header("Location:index.php");
    exit;
}

// Edit admin
$adminMsg='';
if(isset($_POST['edit_admin'])){
    $adminData['user']=$_POST['new_user']??$adminData['user'];
    $adminData['pass']=$_POST['new_pass']??$adminData['pass'];
    file_put_contents($adminFile,json_encode($adminData,JSON_PRETTY_PRINT));
    $adminMsg="✅ Pengaturan berhasil disimpan!";
}

// ===== SETTINGS (auto-reload) =====
$settingsFile = __DIR__ . '/settings.json';
if (!file_exists($settingsFile)) {
    file_put_contents($settingsFile, json_encode(['reload_minutes' => 0], JSON_PRETTY_PRINT));
}
$settings = json_decode(file_get_contents($settingsFile), true);

// Simpan pilihan reload dari index.php
if (isset($_POST['set_reload'])) {
    $allowed = [0,1,5,10,20,30,40,50];
    $val = intval($_POST['reload_minutes'] ?? 0);
    if (!in_array($val, $allowed)) $val = 0;
    $settings['reload_minutes'] = $val;
    file_put_contents($settingsFile, json_encode($settings, JSON_PRETTY_PRINT));
    header("Location:index.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Monitoring AP</title>
<link rel="icon" href="favicon.png" />
<link rel="stylesheet" href="admin.css">
</head>
<body class="dashboard">


<header>Monitoring AP</header>
<main>

<?php
if(isset($_GET['action']) && $_GET['action']==='add'):
?>
<div class="panel">
<h3>➕ Tambah Mikrotik</h3>
<form method="post" style="display:flex;flex-direction:column;gap:15px;">
<input type="text" name="name" placeholder="🌐 Nama Mikrotik" required>
<input type="text" name="ip" placeholder="🔗 IP / Host VPN API" required>
<input type="text" name="user" placeholder="👤 Username" required>
<input type="password" name="pass" placeholder="🔑 Password" required>
<div class="actions">
    <button type="submit" name="add_mikrotik"><i class="fas fa-plus"></i> Tambah</button>
    <a class="batal" href="index.php"><i class="fas fa-times"></i> Batal</a>
</div>
</form>
</div>

<?php else: ?>
<?php
if(isset($_SESSION['toast_error'])): ?>
<div class="toast"><?= htmlspecialchars($_SESSION['toast_error']) ?></div>
<style>
.toast {
    background-color: #f44336;
    color: white;
    padding: 10px 15px;
    border-radius: 5px;
    margin-bottom: 15px; /* beri jarak dengan daftar */
    font-size: 0.95em;
    animation: fadein 0.5s, fadeout 0.5s 4s; /* muncul & hilang otomatis */
}
@keyframes fadein {
    from {opacity: 0; transform: translateY(-10px);}
    to {opacity: 1; transform: translateY(0);}
}
@keyframes fadeout {
    from {opacity: 1;}
    to {opacity: 0;}
}
</style>
<script>
setTimeout(() => {
    const toast = document.querySelector('.toast');
    if(toast) toast.remove();
}, 4500);
</script>
<?php
unset($_SESSION['toast_error']); // hapus setelah ditampilkan
endif;
?>

<!-- Panel Daftar Mikrotik -->
<div class="panel">



    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
        <h3>📡 MikroTik</h3>
        <div style="display:flex; gap:10px;">
            <!-- Tombol Add Mikrotik -->
            <form method="get" action="" style="margin:0;">
                <button type="submit" name="action" value="add"
                    style="padding:5px 12px; font-size:0.9em; border-radius:6px; cursor:pointer; background:#26a69a; color:white; border:none; display:flex; align-items:center;">
                    <i class="fas fa-plus-circle" style="margin-right:5px;"></i> Add
                </button>
            </form>

            <!-- Tombol Logout -->
            <form method="post" style="margin:0;">
                <button type="submit" name="logout"
                    style="padding:5px 12px; font-size:0.9em; border-radius:6px; cursor:pointer; background:#e53935; color:white; border:none; display:flex; align-items:center;">
                    Logout
                </button>
            </form>
        </div>
    </div>

<?php if(!empty($mikrotikList)): ?>
    <?php foreach($mikrotikList as $index=>$mt): ?>
    <div class="card">
        <div class="info"><?= htmlspecialchars($mt['name']) ?></div>
        <div class="actions">
            <a class="connect" href="connect.php?id=<?= $index ?>"><i class="fas fa-plug"></i> Buka</a>
            <a class="edit" href="edit.php?id=<?= $index ?>"><i class="fas fa-pen"></i> Edit</a>
            <a class="delete" href="delete.php?id=<?= $index ?>" onclick="return confirm('Hapus Mikrotik ini?')"><i class="fas fa-trash"></i> Hapus</a>
        </div>
    </div>
    <?php endforeach; ?>
<?php else: ?>
<p style="color:#00796b;">⚠️ Belum ada data Mikrotik.</p>
<?php endif; ?>
</div>

<!-- Panel Auto-reload (letak setelah daftar Mikrotik) -->
<div class="panel">
    <h3>⏱️ Auto-reload Peta</h3>
    <form method="post" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
        <label for="reload_minutes" style="min-width:90px;">Reload tiap</label>
        <select name="reload_minutes" id="reload_minutes" style="padding:6px;border-radius:6px;">
            <?php
            $options = [
                0 => 'Disabled',
                1 => '1 menit',
                5 => '5 menit',
                10 => '10 menit',
                20 => '20 menit',
                30 => '30 menit',
                40 => '40 menit',
                50 => '50 menit'
            ];
            foreach ($options as $val => $label):
            ?>
            <option value="<?= $val ?>" <?= (isset($settings['reload_minutes']) && intval($settings['reload_minutes']) === $val) ? 'selected' : '' ?>>
                <?= $label ?>
            </option>
            <?php endforeach; ?>
        </select>
        <button type="submit" name="set_reload" style="padding:6px 12px;border-radius:6px;background:#26a69a;color:#fff;border:none;cursor:pointer;">
            Simpan
        </button>
    </form>
    <p style="font-size:0.9em;color:#555;margin-top:8px;">Pengaturan ini akan diterapkan pada halaman Monitoring. Pilih 0/Disabled untuk mematikan auto-reload.</p>
</div>

<!-- Panel Admin Settings -->
<div class="panel" >
    <div style="display:flex; justify-content:space-between; align-items:center;">
        <h3>⚙️ Admin Settings</h3>
        <!-- Tombol toggle di dalam panel -->
        <button id="toggle-admin" style="padding:5px 10px; font-size:0.9em; border-radius:6px; cursor:pointer; background:#26a69a; color:white; border:none;">
            Show/Hide
        </button>
    </div>

    <!-- Konten form tersembunyi awalnya -->
    <div id="admin-panel" style="display:none; margin-top:15px;">
        <?php if($adminMsg) echo "<p class='msg'>$adminMsg</p>"; ?>
        <form method="post" style="display:flex;flex-direction:column;gap:15px;">
            <input type="text" name="new_user" placeholder="Username" value="<?=htmlspecialchars($adminData['user'])?>" required>
            <input type="password" name="new_pass" placeholder="Password" value="<?=htmlspecialchars($adminData['pass'])?>" required>
            <button type="submit" name="edit_admin"><i class="fas fa-save"></i> Simpan</button>
        </form>
    </div>
</div>

<?php endif; ?>


</main>
</body>
<script>
// Toggle panel admin
document.addEventListener('DOMContentLoaded', () => {
    const toggleBtn = document.getElementById('toggle-admin');
    const adminPanel = document.getElementById('admin-panel');

    toggleBtn.addEventListener('click', () => {
        if(adminPanel.style.display === "none"){
            adminPanel.style.display = "block";
        } else {
            adminPanel.style.display = "none";
        }
    });
});
</script>
</html>