<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Settings\SettingServicesFactory;
use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Guard;

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

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);
$tenantIds = directoryServicesFactory()->createDirectoryScopeGateway()->getUserTenantIds($currentUserId);

$limit = (int) ($_GET['limit'] ?? 10);
$offset = (int) ($_GET['offset'] ?? 0);
$search = trim((string) ($_GET['search'] ?? ''));
$order = (string) ($_GET['order'] ?? 'description');
$dir = (string) ($_GET['dir'] ?? 'asc');
$tenant = trim((string) ($_GET['tenant'] ?? ''));
$active = trim((string) ($_GET['active'] ?? ''));

$result = directoryServicesFactory()->createDepartmentService()->listPaged([
    'limit' => $limit,
    'offset' => $offset,
    'search' => $search,
    'order' => $order,
    'dir' => $dir,
    'tenant' => $tenant,
    'active' => $active,
    'tenantIds' => $tenantIds,
    'tenantUserId' => $currentUserId,
]);

$settingsFactory = new SettingServicesFactory();
$settingGateway = $settingsFactory->createSettingGateway();
$defaultDepartmentId = $settingGateway->getDefaultDepartmentId();
$departmentIds = [];
foreach ($result['rows'] as $departmentRow) {
    $departmentId = (int) ($departmentRow['id'] ?? 0);
    if ($departmentId > 0) {
        $departmentIds[] = $departmentId;
    }
}
$departmentIds = array_values(array_unique($departmentIds));
$userDepartmentRepository = (new UserServicesFactory())->createUserDepartmentRepository();
$departmentUserCounts = $userDepartmentRepository->countUsersByDepartmentIds($departmentIds);
$departmentActiveUserCounts = $userDepartmentRepository->countActiveUsersByDepartmentIds($departmentIds);

$rows = [];
foreach ($result['rows'] as $row) {
    $departmentId = (int) ($row['id'] ?? 0);
    $usersTotal = (int) ($departmentUserCounts[$departmentId] ?? 0);
    $usersActive = (int) ($departmentActiveUserCounts[$departmentId] ?? 0);
    $usersInactive = max(0, $usersTotal - $usersActive);
    $rows[] = [
        'id' => $row['id'] ?? null,
        'uuid' => $row['uuid'] ?? '',
        'is_default' => $departmentId > 0 && $defaultDepartmentId === $departmentId,
        'description' => $row['description'] ?? '',
        'code' => $row['code'] ?? '',
        'cost_center' => $row['cost_center'] ?? '',
        'active' => $row['active'] ?? 1,
        'active_users' => $usersActive,
        'inactive_users' => $usersInactive,
        'tenants' => $row['tenant_labels'] ?? [],
        'created' => dt($row['created'] ?? ''),
        'modified' => dt($row['modified'] ?? ''),
    ];
}

Router::json([
    'data' => $rows,
    'total' => $result['total'] ?? 0,
]);
