<?php
// Clean, production-ready code without debugging
include("header.php");

// Check if user is admin (using username cybervax)
if($_SESSION['username'] !== 'cybervax') {
    header("Location: index.php");
    exit('Access Denied: Admin privileges required');
}
?>

<div class="full-width-container">
    <!-- Admin Panel Header -->
    <div class="row">
        <div class="col-md-12">
            <div class="cyber-panel">
                <div class="cyber-panel-header">
                    <div class="cyber-title">
                        <i class="fas fa-crown cyber-icon"></i>
                        <h3>CyberOK Admin Panel</h3>
                        <div class="cyber-title-decoration"></div>
                    </div>
                </div>
                <div class="cyber-panel-body">
                    <div class="cyber-notification success">
                        <i class="fas fa-check-circle"></i>
                        <span>Welcome to the Admin Control Panel, <?php echo $_SESSION['username']; ?>!</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Admin Actions Section -->
    <div class="row">
        <div class="col-md-6">
            <div class="cyber-panel">
                <div class="cyber-panel-header">
                    <div class="cyber-title">
                        <i class="fas fa-users-cog cyber-icon"></i>
                        <h3>User Management</h3>
                        <div class="cyber-title-decoration"></div>
                    </div>
                </div>
                <div class="cyber-panel-body">
                    <div class="admin-action-card">
                        <h4><i class="fas fa-user-plus"></i> Add New User</h4>
                        <form method="POST" action="">
                            <input type="hidden" name="action" value="add_user">
                            <div class="form-group">
                                <label>Username</label>
                                <input type="text" name="username" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label>Password</label>
                                <input type="password" name="password" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label>License Status</label>
                                <select name="license_status" class="form-control">
                                    <option value="active">Active</option>
                                    <option value="suspended">Suspended</option>
                                    <option value="expired">Expired</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>License Tier</label>
                                <select name="license_tier" class="form-control">
                                    <option value="regular">Regular</option>
                                    <option value="premium">Premium</option>
                                    <option value="vip">VIP</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>License Duration</label>
                                <select name="license_duration" class="form-control">
                                    <option value="7">7 Days</option>
                                    <option value="30" selected>30 Days</option>
                                    <option value="90">3 Months</option>
                                    <option value="180">6 Months</option>
                                    <option value="365">1 Year</option>
                                    <option value="lifetime">Lifetime</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary">Create User</button>
                        </form>
                    </div>
                    
                    <div class="admin-divider"></div>
                    
                    <div class="admin-action-card">
                        <h4><i class="fas fa-user-edit"></i> Manage Users</h4>
                        <p>View and manage all registered users and their licenses</p>
                        <a href="#" class="btn btn-primary" onclick="loadUsers()">Manage Users</a>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="cyber-panel">
                <div class="cyber-panel-header">
                    <div class="cyber-title">
                        <i class="fas fa-tools cyber-icon"></i>
                        <h3>System Tools</h3>
                        <div class="cyber-title-decoration"></div>
                    </div>
                </div>
                <div class="cyber-panel-body">
                    <div class="admin-action-card">
                        <h4><i class="fas fa-database"></i> Database Backup</h4>
                        <form method="POST" action="">
                            <input type="hidden" name="action" value="db_action">
                            <input type="hidden" name="db_action" value="backup">
                            <p>Create a complete backup of the database</p>
                            <button type="submit" class="btn btn-primary">Backup Database</button>
                        </form>
                    </div>
                    
                    <div class="admin-divider"></div>
                    
                    <div class="admin-action-card">
                        <h4><i class="fas fa-cogs"></i> System Settings</h4>
                        <a href="settings.php" class="btn btn-primary">Manage Settings</a>
                    </div>
                    
                    <div class="admin-divider"></div>
                    
                    <div class="admin-action-card">
                        <h4><i class="fas fa-chart-line"></i> System Stats</h4>
                        <div class="admin-stats">
                            <?php
                            // Database size
                            $db_size_query = mysqli_query($condb, "SELECT table_schema AS 'Database', 
                                ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)' 
                                FROM information_schema.TABLES 
                                WHERE table_schema = 'cyberbotnet' 
                                GROUP BY table_schema");
                            $db_size = mysqli_fetch_assoc($db_size_query);
                            
                            // Get counts
                            $bot_count = mysqli_query($condb, "SELECT COUNT(*) AS total FROM bot");
                            $bot_count_result = mysqli_fetch_assoc($bot_count);
                            
                            $task_count = mysqli_query($condb, "SELECT COUNT(*) AS total FROM tasks");
                            $task_count_result = mysqli_fetch_assoc($task_count);
                            
                            // Get active users instead of passwords
                            $active_users = mysqli_query($condb, "SELECT COUNT(*) AS total FROM users WHERE license_status = 'active'");
                            $active_users_result = mysqli_fetch_assoc($active_users);
                            
                            // Server storage
                            $totalSpace = disk_total_space("C:");
                            $freeSpace = disk_free_space("C:");
                            $usedSpace = $totalSpace - $freeSpace;
                            
                            $totalSpaceGB = round($totalSpace / 1024 / 1024 / 1024, 2);
                            $freeSpaceGB = round($freeSpace / 1024 / 1024 / 1024, 2);
                            $usedSpaceGB = round($usedSpace / 1024 / 1024 / 1024, 2);
                            $usedPercent = round(($usedSpace / $totalSpace) * 100, 1);
                            ?>
                            
                            <div class="stat-item">
                                <span class="stat-label">Database Size:</span>
                                <span class="stat-value"><?php echo isset($db_size['Size (MB)']) ? $db_size['Size (MB)'] . ' MB' : 'N/A'; ?></span>
                            </div>
                            
                            <div class="stat-item">
                                <span class="stat-label">Total Bots:</span>
                                <span class="stat-value"><?php echo $bot_count_result['total']; ?></span>
                            </div>
                            
                            <div class="stat-item">
                                <span class="stat-label">Server Storage:</span>
                                <span class="stat-value"><?php echo $usedSpaceGB . ' GB / ' . $totalSpaceGB . ' GB (' . $usedPercent . '%)'; ?></span>
                            </div>
                            
                            <div class="stat-item">
                                <span class="stat-label">Total Active Users:</span>
                                <span class="stat-value"><?php echo $active_users_result['total']; ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- User Management Section (hidden initially, loaded via AJAX) -->
    <div class="row" id="users-container" style="display:none;">
        <div class="col-md-12">
            <div class="cyber-panel">
                <div class="cyber-panel-header">
                    <div class="cyber-title">
                        <i class="fas fa-users cyber-icon"></i>
                        <h3>User Management</h3>
                        <div class="cyber-title-decoration"></div>
                    </div>
                </div>
                <div class="cyber-panel-body">
                    <div id="users-list-container">
                        <div class="text-center">
                            <i class="fas fa-spinner fa-spin fa-2x"></i>
                            <p>Loading user data...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Process Admin Actions -->
