<?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::DEPARTMENTS_DELETE);

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

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$department = $uuid !== '' ? directoryServicesFactory()->createDepartmentService()->findByUuid($uuid) : null;
if ($department && !directoryServicesFactory()->createDirectoryScopeGateway()->canAccess('departments', (int) ($department['id'] ?? 0), $currentUserId)) {
    Router::redirect('error/forbidden');
    return;
}

$result = directoryServicesFactory()->createDepartmentService()->deleteByUuid($uuid);
if (!($result['ok'] ?? false)) {
    Flash::error('Department not found', 'admin/departments', 'department_not_found');
    Router::redirect('admin/departments');
}

if ($currentUserId > 0) {
    (new AuthServicesFactory())->createAuthService()->loadTenantDataIntoSession($currentUserId);
}

Flash::success('Department deleted', 'admin/departments', 'department_deleted');
Router::redirect('admin/departments');
