95 lines
3.5 KiB
JavaScript
95 lines
3.5 KiB
JavaScript
$(document).ready(function() {
|
|
const usersTable = $('#users-table').DataTable({
|
|
"processing": true,
|
|
"serverSide": false, // For simplicity, we'll do client-side processing
|
|
"ajax": {
|
|
"url": "api.php?action=get_users",
|
|
"dataSrc": "data"
|
|
},
|
|
"columns": [
|
|
{ "data": "id" },
|
|
{ "data": "username" },
|
|
{ "data": "email" },
|
|
{ "data": "role" },
|
|
{ "data": "created_at" },
|
|
{
|
|
"data": null,
|
|
"render": function(data, type, row) {
|
|
const isCurrentUser = row.id === currentUserId;
|
|
let actions = '';
|
|
if (!isCurrentUser) {
|
|
actions += `<select class="role-select" data-user-id="${row.id}">
|
|
<option value="user" ${row.role === 'user' ? 'selected' : ''}>User</option>
|
|
<option value="admin" ${row.role === 'admin' ? 'selected' : ''}>Admin</option>
|
|
</select>`;
|
|
actions += `<button class="delete-user" data-user-id="${row.id}">Delete</button>`;
|
|
}
|
|
return actions;
|
|
}
|
|
}
|
|
],
|
|
"initComplete": function(settings, json) {
|
|
// Set currentUserId from the server if available
|
|
window.currentUserId = json.current_user_id || null;
|
|
}
|
|
});
|
|
|
|
// Handle role change
|
|
$('#users-table').on('change', '.role-select', function() {
|
|
const userId = $(this).data('user-id');
|
|
const newRole = $(this).val();
|
|
|
|
if (confirm(`Are you sure you want to change this user's role to ${newRole}?`)) {
|
|
$.ajax({
|
|
url: 'api.php',
|
|
type: 'POST',
|
|
contentType: 'application/json',
|
|
data: JSON.stringify({
|
|
action: 'update_user_role',
|
|
user_id: userId,
|
|
role: newRole
|
|
}),
|
|
success: function(response) {
|
|
if (response.success) {
|
|
alert('User role updated successfully.');
|
|
usersTable.ajax.reload();
|
|
} else {
|
|
alert('Error: ' + response.error);
|
|
}
|
|
},
|
|
error: function() {
|
|
alert('An unexpected error occurred.');
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
// Handle user deletion
|
|
$('#users-table').on('click', '.delete-user', function() {
|
|
const userId = $(this).data('user-id');
|
|
|
|
if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
|
|
$.ajax({
|
|
url: 'api.php',
|
|
type: 'POST',
|
|
contentType: 'application/json',
|
|
data: JSON.stringify({
|
|
action: 'delete_user',
|
|
user_id: userId
|
|
}),
|
|
success: function(response) {
|
|
if (response.success) {
|
|
alert('User deleted successfully.');
|
|
usersTable.ajax.reload();
|
|
} else {
|
|
alert('Error: ' + response.error);
|
|
}
|
|
},
|
|
error: function() {
|
|
alert('An unexpected error occurred.');
|
|
}
|
|
});
|
|
}
|
|
});
|
|
});
|