<?php
namespace Misuzu;

use stdClass;
use RuntimeException;

$forumCtx = $msz->getForumContext();
$forumCategories = $forumCtx->getCategories();
$forumTopics = $forumCtx->getTopics();
$forumPosts = $forumCtx->getPosts();
$usersCtx = $msz->getUsersContext();

$categoryId = (int)filter_input(INPUT_GET, 'f', FILTER_SANITIZE_NUMBER_INT);

try {
    $categoryInfo = $forumCategories->getCategory(categoryId: $categoryId);
} catch(RuntimeException $ex) {
    Template::throwError(404);
}

$authInfo = $msz->getAuthInfo();
$perms = $authInfo->getPerms('forum', $categoryInfo);

$currentUser = $authInfo->getUserInfo();
$currentUserId = $currentUser === null ? '0' : $currentUser->getId();

if(!$perms->check(Perm::F_CATEGORY_VIEW))
    Template::throwError(403);

if($usersCtx->hasActiveBan($currentUser))
    $perms = $perms->apply(fn($calc) => $calc & (Perm::F_CATEGORY_LIST | Perm::F_CATEGORY_VIEW));

if($categoryInfo->isLink()) {
    if($categoryInfo->hasLinkTarget()) {
        $forumCategories->incrementCategoryClicks($categoryInfo);
        Tools::redirect($categoryInfo->getLinkTarget());
        return;
    }

    Template::throwError(404);
}

$forumPagination = new Pagination($forumTopics->countTopics(
    categoryInfo: $categoryInfo,
    global: true,
    deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false
), 20);

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

$children = [];
$topics = [];

if($categoryInfo->mayHaveChildren()) {
    $children = $forumCategories->getCategoryChildren($categoryInfo, hidden: false, asTree: true);

    foreach($children as $childId => $child) {
        $childPerms = $authInfo->getPerms('forum', $child->info);
        if(!$childPerms->check(Perm::F_CATEGORY_LIST)) {
            unset($category->children[$childId]);
            continue;
        }

        $childUnread = false;

        if($child->info->mayHaveChildren()) {
            foreach($child->children as $grandChildId => $grandChild) {
                $grandChildPerms = $authInfo->getPerms('forum', $grandChild->info);
                if(!$grandChildPerms->check(Perm::F_CATEGORY_LIST)) {
                    unset($child->children[$grandChildId]);
                    continue;
                }

                $grandChildUnread = false;

                if($grandChild->info->mayHaveTopics()) {
                    $catIds = [$grandChild->info->getId()];
                    foreach($grandChild->childIds as $greatGrandChildId) {
                        $greatGrandChildPerms = $authInfo->getPerms('forum', $greatGrandChildId);
                        if(!$greatGrandChildPerms->check(Perm::F_CATEGORY_LIST))
                            $catIds[] = $greatGrandChildId;
                    }

                    $grandChildUnread = $forumCategories->checkCategoryUnread($catIds, $currentUser);
                    if($grandChildUnread)
                        $childUnread = true;
                }

                $grandChild->perms = $grandChildPerms;
                $grandChild->unread = $grandChildUnread;
            }
        }

        if($child->info->mayHaveChildren() || $child->info->mayHaveTopics()) {
            $catIds = [$child->info->getId()];
            foreach($child->childIds as $grandChildId) {
                $grandChildPerms = $authInfo->getPerms('forum', $grandChildId);
                if($grandChildPerms->check(Perm::F_CATEGORY_LIST))
                    $catIds[] = $grandChildId;
            }

            try {
                $lastPostInfo = $forumPosts->getPost(categoryInfos: $catIds, getLast: true, deleted: false);
            } catch(RuntimeException $ex) {
                $lastPostInfo = null;
            }

            if($lastPostInfo !== null) {
                $child->lastPost = new stdClass;
                $child->lastPost->info = $lastPostInfo;
                $child->lastPost->topicInfo = $forumTopics->getTopic(postInfo: $lastPostInfo);

                if($lastPostInfo->hasUserId()) {
                    $child->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
                    $child->lastPost->colour = $usersCtx->getUserColour($child->lastPost->user);
                }
            }
        }

        if($child->info->mayHaveTopics() && !$childUnread)
            $childUnread = $forumCategories->checkCategoryUnread($child->info, $currentUser);

        $child->perms = $childPerms;
        $child->unread = $childUnread;
    }
}

if($categoryInfo->mayHaveTopics()) {
    $topicInfos = $forumTopics->getTopics(
        categoryInfo: $categoryInfo,
        global: true,
        deleted: $perms->check(Perm::F_POST_DELETE_ANY) ? null : false,
        pagination: $forumPagination,
    );

    foreach($topicInfos as $topicInfo) {
        $topics[] = $topic = new stdClass;
        $topic->info = $topicInfo;
        $topic->unread = $forumTopics->checkTopicUnread($topicInfo, $currentUser);
        $topic->participated = $forumTopics->checkTopicParticipated($topicInfo, $currentUser);

        if($topicInfo->hasUserId()) {
            $topic->user = $usersCtx->getUserInfo($topicInfo->getUserId());
            $topic->colour = $usersCtx->getUserColour($topic->user);
        }

        try {
            $topic->lastPost = new stdClass;
            $topic->lastPost->info = $lastPostInfo = $forumPosts->getPost(
                topicInfo: $topicInfo,
                getLast: true,
                deleted: $topicInfo->isDeleted() ? null : false,
            );

            if($lastPostInfo->hasUserId()) {
                $topic->lastPost->user = $usersCtx->getUserInfo($lastPostInfo->getUserId());
                $topic->lastPost->colour = $usersCtx->getUserColour($topic->lastPost->user);
            }
        } catch(RuntimeException $ex) {
            $topic->lastPost = null;
        }
    }
}

$perms = $perms->checkMany([
    'can_create_topic' => Perm::F_TOPIC_CREATE,
]);

Template::render('forum.forum', [
    'forum_breadcrumbs' => $forumCategories->getCategoryAncestry($categoryInfo),
    'global_accent_colour' => $forumCategories->getCategoryColour($categoryInfo),
    'forum_info' => $categoryInfo,
    'forum_children' => $children,
    'forum_topics' => $topics,
    'forum_pagination' => $forumPagination,
    'forum_show_mark_as_read' => $currentUser !== null,
    'forum_perms' => $perms,
]);
