<?php
namespace Misuzu;

use RuntimeException;

if(!$msz->isLoggedIn() || !perms_check_user(MSZ_PERMS_CHANGELOG, $msz->getActiveUser()->getId(), MSZ_PERM_CHANGELOG_MANAGE_CHANGES)) {
    echo render_error(403);
    return;
}

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

if(!$changelogPagination->hasValidOffset()) {
    echo render_error(404);
    return;
}

$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,
]);
