<?php

use MintyPHP\Http\Request;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();

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']) && is_array($session['user'])) {
    $userSession = $session['user'];
    $userSession['current_tenant_id'] = $tenantId;
    $sessionStore->set('user', $userSession);
}

// Update session with full tenant data
$sessionStore->set('current_tenant', $result['tenant'] ?? null);

// Reload available tenants and departments
$sessionStore->set('available_tenants', $userTenantContextService->getAvailableTenants($userId));
$sessionStore->set('available_departments_by_tenant', $userTenantContextService->getAvailableDepartmentsByTenant($userId));

if (Request::wantsJson()) {
    Router::json([
        'ok' => true,
        'tenant_id' => $tenantId,
        'tenant' => $result['tenant'] ?? null,
        'theme' => currentTheme(),
    ]);
    return;
}

Router::redirect('admin');
