<?php
session_start();

// ===== FILE PATHS =====
$adminFile = __DIR__ . '/admin.json';
$expireFile = __DIR__ . '/expire.json';

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

// ===== ADMIN DEFAULT =====
if (!file_exists($adminFile)) {
    file_put_contents($adminFile, json_encode(['user' => 'MONSEL', 'pass' => '1234'], JSON_PRETTY_PRINT), LOCK_EX);
}
$adminData = json_decode(file_get_contents($adminFile), true);
if (!is_array($adminData)) $adminData = ['user' => 'MONSEL', 'pass' => '1234'];

// ===== EXPIRE: read safely from expire.json (if present) =====
$expire_at = 0;
$expire_exists = file_exists($expireFile);
if ($expire_exists) {
    $raw = file_get_contents($expireFile);
    $ed = json_decode($raw, true);
    if (is_array($ed) && isset($ed['expires_at'])) {
        $expire_at = intval($ed['expires_at']);
    } else {
        error_log("[expire.json] invalid content or missing expires_at");
        $expire_at = 0;
    }
}

// PROSES LOGIN
$error = '';
if (isset($_POST['login'])) {
    $inputUser = $_POST['username'] ?? '';
    $inputPass = $_POST['password'] ?? '';
    if ($inputUser === ($adminData['user'] ?? '') && $inputPass === ($adminData['pass'] ?? '')) {
        $_SESSION['loggedin'] = true;
        $_SESSION['subscription_expires_at'] = $expire_at;
    } 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>MONSEL - Login</title>
<link rel="icon" href="favicon.png" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}

.login-container {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    padding: 40px;
    width: 100%;
    max-width: 420px;
    animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.login-header {
    text-align: center;
    margin-bottom: 35px;
}

.login-logo {
    font-size: 3em;
    margin-bottom: 15px;
}

.login-header h1 {
    font-size: 28px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 700;
}

.login-header p {
    color: #666;
    font-size: 14px;
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    color: #333;
    font-weight: 500;
    font-size: 14px;
}

.form-group input {
    width: 100%;
    padding: 14px 16px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: #f8f9fa;
}

.form-group input:focus {
    outline: none;
    border-color: #667eea;
    background: white;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group input::placeholder {
    color: #999;
}

.error-message {
    background: #fee;
    border: 1px solid #fcc;
    color: #c33;
    padding: 12px 14px;
    border-radius: 8px;
    margin-bottom: 20px;
    font-size: 14px;
    animation: shake 0.5s ease;
}

@keyframes shake {
    0%, 100% { transform: translateX(0); }
    25% { transform: translateX(-5px); }
    75% { transform: translateX(5px); }
}

.login-btn {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

.login-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
}

.login-btn:active {
    transform: translateY(0);
}

.login-footer {
    text-align: center;
    margin-top: 20px;
    color: #999;
    font-size: 12px;
}
</style>
</head>
<body>
<div class="login-container">
    <div class="login-header">
        <div class="login-logo"></div>

        <img src="favicon.png" width="160" height="160">
    </div>

    <?php if ($error): ?>
        <div class="error-message">
            <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
        </div>
    <?php endif; ?>

    <form method="post" style="display:flex;flex-direction:column;gap:15px;">
        <div class="form-group">
            <label for="username"><i class="fas fa-user"></i> Username</label>
            <input type="text" id="username" name="username" placeholder="Masukkan username" required autofocus>
        </div>
        <div class="form-group">
            <label for="password"><i class="fas fa-lock"></i> Password</label>
            <input type="password" id="password" name="password" placeholder="Masukkan password" required>
        </div>
        <button type="submit" name="login" class="login-btn">
            <i class="fas fa-sign-in-alt"></i> Login
        </button>
    </form>

    <div class="login-footer">
        © 2026 MONITORING VCR
    </div>
</div>
</body>
</html>
<?php exit; endif; ?>

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

// Tambah Mikrotik
if (isset($_POST['add_mikrotik'])) {
    $mikrotikList[] = [
        'name'      => ($_POST['name'] ?? ''),
        'ip'        => ($_POST['ip'] ?? ''),
        'user'      => ($_POST['user'] ?? ''),
        'pass'      => ($_POST['pass'] ?? ''),
        'bot_token' => trim($_POST['bot_token'] ?? ''),
        'chat_id'   => trim($_POST['chat_id'] ?? '')
    ];
    file_put_contents($dataFile, json_encode($mikrotikList, JSON_PRETTY_PRINT), LOCK_EX);
    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), LOCK_EX);

    if (!$expire_exists && !empty($_POST['expire_date'])) {
        $d = $_POST['expire_date'];
        $ts = strtotime($d . ' 23:59:59');
        if ($ts !== false) {
            $expireData = ['expires_at' => $ts];
            $written = @file_put_contents($expireFile, json_encode($expireData, JSON_PRETTY_PRINT), LOCK_EX);
            if ($written === false) {
                error_log("Failed to write expire.json");
                $adminMsg = "⚠️ Pengaturan disimpan, tapi gagal membuat expire.json.";
            } else {
                $expire_at = $ts;
                $expire_exists = true;
                if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
                    $_SESSION['subscription_expires_at'] = $expire_at;
                }
                $adminMsg = "✅ Pengaturan dan tanggal kadaluarsa berhasil disimpan!";
            }
        } else {
            $adminMsg = "⚠️ Format tanggal tidak valid.";
        }
    } else {
        if ($adminMsg === '') $adminMsg = "✅ Pengaturan berhasil disimpan!";
    }
}

