<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::TENANTS_DELETE);

$uuid = trim((string) ($id ?? ''));
if ($uuid === '') {
    Router::redirect('admin/tenants');
}

$result = directoryServicesFactory()->createTenantService()->deleteByUuid($uuid);
if (!($result['ok'] ?? false)) {
    if (($result['error'] ?? '') === 'tenant_has_departments') {
        Flash::error('Tenant can not be deleted while departments are assigned', 'admin/tenants', 'tenant_has_departments');
        Router::redirect('admin/tenants');
    }
    Flash::error('Tenant not found', 'admin/tenants', 'tenant_not_found');
    Router::redirect('admin/tenants');
}

// Refresh session tenant data (removes deleted tenant, switches if it was current)
$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
if ($currentUserId > 0) {
    (new AuthServicesFactory())->createAuthService()->loadTenantDataIntoSession($currentUserId);
}

Flash::success('Tenant deleted', 'admin/tenants', 'tenant_deleted');
Router::redirect('admin/tenants');
