<?php
namespace Misuzu;

if(!$msz->getAuthInfo()->getPerms('user')->check(Perm::U_USERS_MANAGE))
    Template::throwError(403);

$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();
$pagination = new Pagination($users->countUsers(), 30);

if(!$pagination->hasValidOffset())
    Template::throwError(404);

$userList = [];
$userInfos = $users->getUsers(pagination: $pagination, orderBy: 'id');
$roleInfos = [];

foreach($userInfos as $userInfo) {
    $displayRoleId = $userInfo->getDisplayRoleId() ?? '1';
    if(array_key_exists($displayRoleId, $roleInfos))
        $roleInfo = $roleInfos[$displayRoleId];
    else
        $roleInfos[$displayRoleId] = $roleInfo = $roles->getRole($displayRoleId);

    $colour = $userInfo->hasColour() ? $userInfo->getColour() : $roleInfo->getColour();

    $userList[] = [
        'info' => $userInfo,
        'role' => $roleInfo,
        'colour' => $colour,
    ];
}

Template::render('manage.users.users', [
    'manage_users' => $userList,
    'manage_users_pagination' => $pagination,
]);