if (isset($_SESSION['loggedin']) && (!isset($_SESSION['subscription_expires_at']) || $_SESSION['subscription_expires_at'] === null)) {
    $_SESSION['subscription_expires_at'] = $expire_at;
}

$subscription_expires_at = isset($_SESSION['subscription_expires_at']) ? intval($_SESSION['subscription_expires_at']) : 0;
$expired = ($subscription_expires_at > 0) && (time() > $subscription_expires_at);
$remaining = ($subscription_expires_at > 0) ? max(0, $subscription_expires_at - time()) : 0;
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MONSEL</title>
<link rel="icon" href="favicon.png" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    min-height: 100vh;
    padding: 20px;
}

/* Header */
header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 25px 30px;
    border-radius: 15px;
    margin-bottom: 30px;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 15px;
}

.header-logo {
    font-size: 2em;
}

.header-info h1 {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 5px;
}

.header-info p {
    font-size: 13px;
    opacity: 0.9;
}

.header-right {
    text-align: right;
}

.session-info {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.session-label {
    font-size: 12px;
    opacity: 0.9;
}

.session-time {
    font-size: 18px;
    font-weight: 700;
}

.session-expired {
    color: #ffcdd2;
    font-weight: 600;
}

/* Main Container */
main {
    max-width: 1200px;
    margin: 0 auto;
}

/* Cards & Panels */
.panel {
    background: white;
    border-radius: 15px;
    padding: 30px;
    margin-bottom: 25px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.panel:hover {
    box-shadow: 0 10px 35px rgba(0, 0, 0, 0.12);
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 15px;
}

.panel-title {
    font-size: 24px;
    font-weight: 700;
    color: #333;
    display: flex;
    align-items: center;
    gap: 10px;
}

.panel-actions {
    display: flex;
    gap: 10px;
}

/* Buttons */
.btn {
    padding: 10px 18px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    text-decoration:none;
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}

.btn-danger {
    background: #f44336;
    color: white;
}

.btn-danger:hover {
    background: #e53935;
    transform: translateY(-2px);
}

.btn-secondary {
    background: #26a69a;
    color: white;
}

.btn-secondary:hover {
    background: #1e8e7a;
    transform: translateY(-2px);
}

.btn-warning {
    background: #ff9800;
    color: white;
}

.btn-warning:hover {
    background: #f57c00;
}

/* MikroTik Cards */
.mikrotik-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
}

.mikrotik-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 20px;
    color: white;
    transition: all 0.3s ease;
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}