<?php
// Process form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // Add User Action
    if ($action === 'add_user') {
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        $license_status = $_POST['license_status'];
        $license_tier = $_POST['license_tier'];
        $license_duration = $_POST['license_duration'];
        
        // Calculate license start and end dates
        $license_start = date('Y-m-d H:i:s');
        
        if ($license_duration === 'lifetime') {
            $license_expiry = NULL; // No expiry for lifetime
        } else {
            $license_expiry = date('Y-m-d H:i:s', strtotime("+{$license_duration} days"));
        }
        
        // Hash password
        $hashed_password = md5($password); // Using md5 to match existing logic
        
        // Check if user exists
        $check_user = $condb->prepare("SELECT id_user FROM users WHERE username = ?");
        $check_user->bind_param("s", $username);
        $check_user->execute();
        $user_result = $check_user->get_result();
        
        if ($user_result->num_rows == 0) {
            // Check if license_expiry column exists
            $checkColumn = $condb->query("SHOW COLUMNS FROM users LIKE 'license_expiry'");
            $licenseExpiryExists = ($checkColumn && $checkColumn->num_rows > 0);
            
            // Create user
            if ($licenseExpiryExists) {
                $add_user = $condb->prepare("INSERT INTO users (username, password, license_status, license_tier, license_start, license_expiry) VALUES (?, ?, ?, ?, ?, ?)");
                $add_user->bind_param("ssssss", $username, $hashed_password, $license_status, $license_tier, $license_start, $license_expiry);
            } else {
                $add_user = $condb->prepare("INSERT INTO users (username, password, license_status, license_tier, license_start) VALUES (?, ?, ?, ?, ?)");
                $add_user->bind_param("sssss", $username, $hashed_password, $license_status, $license_tier, $license_start);
            }
            
            if ($add_user->execute()) {
                // Update all users where license_start is NULL
                $condb->query("UPDATE users SET license_start = NOW() WHERE license_start IS NULL");
                
                echo '<script>alert("User created successfully!");</script>';
            } else {
                echo '<script>alert("Error creating user: ' . $condb->error . '");</script>';
            }
            
            $add_user->close();
        } else {
            echo '<script>alert("Username already exists!");</script>';
        }
        
        $check_user->close();
    }
    
    // Database Actions
    if ($action === 'db_action') {
        $db_action = $_POST['db_action'];
        
        if ($db_action === 'backup') {
            // Create a proper database backup
            $backup_dir = 'backups/'; 
            if (!is_dir($backup_dir)) {
                mkdir($backup_dir, 0755, true);
            }
            
            $backup_file = $backup_dir . 'cyberbotnet_' . date('Y-m-d_H-i-s') . '.sql';
            $command = sprintf('mysqldump -u %s -p%s %s > %s', 'root', 'Cyberproduct123!@#', 'cyberbotnet', $backup_file);
            
            if (system($command)) {
                echo '<script>alert("Database backup created successfully: ' . $backup_file . '");</script>';
            } else {
                echo '<script>alert("Error creating database backup. Check server permissions.");</script>';
            }
        }
    }
}
?>

