<?php

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

Guard::requireLogin();
Guard::requirePermission(PermissionService::ROLES_VIEW);

$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');
$active = (string) ($_GET['active'] ?? '');

$result = directoryServicesFactory()->createRoleService()->listPaged([
    'limit' => $limit,
    'offset' => $offset,
    'search' => $search,
    'order' => $order,
    'dir' => $dir,
    'active' => $active,
]);

$settingsFactory = new SettingServicesFactory();
$settingGateway = $settingsFactory->createSettingGateway();
$defaultRoleId = $settingGateway->getDefaultRoleId();
$rolePermissionRepository = (new AccessServicesFactory())->createRolePermissionRepository();
$roleIds = [];
foreach ($result['rows'] as $roleRow) {
    $roleId = (int) ($roleRow['id'] ?? 0);
    if ($roleId > 0) {
        $roleIds[] = $roleId;
    }
}
$roleIds = array_values(array_unique($roleIds));
$userRoleRepository = (new UserServicesFactory())->createUserRoleRepository();
$roleUserCounts = $userRoleRepository->countUsersByRoleIds($roleIds);
$roleActiveUserCounts = $userRoleRepository->countActiveUsersByRoleIds($roleIds);
$rolePermissionCounts = $rolePermissionRepository->countPermissionsByRoleIds($roleIds);

$rows = [];
foreach ($result['rows'] as $row) {
    $roleId = (int) ($row['id'] ?? 0);
    $usersTotal = (int) ($roleUserCounts[$roleId] ?? 0);
    $usersActive = (int) ($roleActiveUserCounts[$roleId] ?? 0);
    $usersInactive = max(0, $usersTotal - $usersActive);
    $rows[] = [
        'id' => $row['id'] ?? null,
        'uuid' => $row['uuid'] ?? '',
        'is_default' => $roleId > 0 && $defaultRoleId === $roleId,
        'description' => $row['description'] ?? '',
        'code' => $row['code'] ?? '',
        'active' => (int) ($row['active'] ?? 1),
        'active_users' => $usersActive,
        'inactive_users' => $usersInactive,
        'permission_count' => (int) ($rolePermissionCounts[$roleId] ?? 0),
        'created' => dt($row['created'] ?? ''),
        'modified' => dt($row['modified'] ?? ''),
    ];
}

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