<?php
namespace Misuzu;

use RuntimeException;
use Misuzu\Comments\CommentsCategory;
use Misuzu\Users\User;

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

if(!empty($searchQuery)) {
    $forumTopics = forum_topic_listing_search($searchQuery, User::hasCurrent() ? User::getCurrent()->getId() : 0);
    $forumPosts = forum_post_search($searchQuery);

    // this sure is an expansion
    $news = $msz->getNews();
    $comments = $msz->getComments();
    $newsPosts = [];
    $newsPostInfos = $news->getPostsBySearchQuery($searchQuery);
    $newsUserInfos = [];
    $newsCategoryInfos = [];

    foreach($newsPostInfos as $postInfo) {
        $userId = $postInfo->getUserId();
        $categoryId = $postInfo->getCategoryId();

        if(array_key_exists($userId, $newsUserInfos)) {
            $userInfo = $newsUserInfos[$userId];
        } else {
            try {
                $userInfo = User::byId($userId);
            } catch(RuntimeException $ex) {
                $userInfo = null;
            }

            $newsUserInfos[$userId] = $userInfo;
        }

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

        $commentsCount = $postInfo->hasCommentsCategoryId()
            ? $comments->countPosts($postInfo->getCommentsCategoryId(), includeReplies: true) : 0;

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

    $findUsers = DB::prepare('
        SELECT u.`user_id`, u.`username`, u.`user_country`,
            u.`user_created`, u.`user_active`, r.`role_id`,
            COALESCE(u.`user_title`, r.`role_title`) AS `user_title`,
            COALESCE(u.`user_colour`, r.`role_colour`) AS `user_colour`,
            (
                SELECT COUNT(`topic_id`)
                FROM `msz_forum_topics`
                WHERE `user_id` = u.`user_id`
                AND `topic_deleted` IS NULL
            ) AS `user_count_topics`,
            (
                SELECT COUNT(`post_Id`)
                FROM `msz_forum_posts`
                WHERE `user_id` = u.`user_id`
                AND `post_deleted` IS NULL
            ) AS `user_count_posts`
        FROM `msz_users` AS u
        LEFT JOIN `msz_roles` AS r
        ON r.`role_id` = u.`display_role`
        LEFT JOIN `msz_user_roles` AS ur
        ON ur.`user_id` = u.`user_id`
        WHERE LOWER(u.`username`) LIKE CONCAT("%%", LOWER(:query), "%%")
        GROUP BY u.`user_id`
    ');
    $findUsers->bind('query', $searchQuery);
    $users = $findUsers->fetchAll();
}

Template::render('home.search', [
    'search_query' => $searchQuery,
    'forum_topics' => $forumTopics ?? [],
    'forum_posts' => $forumPosts ?? [],
    'users' => $users ?? [],
    'news_posts' => $newsPosts ?? [],
]);
