<?php
namespace Misuzu;

use RuntimeException;

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

$changelog = $msz->getChangelog();
$changelogPagination = new Pagination($changelog->countChanges(), 30);

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

$changeInfos = $changelog->getChanges(pagination: $changelogPagination);
$changes = [];
$userInfos = [];
$userColours = [];

foreach($changeInfos as $changeInfo) {
    $userId = $changeInfo->getUserId();

    if(array_key_exists($userId, $userInfos)) {
        $userInfo = $userInfos[$userId];
    } else {
        try {
            $userInfo = $users->getUser($userId, 'id');
            $userColours[$userId] = $users->getUserColour($userInfo);
        } catch(RuntimeException $ex) {
            $userInfo = null;
        }

        $userInfos[$userId] = $userInfo;
    }

    $changes[] = [
        'change' => $changeInfo,
        'tags' => $changelog->getTags(changeInfo: $changeInfo),
        'user' => $userInfo,
        'user_colour' => $userColours[$userId] ?? \Index\Colour\Colour::none(),
    ];
}

Template::render('manage.changelog.changes', [
    'changelog_changes' => $changes,
    'changelog_pagination' => $changelogPagination,
]);
