async function handleUserAction(userId, action) {
    if (!action) return;
    if (action === 'promote_admin') {
        if (!confirm('Promote to admin?')) return;
        const fd = new FormData(); fd.append('user_id', userId); fd.append('action', 'promote');
        const res = await fetch('admin_toggle_admin.php', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) location.reload(); else alert('Error: ' + (data.message||'unknown'));
    }
    if (action === 'demote_admin') {
        if (!confirm('Remove admin rights?')) return;
        const fd = new FormData(); fd.append('user_id', userId); fd.append('action', 'demote');
        const res = await fetch('admin_toggle_admin.php', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) location.reload(); else alert('Error: ' + (data.message||'unknown'));
    }
    if (action === 'promote_editor') {
        if (!confirm('Promote to Editor?')) return;
        const fd = new FormData(); fd.append('user_id', userId);
        // provide editor-level permissions
        fd.append('permissions[manage_posts]', 'editor');
        fd.append('permissions[manage_pages]', 'editor');
        fd.append('permissions[manage_users]', 'none');
        const res = await fetch('admin_promote_subadmin.php', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) { alert('Promoted to Editor'); location.reload(); } else alert('Error: ' + (data.message||'unknown'));
    }
    if (action === 'unpromote_subadmin') {
        if (!confirm('Remove sub-admin privileges?')) return;
        const fd = new FormData(); fd.append('user_id', userId);
        const res = await fetch('admin_unpromote_subadmin.php', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) { alert('Sub-admin removed'); location.reload(); } else alert('Error: ' + (data.message||'unknown'));
    }
    if (action === 'promote_subadmin') {
        if (!confirm('Promote this user to sub-admin (default permissions)?')) return;
        const fd = new FormData(); fd.append('user_id', userId);
        const res = await fetch('admin_promote_subadmin.php', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) { alert('Promoted to sub-admin. You can adjust permissions in Sub-admins.'); location.reload(); }
        else alert('Error: ' + (data.message||'unknown'));
    }
    if (action === 'delete_user') {
        if (!confirm('Delete user and related admin/subadmin entries? This cannot be undone.')) return;
        const fd = new FormData(); fd.append('user_id', userId);
        const res = await fetch('admin_delete_user.php', { method: 'POST', body: fd });
        const data = await res.json();
        if (data.success) location.reload(); else alert('Error: ' + (data.message||'unknown'));
    }
}
