<?php
namespace Misuzu;

use RuntimeException;

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

$usersCtx = $msz->getUsersContext();
$bans = $usersCtx->getBans();

$filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) {
    $filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
    try {
        $filterUser = $usersCtx->getUserInfo($filterUserId);
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }
}

$pagination = new Pagination($bans->countBans(userInfo: $filterUser), 10);

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

$banList = [];
$banInfos = $bans->getBans(userInfo: $filterUser, activeFirst: true, pagination: $pagination);

foreach($banInfos as $banInfo) {
    $userInfo = $usersCtx->getUserInfo($banInfo->getUserId());
    $userColour = $usersCtx->getUserColour($userInfo);

    if(!$banInfo->hasModId()) {
        $modInfo = null;
        $modColour = null;
    } else {
        $modInfo = $usersCtx->getUserInfo($banInfo->getModId());
        $modColour = $usersCtx->getUserColour($modInfo);
    }

    $banList[] = [
        'info' => $banInfo,
        'user' => $userInfo,
        'user_colour' => $userColour,
        'mod' => $modInfo,
        'mod_colour' => $modColour,
    ];
}

Template::render('manage.users.bans', [
    'manage_bans' => $banList,
    'manage_bans_pagination' => $pagination,
    'manage_bans_filter_user' => $filterUser,
]);