<style>
/* Admin Panel Specific Styles */
body {
    background: #0a0a0f !important;
    color: #ffffff !important;
}

.cyber-panel {
    background: rgba(19, 19, 31, 0.85) !important;
    backdrop-filter: blur(20px);
    border-radius: 15px;
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.3),
                inset 0 0 2px rgba(0, 255, 255, 0.1);
    overflow: hidden;
    border: 1px solid rgba(0, 255, 255, 0.2);
    margin-bottom: 30px;
}

.cyber-panel-header {
    background: rgba(19, 19, 31, 0.9) !important;
    border-bottom: 1px solid rgba(0, 255, 255, 0.2);
    padding: 20px;
}

.cyber-panel-body {
    background: rgba(13, 13, 22, 0.7) !important;
    padding: 20px;
}

.full-width-container {
    padding: 20px;
    background: #0a0a0f !important;
}

.admin-action-card {
    background: rgba(19, 19, 31, 0.85) !important;
    border: 1px solid rgba(0, 255, 255, 0.2);
    border-radius: 15px;
    padding: 20px;
    margin-bottom: 20px;
    transition: all 0.3s ease;
}

.admin-action-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1) !important;
    border-color: rgba(0, 255, 255, 0.4);
}

.admin-action-card h4 {
    color: #00f3ff;
    font-family: 'Orbitron', sans-serif;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
    text-shadow: 0 0 10px rgba(0, 243, 255, 0.5);
}

.admin-action-card i {
    color: #00f3ff;
}

.admin-action-card p {
    color: #8a8fa3;
    margin-bottom: 15px;
    font-size: 14px;
}

.admin-divider {
    height: 1px;
    background: linear-gradient(90deg, transparent, rgba(0, 255, 255, 0.2), transparent);
    margin: 25px 0;
}

.admin-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
}

