91 lines
2.5 KiB
PHP
91 lines
2.5 KiB
PHP
<?php
|
|
|
|
use MintyPHP\Http\Request;
|
|
use MintyPHP\Router;
|
|
use MintyPHP\Session;
|
|
use MintyPHP\Support\Guard;
|
|
|
|
Guard::requireLogin();
|
|
$userTenantContextService = app(\MintyPHP\Service\User\UserTenantContextService::class);
|
|
$errorBag = formErrors();
|
|
|
|
if ((requestInput()->method()) !== 'POST') {
|
|
Router::redirect('admin');
|
|
return;
|
|
}
|
|
|
|
if (!Session::checkCsrfToken()) {
|
|
if (Request::wantsJson()) {
|
|
http_response_code(400);
|
|
Router::json(['ok' => false, 'error' => 'csrf']);
|
|
return;
|
|
}
|
|
$errorBag->addGlobal(t('Form expired, please try again'));
|
|
flashFormErrors($errorBag, 'admin', 'switch_tenant');
|
|
Router::redirect('admin');
|
|
return;
|
|
}
|
|
|
|
$userId = (int) ($_SESSION['user']['id'] ?? 0);
|
|
if ($userId <= 0) {
|
|
http_response_code(401);
|
|
if (Request::wantsJson()) {
|
|
Router::json(['ok' => false, 'error' => 'unauthorized']);
|
|
return;
|
|
}
|
|
Router::redirect('login');
|
|
return;
|
|
}
|
|
|
|
// Get tenant_id from POST
|
|
$tenantId = (int) (requestInput()->bodyAll()['tenant_id'] ?? 0);
|
|
|
|
if ($tenantId <= 0) {
|
|
http_response_code(400);
|
|
if (Request::wantsJson()) {
|
|
Router::json(['ok' => false, 'error' => 'invalid_tenant_id']);
|
|
return;
|
|
}
|
|
$errorBag->addGlobal(t('Failed to switch tenant'));
|
|
flashFormErrors($errorBag, 'admin', 'switch_tenant');
|
|
Router::redirect('admin');
|
|
return;
|
|
}
|
|
|
|
$result = $userTenantContextService->setCurrentTenant($userId, $tenantId);
|
|
if (!($result['ok'] ?? false)) {
|
|
$error = $result['error'] ?? 'update_failed';
|
|
http_response_code(400);
|
|
if (Request::wantsJson()) {
|
|
Router::json(['ok' => false, 'error' => $error]);
|
|
return;
|
|
}
|
|
$errorBag->addGlobal(t('Failed to switch tenant'));
|
|
flashFormErrors($errorBag, 'admin', 'switch_tenant');
|
|
Router::redirect('admin');
|
|
return;
|
|
}
|
|
|
|
// Update session with new current tenant
|
|
if (isset($_SESSION['user'])) {
|
|
$_SESSION['user']['current_tenant_id'] = $tenantId;
|
|
}
|
|
|
|
// Update session with full tenant data
|
|
$_SESSION['current_tenant'] = $result['tenant'] ?? null;
|
|
|
|
// Reload available tenants and departments
|
|
$_SESSION['available_tenants'] = $userTenantContextService->getAvailableTenants($userId);
|
|
$_SESSION['available_departments_by_tenant'] = $userTenantContextService->getAvailableDepartmentsByTenant($userId);
|
|
|
|
if (Request::wantsJson()) {
|
|
Router::json([
|
|
'ok' => true,
|
|
'tenant_id' => $tenantId,
|
|
'tenant' => $result['tenant'] ?? null,
|
|
]);
|
|
return;
|
|
}
|
|
|
|
Router::redirect('admin');
|