<?php
namespace Misuzu;

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

if(!isset($msz) || !($msz instanceof \Misuzu\MisuzuContext))
    die('Script must be called through the Misuzu route dispatcher.');

if(!$msz->authInfo->loggedIn)
    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']->name;

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

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

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

    return implode(' ', $existing);
});
if(!empty($searchQuery)) {
    $searchQueryAttributes = ['type', 'author', 'after', 'topic'];
    $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'] = $msz->usersCtx->getUserInfo($searchQueryEvaluated['author'], 'search');
        } catch(RuntimeException $ex) {
            unset($searchQueryEvaluated['author']);
        }

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

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

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

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

            if($topicInfo->userId !== null) {
                $topic->user = $msz->usersCtx->getUserInfo($topicInfo->userId, 'id');
                $topic->colour = $msz->usersCtx->getUserColour($topic->user);
            }

            try {
                $topic->lastPost->info = $lastPostInfo = $msz->forumCtx->posts->getPost(
                    topicInfo: $topicInfo,
                    getLast: true,
                    deleted: $topicInfo->deleted ? null : false,
                );

                if($lastPostInfo->userId !== null) {
                    $topic->lastPost->user = $msz->usersCtx->getUserInfo($lastPostInfo->userId, 'id');
                    $topic->lastPost->colour = $msz->usersCtx->getUserColour($topic->lastPost->user);
                }
            } catch(RuntimeException $ex) {}
        }

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

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

            if($postInfo->userId !== null) {
                $post->user = $msz->usersCtx->getUserInfo($postInfo->userId, 'id');
                $post->colour = $msz->usersCtx->getUserColour($post->user);
                $post->postsCount = $msz->forumCtx->countTotalUserPosts($post->user);
            }

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

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

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

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

        $commentsCount = $msz->commentsCtx->posts->countPosts(
            categoryName: $postInfo->commentsCategoryName,
            deleted: false,
        );

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

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

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

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