<?php
namespace Misuzu;

use RuntimeException;
use Misuzu\Users\User;

if(!User::hasCurrent() || !perms_check_user(MSZ_PERMS_CHANGELOG, User::getCurrent()->getId(), MSZ_PERM_CHANGELOG_MANAGE_CHANGES)) {
    echo render_error(403);
    return;
}

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

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

$changeInfos = $changelog->getAllChanges(withTags: true, pagination: $changelogPagination);
$changes = [];
$userInfos = [];

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

    if(array_key_exists($userId, $userInfos)) {
        $userInfo = $userInfos[$userId];
    } else {
        try {
            $userInfo = User::byId($userId);
        } catch(RuntimeException $ex) {
            $userInfo = null;
        }

        $userInfos[$userId] = $userInfo;
    }

    $changes[] = [
        'change' => $changeInfo,
        'user' => $userInfo,
    ];
}

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