<?php
namespace Misuzu;

use RuntimeException;

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

$usersCtx = $msz->getUsersContext();
$modNotes = $usersCtx->getModNotes();

$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($modNotes->countNotes(userInfo: $filterUser), 10);

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

$notes = [];
$noteInfos = $modNotes->getNotes(userInfo: $filterUser, pagination: $pagination);

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

    if(!$noteInfo->hasAuthorId()) {
        $authorInfo = null;
        $authorColour = null;
    } else {
        $authorInfo = $usersCtx->getUserInfo($noteInfo->getAuthorId());
        $authorColour = $usersCtx->getUserColour($authorInfo);
    }

    $notes[] = [
        'info' => $noteInfo,
        'user' => $userInfo,
        'user_colour' => $userColour,
        'author' => $authorInfo,
        'author_colour' => $authorColour,
    ];
}

Template::render('manage.users.notes', [
    'manage_notes' => $notes,
    'manage_notes_pagination' => $pagination,
    'manage_notes_filter_user' => $filterUser,
]);
