$(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 += ``; actions += ``; } 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.'); } }); } }); });