<?php
namespace Misuzu;

use stdClass;
use RuntimeException;
use Index\XArray;
use Misuzu\Comments\CommentsCategory;

$authInfo = $msz->getAuthInfo();
if(!$authInfo->isLoggedIn())
    Template::throwError(403);

$searchQuery = !empty($_GET['q']) && is_string($_GET['q']) ? $_GET['q'] : '';

$searchQueryEvaluated = ['query' => []];
Template::addFunction('search_merge_query', function($attrs) use (&$searchQueryEvaluated) {
    $existing = [];

    if(!empty($attrs['type']))
        $existing[] = 'type:' . $attrs['type'];
    elseif(!empty($searchQueryEvaluated['type']))
        $existing[] = 'type:' . $searchQueryEvaluated['type'];

    if(!empty($attrs['author']))
        $existing[] = 'author:' . $attrs['author'];
    elseif(!empty($searchQueryEvaluated['author']))
        $existing[] = 'author:' . $searchQueryEvaluated['author']->getName();

    if(!empty($attrs['after']))
        $existing[] = 'after:' . $attrs['after'];
    elseif(!empty($searchQueryEvaluated['after']))
        $existing[] = 'after:' . $searchQueryEvaluated['after'];

    $existing = array_merge($existing, array_unique(array_merge(
        $searchQueryEvaluated['query'],
        empty($attrs['query']) ? [] : explode(' ', $attrs['query'])
    )));

    return rawurlencode(implode(' ', $existing));
});
if(!empty($searchQuery)) {
    $usersCtx = $msz->getUsersContext();
    $users = $usersCtx->getUsers();
    $forumCtx = $msz->getForumContext();
    $forumCategories = $forumCtx->getCategories();
    $forumTopics = $forumCtx->getTopics();
    $forumPosts = $forumCtx->getPosts();
    $news = $msz->getNews();
    $comments = $msz->getComments();

    $searchQueryAttributes = ['type', 'author', 'after'];
    $searchQueryParts = explode(' ', $searchQuery);
    foreach($searchQueryParts as $queryPart) {
        $queryPart = trim($queryPart);
        if($queryPart === '')
            continue;

        $colonIndex = strpos($queryPart, ':');
        if($colonIndex !== false && $colonIndex > 0) {
            $attrName = substr($queryPart, 0, $colonIndex);
            if(in_array($attrName, $searchQueryAttributes)) {
                $attrValue = substr($queryPart, $colonIndex + 1);
                $searchQueryEvaluated[$attrName] = $attrValue;
                continue;
            }
        }

        $searchQueryEvaluated['query'][] = $queryPart;
    }

    $searchQueryEvaluated['query_string'] = implode(' ', $searchQueryEvaluated['query']);

    if(!empty($searchQueryEvaluated['author']))
        try {
            $searchQueryEvaluated['author'] = $usersCtx->getUserInfo($searchQueryEvaluated['author'], 'search');
        } catch(RuntimeException $ex) {
            unset($searchQueryEvaluated['author']);
        }

    if(empty($searchQueryEvaluated['type']) || str_starts_with($searchQueryEvaluated['type'], 'forum')) {
        $currentUser = $authInfo->getUserInfo();
        $currentUserId = $currentUser === null ? 0 : (int)$currentUser->getId();

        $forumCategoryIds = XArray::where(
            $forumCategories->getCategories(hidden: false),
            fn($categoryInfo) => $categoryInfo->mayHaveTopics() && $authInfo->getPerms('forum', $categoryInfo)->check(Perm::F_CATEGORY_VIEW)
        );

        $forumTopicInfos = $forumTopics->getTopics(categoryInfo: $forumCategoryIds, deleted: false, searchQuery: $searchQueryEvaluated);
        $ftopics = [];

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

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

            try {
                $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(), 'id');
                    $topic->lastPost->colour = $usersCtx->getUserColour($topic->lastPost->user);
                }
            } catch(RuntimeException $ex) {}
        }

        $forumPostInfos = $forumPosts->getPosts(categoryInfo: $forumCategoryIds, searchQuery: $searchQueryEvaluated);
        $fposts = [];

        foreach($forumPostInfos as $postInfo) {
            $fposts[] = $post = new stdClass;
            $post->info = $postInfo;

            if($postInfo->hasUserId()) {
                $post->user = $usersCtx->getUserInfo($postInfo->getUserId(), 'id');
                $post->colour = $usersCtx->getUserColour($post->user);
                $post->postsCount = $forumCtx->countTotalUserPosts($post->user);
            }

            // can't be bothered sorry
            $post->isOriginalPost = false;
            $post->isOriginalPoster = false;
        }
    }

    $newsPosts = [];
    $newsPostInfos = empty($searchQueryEvaluated['type']) || $searchQueryEvaluated['type'] === 'news' ? $news->getPosts(searchQuery: $searchQuery) : [];
    $newsCategoryInfos = [];

    foreach($newsPostInfos as $postInfo) {
        $userId = $postInfo->getUserId();
        $categoryId = $postInfo->getCategoryId();
        $userInfo = $postInfo->hasUserId() ? $usersCtx->getUserInfo($postInfo->getUserId()) : null;
        $userColour = $usersCtx->getUserColour($userInfo);

        if(array_key_exists($categoryId, $newsCategoryInfos))
            $categoryInfo = $newsCategoryInfos[$categoryId];
        else
            $newsCategoryInfos[$categoryId] = $categoryInfo = $news->getCategory(postInfo: $postInfo);

        $commentsCount = $postInfo->hasCommentsCategoryId()
            ? $comments->countPosts(categoryInfo: $postInfo->getCommentsCategoryId(), deleted: false) : 0;

        $newsPosts[] = [
            'post' => $postInfo,
            'category' => $categoryInfo,
            'user' => $userInfo,
            'user_colour' => $userColour,
            'comments_count' => $commentsCount,
        ];
    }

    $members = [];
    $memberInfos = $users->getUsers(searchQuery: $searchQueryEvaluated);

    foreach($memberInfos as $memberInfo) {
        $members[] = $member = new stdClass;
        $member->info = $memberInfo;
        $member->colour = $usersCtx->getUserColour($memberInfo);
        $member->ftopics = $forumCtx->countTotalUserTopics($memberInfo);
        $member->fposts = $forumCtx->countTotalUserPosts($memberInfo);
    }
}

Template::render('home.search', [
    'search_query' => $searchQuery,
    'forum_topics' => $ftopics ?? [],
    'forum_posts' => $fposts ?? [],
    'members' => $members ?? [],
    'news_posts' => $newsPosts ?? [],
]);