<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Access\DepartmentAuthorizationPolicy;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
$request = requestInput();
$returnTarget = requestResolveReturnTarget();
$closeTarget = requestResolveReturnTarget('admin/departments');
$authorizationService = app(\MintyPHP\Service\Access\AuthorizationService::class);

$currentUserId = (int) ($session['user']['id'] ?? 0);
if ($currentUserId > 0) {
    app(\MintyPHP\Service\Access\PermissionService::class)->getUserPermissions($currentUserId);
}
$departmentService = app(\MintyPHP\Service\Org\DepartmentService::class);
$tenantService = app(\MintyPHP\Service\Tenant\TenantService::class);
$directoryScopeGateway = app(\MintyPHP\Service\Tenant\TenantScopeService::class);

$uuid = trim((string) ($id ?? ''));
$editTarget = requestPathWithReturnTarget("admin/departments/edit/{$uuid}", $returnTarget);
$department = $uuid !== '' ? $departmentService->findByUuid($uuid) : null;
if (!$department) {
    Flash::error('Department not found', $closeTarget, 'department_not_found');
    Router::redirect($closeTarget);
}

$departmentId = (int) ($department['id'] ?? 0);
$contextDecision = $authorizationService->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_CONTEXT, [
    'actor_user_id' => $currentUserId,
    'target_department_id' => $departmentId,
]);
if (!$contextDecision->isAllowed()) {
    Router::redirect('error/forbidden');
    return;
}

$capabilities = $contextDecision->attribute('capabilities', []);
if (!is_array($capabilities)) {
    $capabilities = [];
}
$canViewPage = (bool) ($capabilities['can_view_page'] ?? false);
$canUpdateDepartment = (bool) ($capabilities['can_update_department'] ?? false);
$canDeleteDepartment = (bool) ($capabilities['can_delete_department'] ?? false);
$viewAuth['page'] = [
    'can_update_department' => $canUpdateDepartment,
    'can_delete_department' => $canDeleteDepartment,
];
$allowedTenantIdsRaw = $capabilities['allowed_tenant_ids'] ?? [];
$allowedTenantIds = is_array($allowedTenantIdsRaw)
    ? array_values(array_unique(array_filter(array_map('intval', $allowedTenantIdsRaw), static fn (int $tenantId): bool => $tenantId > 0)))
    : [];
if (!$canViewPage) {
    Router::redirect('error/forbidden');
    return;
}

app(\MintyPHP\Service\Audit\AuditMetadataEnricher::class)->enrich($department);

$errorBag = formErrors();
$errors = [];
$warnings = [];
$form = $department;
$tenants = $tenantService->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);
    }));
    if (!in_array((int) ($form['tenant_id'] ?? 0), $allowedTenantIds, true)) {
        $form['tenant_id'] = 0;
    }
} elseif ($directoryScopeGateway->isStrict()) {
    $tenants = [];
    $form['tenant_id'] = 0;
}

if ($request->isMethod('POST') && !Session::checkCsrfToken()) {
    Flash::error(t('Form expired, please try again'), $editTarget, 'csrf_expired');
    Router::redirect($editTarget);
    return;
}

if ($request->hasBody('description')) {
    $submitDecision = $authorizationService->authorize(DepartmentAuthorizationPolicy::ABILITY_ADMIN_DEPARTMENTS_EDIT_SUBMIT, [
        'actor_user_id' => $currentUserId,
        'target_department_id' => $departmentId,
        'input' => $request->bodyAll(),
    ]);
    if (!$submitDecision->isAllowed()) {
        Router::redirect('error/forbidden');
        return;
    }

    $submitCapabilities = $submitDecision->attribute('capabilities', []);
    if (is_array($submitCapabilities)) {
        $canUpdateDepartment = (bool) ($submitCapabilities['can_update_department'] ?? $canUpdateDepartment);
        $canDeleteDepartment = (bool) ($submitCapabilities['can_delete_department'] ?? $canDeleteDepartment);
        $viewAuth['page'] = [
            'can_update_department' => $canUpdateDepartment,
            'can_delete_department' => $canDeleteDepartment,
        ];
    }
    if (!$canUpdateDepartment) {
        Router::redirect('error/forbidden');
        return;
    }

    $selectedTenantId = $request->bodyInt('tenant_id');
    if ($allowedTenantIds) {
        $selectedTenantId = in_array($selectedTenantId, $allowedTenantIds, true) ? $selectedTenantId : 0;
    } elseif ($directoryScopeGateway->isStrict()) {
        $selectedTenantId = 0;
    }
    $input = $request->bodyAll();
    $input['tenant_id'] = $selectedTenantId;

    $result = $departmentService->updateFromAdmin($departmentId, $input, $currentUserId);
    $form = $result['form'] ?? $form;
    $errorBag->merge($result['errors'] ?? []);
    $warnings = $result['warnings'] ?? [];
    $form['tenant_id'] = $selectedTenantId;

    if (($result['ok'] ?? false) && !$errorBag->hasAny()) {
        $cleaned = $departmentService->cleanupUserAssignments($departmentId);
        $action = (string) $request->body('action', 'save');
        if ($cleaned > 0) {
            Flash::info(t('Department assignments cleaned: %d', $cleaned), $editTarget, 'department_assignments_cleaned');
        }
        if ($action === 'save_close') {
            if ($warnings) {
                Flash::info(implode(' ', $warnings), $closeTarget, 'department_warning');
            }
            Flash::success('Department updated', $closeTarget, 'department_updated');
            Router::redirect($closeTarget);
        } else {
            if ($warnings) {
                Flash::info(implode(' ', $warnings), $editTarget, 'department_warning');
            }
            Flash::success('Department updated', $editTarget, 'department_updated');
            Router::redirect($editTarget);
        }
    }
}

$validationSummaryErrors = $errorBag->toArray();
$errors = $errorBag->toFlatList();
Buffer::set('title', t('Edit department'));
