const switchTenant = async (link) => { const tenantId = link.dataset.switchTenant; const csrfKey = link.dataset.csrfKey; const csrfToken = link.dataset.csrfToken; const errorMessage = link.dataset.errorMessage || 'Failed to switch tenant'; if (!tenantId || !csrfKey || !csrfToken) { console.error('Missing tenant ID or CSRF token'); return; } // Disable link during request link.style.pointerEvents = 'none'; link.style.opacity = '0.5'; try { const body = new URLSearchParams({ tenant_id: tenantId, [csrfKey]: csrfToken }); const response = await fetch('admin/users/switch-tenant', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', 'X-Requested-With': 'fetch' }, body }); if (response.ok) { const data = await response.json(); if (data.ok) { window.location.reload(); } else { console.error('Tenant switch failed:', data.error); alert(errorMessage); link.style.pointerEvents = ''; link.style.opacity = ''; } } else { console.error('Server error:', response.status); alert(errorMessage); link.style.pointerEvents = ''; link.style.opacity = ''; } } catch (error) { console.error('Network error:', error); alert(errorMessage); link.style.pointerEvents = ''; link.style.opacity = ''; } }; const initTenantSwitcher = () => { const tenantLinks = document.querySelectorAll('[data-switch-tenant]'); tenantLinks.forEach(link => { link.addEventListener('click', (e) => { e.preventDefault(); switchTenant(link); }); }); }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initTenantSwitcher); } else { initTenantSwitcher(); }