<?php
namespace Misuzu;

use RuntimeException;

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

$users = $msz->getUsers();

$userInfos = [
    $msz->getActiveUser()->getId() => $msz->getActiveUser(),
];
$userColours = [
    $msz->getActiveUser()->getId() => $users->getUserColour($msz->getActiveUser()),
];

$filterUser = null;
if(filter_has_var(INPUT_GET, 'u')) {
    $filterUserId = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_NUMBER_INT);
    try {
        $filterUser = $users->getUser($filterUserId, 'id');
        $userInfos[$filterUserId] = $filterUser;
        $userColours[$filterUserId] = $users->getUserColour($filterUser);
    } catch(RuntimeException $ex) {
        Template::throwError(404);
    }
}

$bans = $msz->getBans();
$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) {
    if(array_key_exists($banInfo->getUserId(), $userInfos))
        $userInfo = $userInfos[$banInfo->getUserId()];
    else
        $userInfos[$banInfo->getUserId()] = $userInfo = $users->getUser($banInfo->getUserId(), 'id');

    if(array_key_exists($userInfo->getId(), $userColours))
        $userColour = $userColours[$userInfo->getId()];
    else
        $userColours[$userInfo->getId()] = $userColour = $users->getUserColour($userInfo);

    if(!$banInfo->hasModId()) {
        $modInfo = null;
        $modColour = null;
    } else {
        if(array_key_exists($banInfo->getModId(), $userInfos))
            $modInfo = $userInfos[$banInfo->getModId()];
        else
            $userInfos[$banInfo->getModId()] = $modInfo = $users->getUser($banInfo->getModId(), 'id');

        if(array_key_exists($modInfo->getId(), $userColours))
            $modColour = $userColours[$modInfo->getId()];
        else
            $userColours[$modInfo->getId()] = $modColour = $users->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,
]);
