<?php
namespace Misuzu;

use RuntimeException;

$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
    Template::throwError(403);

// TODO: restore forum-topics and forum-posts orderings

$forumCtx = $msz->getForumContext();
$usersCtx = $msz->getUsersContext();
$users = $usersCtx->getUsers();
$roles = $usersCtx->getRoles();

$roleId = filter_has_var(INPUT_GET, 'r') ? (string)filter_input(INPUT_GET, 'r') : null;
$orderBy = strtolower((string)filter_input(INPUT_GET, 'ss'));
$orderDir = strtolower((string)filter_input(INPUT_GET, 'sd'));

$orderDirs = [
    'asc' => 'In Order',
    'desc' => 'Reverse Order',
];

$defaultOrder = 'active';
$orderFields = [
    'id' => [
        'title' => 'User ID',
    ],
    'name' => [
        'title' => 'Username',
    ],
    'country' => [
        'title' => 'Country',
    ],
    'created' => [
        'title' => 'Registration Date',
    ],
    'active' => [
        'title' => 'Last Online',
    ],
    'registered' => [
        'alt' => 'created',
        'title' => 'Registration Date',
    ],
    'last-online' => [
        'alt' => 'active',
        'title' => 'Last Online',
    ],
];

if(empty($orderBy)) {
    $orderBy = $defaultOrder;
} elseif(!array_key_exists($orderBy, $orderFields)) {
    Template::throwError(400);
}

if(array_key_exists('alt', $orderFields[$orderBy]))
    $orderBy = $orderFields[$orderBy]['alt'];

if(empty($orderDir)) {
    $orderDir = 'asc';
} elseif(!array_key_exists($orderDir, $orderDirs)) {
    Template::throwError(400);
}

if($roleId === null) {
    $roleInfo = $roles->getDefaultRole();
} else {
    try {
        $roleInfo = $roles->getRole($roleId);
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }
}

$canManageUsers = $authInfo->getPerms('user')->check(Perm::U_USERS_MANAGE);
$deleted = $canManageUsers ? null : false;

$rolesAll = $roles->getRoles(hidden: false);
$pagination = new Pagination($users->countUsers(roleInfo: $roleInfo, deleted: $deleted), 15);

$userList = [];
$userInfos = $users->getUsers(
    roleInfo: $roleInfo,
    deleted: $deleted,
    orderBy: $orderBy,
    reverseOrder: $orderDir !== 'asc',
    pagination: $pagination,
);

foreach($userInfos as $userInfo)
    $userList[] = [
        'info' => $userInfo,
        'colour' => $usersCtx->getUserColour($userInfo),
        'ftopics' => $forumCtx->countTotalUserTopics($userInfo),
        'fposts' => $forumCtx->countTotalUserPosts($userInfo),
    ];

if(empty($userList))
    http_response_code(404);

Template::render('user.listing', [
    'roles' => $rolesAll,
    'role' => $roleInfo,
    'users' => $userList,
    'order_fields' => $orderFields,
    'order_directions' => $orderDirs,
    'order_field' => $orderBy,
    'order_direction' => $orderDir,
    'order_default' => $defaultOrder,
    'can_manage_users' => $canManageUsers,
    'users_pagination' => $pagination,
]);
