<?php
session_start();
include_once('includes/config.php');
include_once('includes/quick-menu.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$currentUserId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Handle user form submissions
if ($_POST) {
    $action = $_POST['action'];
    $userName = mysqli_real_escape_string($con, $_POST['userName']);
    $fullName = mysqli_real_escape_string($con, $_POST['fullName']);
    $userTypePost = mysqli_real_escape_string($con, $_POST['userType']);
    $mobileNumber = mysqli_real_escape_string($con, $_POST['mobileNumber']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $roleId = isset($_POST['roleId']) && !empty($_POST['roleId']) ? (int)$_POST['roleId'] : 'NULL';
    
    if ($action == 'create') {
        $password = $_POST['password'];
        
        // Check if username already exists
        $checkQuery = "SELECT ID FROM tblusers WHERE UserName = '$userName'";
        $checkResult = mysqli_query($con, $checkQuery);
        
        if (mysqli_num_rows($checkResult) > 0) {
            $error = "Username already exists!";
        } else {
            // Hash password
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            
            $insertQuery = "INSERT INTO tblusers (UserName, FullName, UserType, RoleID, MobileNumber, Email, Password, RegDate) 
                           VALUES ('$userName', '$fullName', '$userTypePost', $roleId, '$mobileNumber', '$email', '$hashedPassword', NOW())";
            
            if (mysqli_query($con, $insertQuery)) {
                $success = "User added successfully!";
            } else {
                $error = "Error adding user: " . mysqli_error($con);
            }
        }
    } elseif ($action == 'update') {
        $userId = (int)$_POST['userId'];
        
        if ($userId <= 0) {
            $error = "Invalid user ID for update.";
        } else {
            // Check if username already exists for other users
            $checkQuery = "SELECT ID FROM tblusers WHERE UserName = '$userName' AND ID != $userId";
            $checkResult = mysqli_query($con, $checkQuery);
            
            if (mysqli_num_rows($checkResult) > 0) {
                $error = "Username already exists!";
            } else {
                // Update query without password
                $updateQuery = "UPDATE tblusers SET 
                               UserName = '$userName',
                               FullName = '$fullName',
                               UserType = '$userTypePost',
                               RoleID = $roleId,
                               MobileNumber = '$mobileNumber',
                               Email = '$email'
                               WHERE ID = $userId";
                
                // If password is provided, update it too
                if (!empty($_POST['password'])) {
                    $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
                    $updateQuery = "UPDATE tblusers SET 
                                   UserName = '$userName',
                                   FullName = '$fullName',
                                   UserType = '$userTypePost',
                                   RoleID = $roleId,
                                   MobileNumber = '$mobileNumber',
                                   Email = '$email',
                                   Password = '$hashedPassword'
                                   WHERE ID = $userId";
                }
                
                if (mysqli_query($con, $updateQuery)) {
                    if (mysqli_affected_rows($con) > 0) {
                        $success = "User updated successfully!";
                    } else {
                        $error = "No changes were made to the user.";
                    }
                } else {
                    $error = "Error updating user: " . mysqli_error($con);
                }
            }
        }
    }
}

// Handle delete action
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $userId = (int)$_GET['delete'];
    
    // Prevent deleting own account
    if ($userId == $currentUserId) {
        $error = "You cannot delete your own account!";
    } else {
        $deleteQuery = "DELETE FROM tblusers WHERE ID = $userId";
        
        if (mysqli_query($con, $deleteQuery)) {
            $success = "User deleted successfully!";
        } else {
            $error = "Error deleting user: " . mysqli_error($con);
        }
    }
}

// Get all users with role information
$usersQuery = "SELECT u.*, r.RoleName, r.RoleCode 
               FROM tblusers u
               LEFT JOIN tblroles r ON u.RoleID = r.ID
               ORDER BY u.RegDate DESC";
$usersResult = mysqli_query($con, $usersQuery);

$users = [];
$userStats = ['total' => 0, 'admin' => 0, 'staff' => 0];

if ($usersResult) {
    while ($user = mysqli_fetch_assoc($usersResult)) {
        $users[] = $user;
    }
    
    // Calculate statistics
    foreach ($users as $user) {
        $userStats['total']++;
        if ($user['UserType'] == 'admin') {
            $userStats['admin']++;
        } else {
            $userStats['staff']++;
        }
    }
}

// Get all active roles for dropdown
$rolesQuery = "SELECT ID, RoleName, RoleCode FROM tblroles WHERE Status = 'Active' ORDER BY RoleName";
$rolesResult = mysqli_query($con, $rolesQuery);
$availableRoles = [];
if ($rolesResult) {
    while ($role = mysqli_fetch_assoc($rolesResult)) {
        $availableRoles[] = $role;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>HNF Resorts | User Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="css/modern-messagebox.css" rel="stylesheet">
    <?php renderQuickMenuCSS(); ?>
    <style>
        /* Full-height layout to utilize viewport height */
        html, body, #wrapper, #content-wrapper, #content {
            height: 100%;
        }

        /* Compact global paddings */
        .container-fluid {
            padding: 8px 10px;
        }

        .user-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 8px;
            overflow: hidden;
        }
        
        .user-card:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .user-card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 8px 10px;
            position: relative;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .user-card-header.admin {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        .user-card-header.staff {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        .user-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border: 1px solid rgba(255,255,255,0.3);
            flex-shrink: 0;
        }
        
        .user-header-info {
            flex: 1;
            min-width: 0;
        }
        
        .user-name {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .user-type-badge {
            background: rgba(255,255,255,0.2);
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
        }
        
        .user-card-body {
            padding: 8px 10px;
        }
        
        .user-info {
            margin-bottom: 6px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            font-size: 0.78rem;
        }
        
        .info-item i {
            width: 14px;
            color: #6c757d;
            margin-right: 8px;
            font-size: 0.75rem;
        }
        
        .info-item .value {
            color: #495057;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .user-actions {
            border-top: 1px solid #f0f0f0;
            padding: 6px 8px;
            background: #fafafa;
            display: flex;
            gap: 6px;
        }
        
        .edit-btn {
            background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-weight: 600;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            flex: 1;
            text-decoration: none;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            cursor: pointer;
        }
        
        .edit-btn:hover {
            filter: brightness(0.95);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .delete-btn {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .delete-btn:hover {
            filter: brightness(0.95);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .delete-btn:disabled {
            background: #6c757d;
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .search-box {
            background: white;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .search-input {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 6px 30px 6px 10px;
            font-size: 0.85rem;
            transition: all 0.2s ease;
        }
        
        .search-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102,126,234,0.25);
        }
        
        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        /* Tighter grid gutters for compact look */
        #usersGrid {
            margin-left: -6px;
            margin-right: -6px;
        }
        #usersGrid > .col-6 {
            padding-left: 6px;
            padding-right: 6px;
        }

        /* Modal enhancements */
        .modal-content {
            border-radius: 8px;
            border: none;
            box-shadow: 0 8px 25px rgba(0,0,0,0.2);
        }
        
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px 8px 0 0;
            padding: 12px 16px;
        }
        
        .modal-title {
            font-weight: 600;
            font-size: 1rem;
        }
        
        .form-control {
            border-radius: 4px;
            border: 1px solid #e9ecef;
            padding: 8px 12px;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102,126,234,0.1);
        }

        @media (max-width: 768px) {
            .user-card-body {
                padding: 6px 8px;
            }
            
            .user-actions {
                padding: 4px 6px;
                gap: 4px;
            }
            
            .edit-btn {
                padding: 4px 8px;
                font-size: 0.7rem;
            }
            
            .delete-btn {
                padding: 4px 6px;
                font-size: 0.7rem;
            }
            
            .user-name {
                font-size: 0.85rem;
            }
            
            .info-item {
                font-size: 0.75rem;
                margin-bottom: 2px;
            }
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Alert Messages -->
                    <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle mr-2"></i><?php echo $success; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle mr-2"></i><?php echo $error; ?>
                        <button type="button" class="close" data-dismiss="alert">
                            <span>&times;</span>
                        </button>
                    </div>
                    <?php endif; ?>

                    <?php renderQuickMenu("User Management", "Manage system users and permissions"); ?>
                    
                    <div class="d-flex justify-content-end mb-3">
                        <button class="btn btn-light btn-sm" onclick="openUserModal()">
                            <i class="fas fa-plus mr-1"></i>Add User
                        </button>
                    </div>

                    <!-- User Statistics -->
                    <div class="row mb-3">
                        <div class="col-4">
                            <div class="text-center">
                                <div class="h5 mb-0 text-primary"><?php echo $userStats['total']; ?></div>
                                <small class="text-muted">Total Users</small>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="text-center">
                                <div class="h5 mb-0 text-danger"><?php echo $userStats['admin']; ?></div>
                                <small class="text-muted">Admins</small>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="text-center">
                                <div class="h5 mb-0 text-info"><?php echo $userStats['staff']; ?></div>
                                <small class="text-muted">Staff</small>
                            </div>
                        </div>
                    </div>

                    <!-- Search Box -->
                    <div class="search-box">
                        <div class="position-relative">
                            <input type="text" class="form-control search-input" id="userSearch" placeholder="Search users...">
                            <i class="fas fa-search search-icon"></i>
                        </div>
                    </div>

                    <!-- Filter Buttons -->
                    <div class="mb-3">
                        <div class="btn-group btn-group-sm w-100">
                            <button class="btn btn-outline-primary active" onclick="filterUsers('all')">All</button>
                            <button class="btn btn-outline-danger" onclick="filterUsers('admin')">Admin</button>
                            <button class="btn btn-outline-info" onclick="filterUsers('staff')">Staff</button>
                        </div>
                    </div>

                    <!-- Users Grid -->
                    <div class="row" id="usersGrid">
                        <?php foreach($users as $user): ?>
                        <div class="col-6 user-item" data-usertype="<?php echo strtolower($user['UserType']); ?>">
                            <div class="user-card">
                                <div class="user-card-header <?php echo strtolower($user['UserType']); ?>">
                                    <div class="user-avatar">
                                        <i class="fas fa-user"></i>
                                    </div>
                                    <div class="user-header-info">
                                        <div class="user-name"><?php echo htmlspecialchars($user['FullName']); ?></div>
                                        <div>
                                            <span class="user-type-badge"><?php echo ucfirst($user['UserType']); ?></span>
                                            <?php if (!empty($user['RoleName'])): ?>
                                            <span class="user-type-badge" style="background: rgba(255,255,255,0.3); margin-left: 4px;">
                                                <i class="fas fa-shield-alt" style="font-size: 0.6rem;"></i> <?php echo htmlspecialchars($user['RoleName']); ?>
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                <div class="user-card-body">
                                    <div class="user-info">
                                        <div class="info-item">
                                            <i class="fas fa-user-circle"></i>
                                            <span class="value"><?php echo htmlspecialchars($user['UserName']); ?></span>
                                        </div>
                                        <?php if (!empty($user['RoleName'])): ?>
                                        <div class="info-item" style="background: #f0f7ff; padding: 4px 6px; border-radius: 4px; margin: 4px 0;">
                                            <i class="fas fa-shield-alt" style="color: #667eea;"></i>
                                            <span class="value" style="color: #667eea; font-weight: 600;">
                                                <?php echo htmlspecialchars($user['RoleName']); ?>
                                            </span>
                                        </div>
                                        <?php else: ?>
                                        <div class="info-item" style="background: #fff3cd; padding: 4px 6px; border-radius: 4px; margin: 4px 0;">
                                            <i class="fas fa-exclamation-triangle" style="color: #856404;"></i>
                                            <span class="value" style="color: #856404; font-weight: 600;">No Role Assigned</span>
                                        </div>
                                        <?php endif; ?>
                                        <?php if (!empty($user['MobileNumber'])): ?>
                                        <div class="info-item">
                                            <i class="fas fa-phone"></i>
                                            <span class="value"><?php echo htmlspecialchars($user['MobileNumber']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <?php if (!empty($user['Email'])): ?>
                                        <div class="info-item">
                                            <i class="fas fa-envelope"></i>
                                            <span class="value"><?php echo htmlspecialchars($user['Email']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="info-item">
                                            <i class="fas fa-calendar"></i>
                                            <span class="value">Joined: <?php echo date('M d, Y', strtotime($user['RegDate'])); ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="user-actions">
                                    <button class="edit-btn" onclick="editUser(<?php echo $user['ID']; ?>)">
                                        <i class="fas fa-edit"></i>
                                        <span class="btn-text">Edit</span>
                                    </button>
                                    <button class="delete-btn" onclick="deleteUser(<?php echo $user['ID']; ?>, '<?php echo htmlspecialchars($user['FullName']); ?>')" 
                                            <?php echo ($user['ID'] == $currentUserId) ? 'disabled' : ''; ?>>
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <?php if (empty($users)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-users fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">No users found</h5>
                        <p class="text-muted">Click "Add User" to create your first user</p>
                    </div>
                    <?php endif; ?>

                </div>
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- User Modal -->
    <div class="modal fade" id="userModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalLabel">
                        <i class="fas fa-user-plus mr-2"></i>Add New User
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <form method="POST" id="userForm">
                    <div class="modal-body">
                        <input type="hidden" name="action" id="formAction" value="create">
                        <input type="hidden" name="userId" id="userId">
                        
                        <div class="form-group">
                            <label for="userName">Username <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="userName" name="userName" 
                                   placeholder="Enter username" required>
                            <small class="form-text text-muted">Username must be unique</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="fullName">Full Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="fullName" name="fullName" 
                                   placeholder="Enter full name" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="userType">User Type <span class="text-danger">*</span></label>
                            <select class="form-control" id="userType" name="userType" required>
                                <option value="">Select User Type</option>
                                <option value="admin">Admin</option>
                                <option value="staff">Staff</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="roleId">Assign Role</label>
                            <select class="form-control" id="roleId" name="roleId">
                                <option value="">No Role Assigned</option>
                                <?php foreach ($availableRoles as $role): ?>
                                <option value="<?php echo $role['ID']; ?>">
                                    <?php echo htmlspecialchars($role['RoleName']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="form-text text-muted">Roles define user permissions</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="mobileNumber">Mobile Number</label>
                            <input type="tel" class="form-control" id="mobileNumber" name="mobileNumber" 
                                   placeholder="Enter mobile number">
                        </div>
                        
                        <div class="form-group">
                            <label for="email">Email Address</label>
                            <input type="email" class="form-control" id="email" name="email" 
                                   placeholder="Enter email address">
                        </div>
                        
                        <div class="form-group">
                            <label for="password">Password <span class="text-danger" id="passwordRequired">*</span></label>
                            <input type="password" class="form-control" id="password" name="password" 
                                   placeholder="Enter password" autocomplete="new-password">
                            <small class="form-text text-muted" id="passwordHelp">Minimum 6 characters recommended</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="submitBtn">
                            <i class="fas fa-save mr-1"></i>Save User
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/modern-messagebox.js"></script>
    <script src="js/messagebox-wrapper.js"></script>
    <?php renderQuickMenuScript(); ?>

    <script>
        $(document).ready(function() {
            // Hide sidebar on load for a focused, full-width mobile-like view
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            if ($('.sidebar').hasClass('toggled')) {
                $('.sidebar .collapse').collapse('hide');
            }

            // Add animation on page load
            $('.user-card').each(function(index) {
                $(this).css('opacity', '0').css('transform', 'translateY(30px)');
                $(this).delay(index * 50).animate({
                    opacity: 1
                }, 400, function() {
                    $(this).css('transform', 'translateY(0)');
                });
            });
            
            // Search functionality
            $('#userSearch').on('keyup', function() {
                const searchTerm = $(this).val().toLowerCase();
                
                $('.user-item').each(function() {
                    const userName = $(this).find('.user-name').text().toLowerCase();
                    const userNameField = $(this).find('.info-item .value').first().text().toLowerCase();
                    const email = $(this).find('.fa-envelope').parent().find('.value').text().toLowerCase();
                    const mobile = $(this).find('.fa-phone').parent().find('.value').text().toLowerCase();
                    
                    if (userName.includes(searchTerm) || userNameField.includes(searchTerm) || 
                        email.includes(searchTerm) || mobile.includes(searchTerm)) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
            });
        });

        function openUserModal() {
            clearUserForm();
            $('#password').prop('required', true);
            $('#passwordRequired').show();
            $('#passwordHelp').text('Minimum 6 characters recommended');
            $('#userModal').modal('show');
        }

        function clearUserForm() {
            document.getElementById('userForm').reset();
            document.getElementById('formAction').value = 'create';
            document.getElementById('userId').value = '';
            document.getElementById('userModalLabel').innerHTML = '<i class="fas fa-user-plus mr-2"></i>Add New User';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Save User';
        }

        async function editUser(userId) {
            try {
                const response = await fetch('api/get-user.php?id=' + userId);
                const data = await response.json();
                if (data.success) {
                    const user = data.user;
                    document.getElementById('formAction').value = 'update';
                    document.getElementById('userId').value = user.ID;
                    document.getElementById('userName').value = user.UserName;
                    document.getElementById('fullName').value = user.FullName;
                    document.getElementById('userType').value = user.UserType;
                    document.getElementById('roleId').value = user.RoleID || '';
                    document.getElementById('mobileNumber').value = user.MobileNumber || '';
                    document.getElementById('email').value = user.Email || '';
                    document.getElementById('password').value = '';
                    $('#password').prop('required', false);
                    $('#passwordRequired').hide();
                    $('#passwordHelp').text('Leave blank to keep current password');
                    
                    document.getElementById('userModalLabel').innerHTML = '<i class="fas fa-user-edit mr-2"></i>Edit User';
                    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save mr-1"></i>Update User';
                    
                    $('#userModal').modal('show');
                } else {
                    await MsgBox.alert('Error fetching user data: ' + data.message);
                }
            } catch (error) {
                console.error('Error:', error);
                await MsgBox.alert('Error fetching user data');
            }
        }

        async function deleteUser(userId, userName) {
            const result = await MsgBox.confirm(`Are you sure you want to delete user "${userName}"?`);
            if (result) {
                window.location.href = 'user-management.php?delete=' + userId;
            }
        }

        function filterUsers(userType) {
            // Update active button
            $('.btn-group .btn').removeClass('active');
            event.target.classList.add('active');
            
            // Show/hide users based on type
            $('.user-item').each(function() {
                if (userType === 'all') {
                    $(this).show();
                } else {
                    const itemUserType = $(this).data('usertype');
                    if (itemUserType === userType) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                }
            });
        }

        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);
    </script>
</body>
</html>
