<?php

use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

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

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$allowedTenantIds = directoryServicesFactory()->createDirectoryScopeGateway()->getUserTenantIds($currentUserId);
if (directoryServicesFactory()->createDirectoryScopeGateway()->isStrict() && !$allowedTenantIds) {
    Router::redirect('error/forbidden');
    return;
}

$errors = [];
$warnings = [];
$form = [
    'description' => '',
    'tenant_id' => 0,
    'code' => '',
    'cost_center' => '',
    'active' => '1',
];
$tenants = directoryServicesFactory()->createTenantService()->list();
if ($allowedTenantIds) {
    $tenants = array_values(array_filter($tenants, static function (array $tenant) use ($allowedTenantIds): bool {
        $tenantId = (int) ($tenant['id'] ?? 0);
        return $tenantId > 0 && in_array($tenantId, $allowedTenantIds, true);
    }));
} elseif (directoryServicesFactory()->createDirectoryScopeGateway()->isStrict()) {
    $tenants = [];
}

if (isset($_POST['description'])) {
    $selectedTenantId = (int) ($_POST['tenant_id'] ?? 0);
    $selectedTenantIds = directoryServicesFactory()->createDirectoryScopeGateway()->filterTenantIdsForUser([$selectedTenantId], $currentUserId);
    $selectedTenantId = (int) ($selectedTenantIds[0] ?? 0);
    $input = $_POST;
    $input['tenant_id'] = $selectedTenantId;

    $result = directoryServicesFactory()->createDepartmentService()->createFromAdmin($input, $currentUserId);
    $form = $result['form'] ?? $form;
    $errors = $result['errors'] ?? [];
    $warnings = $result['warnings'] ?? [];
    $form['tenant_id'] = $selectedTenantId;

    if (($result['ok'] ?? false) && !$errors) {
        $action = (string) ($_POST['action'] ?? 'create');
        if ($action === 'create_close') {
            if ($warnings) {
                Flash::info(implode(' ', $warnings), 'admin/departments', 'department_warning');
            }
            Flash::success('Department created', 'admin/departments', 'department_created');
            Router::redirect('admin/departments');
        } else {
            $uuid = (string) ($result['uuid'] ?? '');
            if ($uuid !== '') {
                $target = "admin/departments/edit/{$uuid}";
                if ($warnings) {
                    Flash::info(implode(' ', $warnings), $target, 'department_warning');
                }
                Flash::success('Department created', $target, 'department_created');
                Router::redirect($target);
            } else {
                if ($warnings) {
                    Flash::info(implode(' ', $warnings), 'admin/departments', 'department_warning');
                }
                Flash::success('Department created', 'admin/departments', 'department_created');
                Router::redirect('admin/departments');
            }
        }
    }
}

Buffer::set('title', t('Create department'));
