<?php
namespace Misuzu;

use RuntimeException;

if(!$msz->isLoggedIn()) {
    echo render_error(403);
    return;
}

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

$users = $msz->getUsers();
$roles = $msz->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)) {
    echo render_error(400);
    return;
}

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

if(empty($orderDir)) {
    $orderDir = 'asc';
} elseif(!array_key_exists($orderDir, $orderDirs)) {
    echo render_error(400);
    return;
}

$canManageUsers = perms_check_user(MSZ_PERMS_USER, $msz->getActiveUser()->getId(), MSZ_PERM_USER_MANAGE_USERS);

if($roleId === null) {
    $roleInfo = $roles->getDefaultRole();
} else {
    try {
        $roleInfo = $roles->getRole($roleId);
    } catch(RuntimeException $ex) {
        echo render_error(404);
        return;
    }
}

$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' => $users->getUserColour($userInfo),
        'ftopics' => forum_get_user_topic_count($userInfo),
        'fposts' => forum_get_user_post_count($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,
]);
