<?php
namespace Misuzu;

use RuntimeException;

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

$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) {
        echo render_error(404);
        return;
    }
}

$modNotes = $msz->getModNotes();
$pagination = new Pagination($modNotes->countNotes(userInfo: $filterUser), 10);

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

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

foreach($noteInfos as $noteInfo) {
    if(array_key_exists($noteInfo->getUserId(), $userInfos))
        $userInfo = $userInfos[$noteInfo->getUserId()];
    else
        $userInfos[$noteInfo->getUserId()] = $userInfo = $users->getUser($noteInfo->getUserId(), 'id');

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

    if(!$noteInfo->hasAuthorId()) {
        $authorInfo = null;
        $authorColour = null;
    } else {
        if(array_key_exists($noteInfo->getAuthorId(), $userInfos))
            $authorInfo = $userInfos[$noteInfo->getAuthorId()];
        else
            $userInfos[$noteInfo->getAuthorId()] = $modInfo = $users->getUser($noteInfo->getAuthorId(), 'id');

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