<?php

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\Access\UserAuthorizationPolicy;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbilityOrForbidden(UserAuthorizationPolicy::ABILITY_ADMIN_USERS_VIEW);

gridRequireGetRequest();

$userAccountService = app(\MintyPHP\Service\User\UserAccountService::class);
$userAvatarService = app(\MintyPHP\Service\User\UserAvatarService::class);

$currentUserId = (int) ($session['user']['id'] ?? 0);

$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');

$result = $userAccountService->listPaged([
    'limit' => $filters['limit'],
    'offset' => $filters['offset'],
    'search' => $filters['search'],
    'order' => $filters['order'],
    'dir' => $filters['dir'],
    'active' => $filters['active'],
    'created_from' => $filters['created_from'],
    'created_to' => $filters['created_to'],
    'tenant' => $filters['tenant'],
    'roles' => $filters['roles'],
    'departments' => $filters['departments'],
    'email_verified' => $filters['email_verified'],
    'login_status' => $filters['login_status'],
    'tenantUserId' => $currentUserId,
]);

$rows = [];
foreach ($result['rows'] as $row) {
    $tenantList = gridNormalizeLabelList($row['tenant_labels'] ?? []);
    $roleList = gridNormalizeLabelList($row['role_labels'] ?? []);
    $departmentList = gridNormalizeLabelList($row['department_labels'] ?? []);
    $primaryTenantLabel = (string) ($row['primary_tenant_label'] ?? '');
    if ($primaryTenantLabel === '' && count($tenantList) === 1) {
        $primaryTenantLabel = (string) $tenantList[0];
    }
    $uuid = (string) ($row['uuid'] ?? '');
    $rows[] = [
        'id' => $row['id'] ?? null,
        'uuid' => $uuid,
        'first_name' => $row['first_name'] ?? '',
        'last_name' => $row['last_name'] ?? '',
        'email' => $row['email'] ?? '',
        'phone' => $row['phone'] ?? '',
        'mobile' => $row['mobile'] ?? '',
        'short_dial' => $row['short_dial'] ?? '',
        'tenants' => [
            'items' => $tenantList,
            'primary' => $primaryTenantLabel,
        ],
        'departments' => $departmentList,
        'roles' => $roleList,
        'created' => dt($row['created'] ?? ''),
        'modified' => dt($row['modified'] ?? ''),
        'last_login' => dt($row['last_login_at'] ?? ''),
        'active' => (int) ($row['active'] ?? 0),
        'has_avatar' => $uuid !== '' && $userAvatarService->hasAvatar($uuid),
    ];
}

gridJsonDataResult($rows, (int) ($result['total'] ?? 0));