.stat-item {
    flex: 1 1 40%;
    min-width: 150px;
    background: rgba(0, 0, 0, 0.2);
    padding: 15px;
    border-radius: 10px;
    border: 1px solid rgba(0, 255, 255, 0.1);
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.stat-label {
    color: #8a8fa3;
    font-size: 12px;
}

.stat-value {
    color: #00f3ff;
    font-size: 18px;
    font-family: 'Orbitron', sans-serif;
    text-shadow: 0 0 10px rgba(0, 243, 255, 0.3);
}

.form-control {
    background: rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(0, 255, 255, 0.2);
    color: #ffffff;
    border-radius: 8px;
    padding: 10px 15px;
    transition: all 0.3s ease;
}

.form-control:focus {
    border-color: #00f3ff;
    box-shadow: 0 0 10px rgba(0, 243, 255, 0.3);
    outline: none;
}

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

.form-group label {
    display: block;
    margin-bottom: 8px;
    color: #8a8fa3;
}

.btn-primary {
    background: transparent;
    border: 2px solid #00f3ff;
    color: #00f3ff;
    border-radius: 8px;
    padding: 10px 20px;
    font-family: 'Orbitron', sans-serif;
    font-weight: 500;
    letter-spacing: 1px;
    transition: all 0.3s ease;
    text-transform: uppercase;
    margin-top: 10px;
}

.btn-primary:hover {
    background: #00f3ff;
    color: #0a0a0f;
    transform: translateY(-2px);
    box-shadow: 0 0 15px rgba(0, 243, 255, 0.4);
}

/* Fix table colors */
.table-responsive {
    background: rgba(13, 13, 22, 0.7) !important;
    border-radius: 12px;
    border: 1px solid rgba(0, 255, 255, 0.1);
    overflow: hidden;
}

.table {
    background: transparent !important;
    color: #ffffff !important;
    margin-bottom: 0;
}

.table thead th {
    background: rgba(0, 0, 0, 0.3) !important;
    color: #00f3ff !important;
    border-bottom: 2px solid rgba(0, 255, 255, 0.2) !important;
    font-family: 'Orbitron', sans-serif;
    font-weight: 500;
    letter-spacing: 1px;
    text-transform: uppercase;
    padding: 12px 15px;
}

.table tbody tr {
    background: transparent !important;
    transition: all 0.3s ease;
}

.table tbody tr:hover {
    background: rgba(0, 255, 255, 0.05) !important;
}

.table td {
    border-color: rgba(0, 255, 255, 0.05) !important;
    color: #ffffff !important;
    padding: 12px 15px;
}

.row {
    background: transparent !important;
}

.col-md-6, .col-md-12 {
    background: transparent !important;
}

.container-fluid {
    background: #0a0a0f !important;
}

/* Override Bootstrap styles */
.panel, .panel-default, .panel-body, .panel-heading {
    background: rgba(19, 19, 31, 0.85) !important;
    color: #ffffff !important;
    border-color: rgba(0, 255, 255, 0.2) !important;
}

/* Make sure tables have proper hover colors */
.table-hover > tbody > tr:hover {
    background-color: rgba(0, 255, 255, 0.05) !important;
}

/* Fix text colors in tables */
.table > tbody > tr > td {
    color: #ffffff !important;
}

.label {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 5px;
    font-size: 12px;
    font-weight: 500;
}

.label-success {
    background: rgba(0, 255, 128, 0.15);
    color: #00ff80;
    border: 1px solid rgba(0, 255, 128, 0.3);
}

.label-warning {
    background: rgba(255, 165, 0, 0.15);
    color: #ffa500;
    border: 1px solid rgba(255, 165, 0, 0.3);
}

.label-danger {
    background: rgba(255, 67, 67, 0.15);
    color: #ff4343;
    border: 1px solid rgba(255, 67, 67, 0.3);
}

.btn-xs {
    padding: 5px 10px;
    font-size: 12px;
    line-height: 1.5;
    border-radius: 3px;
}

.btn-danger {
    background: transparent;
    border: 1px solid #ff4343;
    color: #ff4343;
}

.btn-danger:hover {
    background: rgba(255, 67, 67, 0.2);
}

.cyber-notification {
    background: rgba(19, 19, 31, 0.8);
    color: #8a8fa3;
    border: 1px solid rgba(0, 255, 255, 0.1);
}

.cyber-notification.success {
    background: rgba(0, 255, 128, 0.1);
    border-color: rgba(0, 255, 128, 0.2);
    color: #00ff80;
}

/* Make sure all panels have consistent backgrounds */
#users-container, 
#licenses-container,
.cyber-panel,
.panel,
.panel-default,
.well {
    background-color: rgba(19, 19, 31, 0.85) !important;
}

@media screen {
    .table-hover > tbody > tr {
        background-color: transparent !important;
    }
    
    .table-hover > tbody > tr:hover {
        background-color: rgba(0, 255, 255, 0.05) !important;
    }
    
    .table-hover > tbody > tr > td {
        background-color: transparent !important;
    }
    
    .main-content {
        background: #0a0a0f !important;
    }
}
</style>

<script>
function loadUsers() {
    const container = document.getElementById('users-container');
    const listContainer = document.getElementById('users-list-container');
    
    // Show container
    container.style.display = 'block';
    
    // Show loading indicator
    listContainer.innerHTML = `<div class="text-center">
        <i class="fas fa-spinner fa-spin fa-2x"></i>
        <p>Loading user data...</p>
    </div>`;
    
    // Fetch users
    fetch('get_users.php')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.text();
        })
        .then(data => {
            listContainer.innerHTML = data;
            
            // Scroll to the users section
            container.scrollIntoView({ behavior: 'smooth', block: 'start' });
        })
        .catch(error => {
            listContainer.innerHTML = `<div class="cyber-notification" style="background-color: rgba(255,0,0,0.1); color: #ff4444; border: 1px solid rgba(255,0,0,0.2);">
                <i class="fas fa-exclamation-triangle"></i> 
                <span>Error loading users: ${error.message}</span>
            </div>`;
        });
}
</script>

<?php
include("footer.php");
?> 