<?php

use MintyPHP\Http\Request;
use MintyPHP\Router;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Session;
use MintyPHP\Support\Guard;

Guard::requireLogin();
$userTenantContextService = (new UserServicesFactory())->createUserTenantContextService();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    Router::redirect('admin');
    return;
}

if (!Session::checkCsrfToken()) {
    if (Request::wantsJson()) {
        http_response_code(400);
        Router::json(['ok' => false, 'error' => 'csrf']);
        return;
    }
    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) ($_POST['tenant_id'] ?? 0);

if ($tenantId <= 0) {
    http_response_code(400);
    if (Request::wantsJson()) {
        Router::json(['ok' => false, 'error' => 'invalid_tenant_id']);
        return;
    }
    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;
    }
    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');