.mikrotik-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 30px rgba(102, 126, 234, 0.4);
}

.mikrotik-card-title {
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.mikrotik-card-info {
    font-size: 13px;
    opacity: 0.9;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.mikrotik-card-actions {
    display: flex;
    gap: 8px;
    margin-top: 15px;
    flex-wrap: wrap;
}

.card-btn {
    flex: 1;
    min-width: 70px;
    padding: 8px 12px;
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    border-radius: 6px;
    cursor: pointer;
    font-size: 12px;
    font-weight: 600;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    text-decoration: none;
}

.card-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.5);
}

.empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #999;
}

.empty-state-icon {
    font-size: 48px;
    margin-bottom: 15px;
    opacity: 0.5;
}

/* Form Styles */
.form-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-group label {
    margin-bottom: 8px;
    font-weight: 600;
    color: #333;
    font-size: 14px;
}

.form-group input,
.form-group textarea {
    padding: 12px 14px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.3s ease;
    font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus {
    outline: none;
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* Messages */
.msg {
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 10px;
}

.msg.success {
    background: #e8f5e9;
    color: #2e7d32;
    border: 1px solid #81c784;
}

.msg.error {
    background: #ffebee;
    color: #c62828;
    border: 1px solid #ef5350;
}

.msg.warning {
    background: #fff3e0;
    color: #e65100;
    border: 1px solid #ffb74d;
}

/* Admin Settings */
.settings-toggle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.settings-toggle .btn {
    margin: 0;
}

.settings-content {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

.expire-display {
    background: linear-gradient(135deg, #ffc107 0%, #ff9800 100%);
    color: white;
    padding: 15px;
    border-radius: 8px;
    font-weight: 600;
    text-align: center;
}

/* Expired Page */
.expired-container {
    background: white;
    border-radius: 15px;
    padding: 50px 30px;
    text-align: center;
    max-width: 600px;
    margin: 50px auto;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.expired-icon {
    font-size: 60px;
    margin-bottom: 20px;
    color: #f44336;
}

.expired-title {
    font-size: 32px;
    font-weight: 700;
    color: #333;
    margin-bottom: 15px;
}

.expired-message {
    font-size: 16px;
    color: #666;
    margin-bottom: 30px;
    line-height: 1.6;
}

.expired-actions {
    display: flex;
    gap: 15px;
    justify-content: center;
    flex-wrap: wrap;
}

.expired-actions .btn {
    padding: 12px 25px;
}

/* Responsive */
@media (max-width: 768px) {
    header {
        flex-direction: column;
        text-align: center;
    }

    .header-right {
        text-align: center;
    }

    .mikrotik-grid {
        grid-template-columns: 1fr;
    }

    .panel {
        padding: 20px;
    }

    .panel-title {
        font-size: 20px;
    }
}

/* Toast Notifications */
.toast {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: #323232;
    color: white;
    padding: 16px 20px;
    border-radius: 8px;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
    font-size: 14px;
    z-index: 1000;
    animation: slideIn 0.3s ease, slideOut 0.3s ease 4.7s;
}

@keyframes slideIn {
    from {
        transform: translateX(400px);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideOut {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(400px);
        opacity: 0;
    }
}
</style>
</head>
<body>

<header>
    <div class="header-left">
        <div class="header-logo">📡</div>
        <div class="header-info">
            <h1>MONSEL</h1>
            <p>MikroTik Management System</p>
        </div>
    </div>
    <div class="header-right">
        <div class="session-info">
            <div class="session-label">Sesi berakhir dalam:</div>
            <div id="subscription-top" class="session-time" <?= $remaining > 0 ? 'data-seconds="'.$remaining.'"' : '' ?> style="<?= $remaining > 0 ? '' : 'color:#ffcdd2;' ?>">
                <?= $remaining > 0 ? gmdate("H:i:s", $remaining) : ($subscription_expires_at > 0 ? '00:00:00' : 'Belum diatur') ?>
            </div>
        </div>
    </div>
</header>

<main>
<?php if (isset($_GET['action']) && $_GET['action'] === 'add'): ?>

<div class="panel">
    <h2 class="panel-title"><i class="fas fa-plus-circle"></i> Tambah MikroTik Baru</h2>

    <form method="post" style="margin-top:25px;">
        <div class="form-grid">
            <div class="form-group">
                <label for="name"><i class="fas fa-network-wired"></i> Nama MikroTik</label>
                <input type="text" id="name" name="name" placeholder="Cth: MikroTik Utama" required>
            </div>
            <div class="form-group">
                <label for="ip"><i class="fas fa-globe"></i> IP / Host VPN API</label>
                <input type="text" id="ip" name="ip" placeholder="Cth: 192.168.1.1 atau api.example.com" required>
            </div>
            <div class="form-group">
                <label for="user"><i class="fas fa-user"></i> Username</label>
                <input type="text" id="user" name="user" placeholder="Username MikroTik" required>
            </div>
            <div class="form-group">
                <label for="pass"><i class="fas fa-lock"></i> Password</label>
                <input type="password" id="pass" name="pass" placeholder="Password MikroTik" required>
            </div>
            <div class="form-group">
                <label for="bot_token"><i class="fas fa-robot"></i> Bot Token Telegram (Opsional)</label>
                <input type="text" id="bot_token" name="bot_token" placeholder="Bot token dari @BotFather">
            </div>
            <div class="form-group">
                <label for="chat_id"><i class="fas fa-comments"></i> Chat ID Telegram (Opsional)</label>
                <input type="text" id="chat_id" name="chat_id" placeholder="ID penerima notifikasi">
            </div>
        </div>

        <div class="panel-actions">
            <button type="submit" name="add_mikrotik" class="btn btn-primary">
                <i class="fas fa-save"></i> Simpan
            </button>
            <a href="index.php" class="btn" style="background:#e0e0e0;color:#333;">
                <i class="fas fa-times"></i> Batal
            </a>
        </div>
    </form>
</div>

<?php exit; endif; ?>

<?php if ($expired): ?>
<div class="expired-container">
    <div class="expired-icon">🔒</div>
    <h2 class="expired-title">Langganan Berakhir</h2>
    <p class="expired-message">
        Maaf, masa berlangganan untuk akun ini telah berakhir pada <strong><?= date('Y-m-d H:i:s', $subscription_expires_at) ?></strong>.<br><br>
        Untuk melanjutkan penggunaan dan membuka kembali fitur monitoring MikroTik, silakan hubungi penjual/administrator.
    </p>
    <div class="expired-actions">
        <a href="https://wa.me/6285242775539?text=Halo%20saya%20ingin%20memperpanjang%20Langganan%20Monitoring%20VCR" target="_blank" class="btn btn-primary">
            <i class="fab fa-whatsapp"></i> Hubungi via WhatsApp
        </a>
        <form method="post" style="display:inline;">
            <button type="submit" name="logout" class="btn btn-danger">
                <i class="fas fa-sign-out-alt"></i> Logout
            </button>
        </form>
    </div>
</div>
<?php exit; endif; ?>

<?php if (isset($_SESSION['toast_error'])): ?>
<div class="toast">
    <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($_SESSION['toast_error']) ?>
</div>
<script>
setTimeout(() => {
    const toast = document.querySelector('.toast');
    if (toast) toast.remove();
}, 5000);
</script>
<?php unset($_SESSION['toast_error']); endif; ?>

<!-- MikroTik List Panel -->
<div class="panel">
    <div class="panel-header">
        <h2 class="panel-title"><i class="fas fa-list"></i> Daftar MikroTik</h2>
        <div class="panel-actions">
            <a href="index.php?action=add" class="btn btn-primary">
                <i class="fas fa-plus-circle"></i> Tambah Baru
            </a>
            <form method="post" style="margin:0;">
                <button type="submit" name="logout" class="btn btn-danger">
                    <i class="fas fa-sign-out-alt"></i> Logout
                </button>
            </form>
        </div>
    </div>

                    <?php if (!empty($mikrotikList)): ?>
                        <div class="mikrotik-grid">
                            <?php foreach ($mikrotikList as $index => $mt): ?>
                                <div class="mikrotik-card">
                                    <div class="mikrotik-card-title">
                                        <i class="fas fa-router"></i> <?= htmlspecialchars($mt['name']) ?>
                                    </div>
                                    <div class="mikrotik-card-info">
                                        <i class="fas fa-network-wired"></i> <strong><?= htmlspecialchars($mt['ip']) ?></strong>
                                    </div>
                                    <div class="mikrotik-card-info">
                                        <i class="fas fa-user-circle"></i> <?= htmlspecialchars($mt['user']) ?>
                                    </div>
                                    <?php if (!empty($mt['bot_token']) && !empty($mt['chat_id'])): ?>
                                    <div class="mikrotik-card-info">
                                        <i class="fab fa-telegram"></i> Notifikasi aktif
                                    </div>
                                    <?php endif; ?>
                                    
                                    <!-- ANALYTICS BADGE -->
                                    <?php 
                                    // Load analytics untuk card ini
                                    $cacheDir = __DIR__ . '/cache';
                                    $mikrotikIpClean = preg_replace('/[^0-9\.]/', '', $mt['ip']);
                                    $cacheFile = $cacheDir . '/cache_comment_' . ($mikrotikIpClean ?: 'unknown') . '.json';
                                    
                                    $cacheData = [];
                                    if (file_exists($cacheFile)) {
                                        $fp = @fopen($cacheFile, 'r');
                                        if ($fp) {
                                            $contents = '';
                                            if (flock($fp, LOCK_SH)) {
                                                $contents = stream_get_contents($fp);
                                                flock($fp, LOCK_UN);
                                            }
                                            fclose($fp);
                                            $cacheData = json_decode($contents, true) ?: [];
                                        }
                                    }
                                    
                                    $activeCount = 0;
                                    $expiredCount = 0;
                                    $totalUsers = 0;
                                    
                                    if (!empty($cacheData['data'])) {
                                        foreach ($cacheData['data'] as $item) {
                                            if (($item['status'] ?? 'active') === 'active') {
                                                $activeCount++;
                                            }
                                            $totalUsers += (int)($item['jumlah'] ?? 0);
                                        }
                                    }
                                    if (!empty($cacheData['expired'])) {
                                        $expiredCount = count($cacheData['expired']);
                                    }
                                    ?>
                                    
                                    <div style="display:flex; gap:8px; margin-top:10px; margin-bottom:10px; flex-wrap:wrap;">
                                        <div style="background:linear-gradient(135deg, #28a745, #20c997); color:white; padding:6px 10px; border-radius:5px; font-size:12px; font-weight:600; flex:1; text-align:center;">
                                            ✅ <?= $activeCount ?> Active
                                        </div>
                                        <div style="background:linear-gradient(135deg, #ff9800, #ffb74d); color:white; padding:6px 10px; border-radius:5px; font-size:12px; font-weight:600; flex:1; text-align:center;">
                                            ⏱️ <?= $expiredCount ?> Expired
                                        </div>
                                        <!---
                                        <div style="background:linear-gradient(135deg, #667eea, #764ba2); color:white; padding:6px 10px; border-radius:5px; font-size:12px; font-weight:600; flex:1; text-align:center;">
                                            👥 <?= $totalUsers ?> Users
                                        </div>--->
                                    </div>
                                    
                                    <div class="mikrotik-card-actions">
                                        <a href="connect.php?id=<?= $index ?>" class="card-btn">
                                            <i class="fas fa-plug"></i> Buka
                                        </a>
                                        <a href="connect.php?id=<?= $index ?>&analytics=1" class="card-btn" style="background:linear-gradient(135deg, #667eea, #764ba2);">
                                            <i class="fas fa-chart-bar"></i> Analytics
                                        </a>
                                        <a href="edit.php?id=<?= $index ?>" class="card-btn">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        <a href="delete.php?id=<?= $index ?>" class="card-btn" onclick="return confirm('Hapus MikroTik ini?')">
                                            <i class="fas fa-trash"></i> Hapus
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <div class="empty-state-icon">📭</div>
                            <p>Belum ada data MikroTik. <a href="index.php?action=add" style="color:#667eea;font-weight:600;">Tambah sekarang</a></p>
                        </div>
                    <?php endif; ?>
                </div>

<!-- Admin Settings Panel -->
<div class="panel">
    <div class="settings-toggle">
        <h2 class="panel-title"><i class="fas fa-cog"></i> Pengaturan Admin</h2>
        <button id="toggle-admin" class="btn btn-secondary">
            <i class="fas fa-chevron-down"></i> <span id="toggle-text">Tampilkan</span>
        </button>
    </div>

    <div id="admin-panel" style="display:none; margin-top:25px;">
        <?php if ($adminMsg): ?>
            <div class="msg <?= strpos($adminMsg, '✅') !== false ? 'success' : (strpos($adminMsg, '⚠️') !== false ? 'warning' : 'error') ?>">
                <?= htmlspecialchars($adminMsg) ?>
            </div>
        <?php endif; ?>

        <form method="post">
            <div class="settings-content">
                <div class="form-group">
                    <label for="new_user"><i class="fas fa-user-lock"></i> Username Admin</label>
                    <input type="text" id="new_user" name="new_user" value="<?= htmlspecialchars($adminData['user']) ?>" required>
                </div>
                <div class="form-group">
                    <label for="new_pass"><i class="fas fa-key"></i> Password Admin</label>
                    <input type="password" id="new_pass" name="new_pass" value="<?= htmlspecialchars($adminData['pass']) ?>" required>
                </div>

                <?php if (!$expire_exists): ?>
                <div class="form-group">
                    <label for="expire_date"><i class="fas fa-calendar"></i> Tanggal Kadaluarsa (Opsional)</label>
                    <input type="date" id="expire_date" name="expire_date" value="">
                </div>
                <?php endif; ?>
            </div>

            <div style="margin-top:20px;display:flex;gap:10px;">
                <button type="submit" name="edit_admin" class="btn btn-primary">
                    <i class="fas fa-save"></i> Simpan Perubahan
                </button>
            </div>
        </form>

        <?php if ($expire_exists): ?>
            <div class="expire-display" style="margin-top:20px;">
                <i class="fas fa-calendar-check"></i> Tanggal Kadaluarsa: <?= $expire_at > 0 ? date('d F Y', $expire_at) : 'Belum diatur' ?>
            </div>
        <?php endif; ?>
    </div>
</div>

</main>

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

    toggleBtn.addEventListener('click', () => {
        const isHidden = adminPanel.style.display === 'none' || adminPanel.style.display === '';
        adminPanel.style.display = isHidden ? 'block' : 'none';
        toggleText.textContent = isHidden ? 'Sembunyikan' : 'Tampilkan';
        toggleBtn.innerHTML = (isHidden ? '<i class="fas fa-chevron-up"></i>' : '<i class="fas fa-chevron-down"></i>') + '<span id="toggle-text">' + toggleText.textContent + '</span>';
    });

    // Countdown timer
    const topEl = document.getElementById('subscription-top');
    if (topEl) {
        const secondsAttr = topEl.getAttribute('data-seconds');
        const secondsInit = (secondsAttr && !isNaN(parseInt(secondsAttr, 10))) ? parseInt(secondsAttr, 10) : null;
        if (secondsInit !== null && secondsInit > 0) {
            let seconds = secondsInit;
            const updateTop = () => {
                if (seconds <= 0) {
                    topEl.textContent = '00:00:00';
                    window.location.reload();
                    return;
                }
                const h = String(Math.floor(seconds / 3600)).padStart(2, '0');
                const m = String(Math.floor((seconds % 3600) / 60)).padStart(2, '0');
                const s = String(seconds % 60).padStart(2, '0');
                topEl.textContent = `${h}:${m}:${s}`;
                seconds--;
            };
            updateTop();
            setInterval(updateTop, 1000);
        }
    }
});
</script>

</body>
</html>