<?php

namespace Main\Controllers\Forum;

use Main\Core\Controller;
use Main\Services\AvatarService;
use Main\Services\SeoService;
use PDO;

class CategoryController extends Controller
{
		protected string $route_type = 'forum';
		
    public function show($id, $slug)
    {
        $category = db()->prepare("SELECT * FROM ForumCategories WHERE id = ?");
        $category->execute(array($id));
        $category = $category->fetch();
				
				if (!$category) abort_404();
				if (!forum()->user()->can($category["id"], "VIEW_FORUM")) abort_404();
	    
		    SeoService::set('forum.categories.show', [
			    'category_name' => $category["name"],
		    ]);
				
				if ($category["parentID"]) {
					$parentCategory = db()->prepare("SELECT * FROM ForumCategories WHERE id = ?");
					$parentCategory->execute(array($category["parentID"]));
					$parentCategory = $parentCategory->fetch();
					
					if (!$parentCategory) abort_404();
					
					$category["parent"] = $parentCategory;
				}
				
        $subcategories = db()->prepare("SELECT * FROM ForumCategories WHERE parentID = ?");
		    $subcategories->execute(array($category["id"]));
		    $category["subcategories"] = array_map(function ($subcategory)  {
			    if (!forum()->user()->can($subcategory["id"], "VIEW_FORUM")) return null;
					
					$subcategory["image"] = "/assets/core/images/forum/categories/" . $subcategory["imageID"] . "." . $subcategory["imageType"];
					
					return $subcategory;
		    }, $subcategories->fetchAll());
				$category["subcategories"] = array_filter($category["subcategories"]);

        if (isset($_GET["page"])) {
            if (!is_numeric($_GET["page"])) {
                $_GET["page"] = 1;
            }
            $page = intval($_GET["page"]);
        } else {
            $page = 1;
        }

        $threadLimit = 20;
        $itemsCount = db()->prepare("SELECT count(id) from ForumThreads WHERE categoryID = ?");
        $itemsCount->execute(array($category["id"]));
        $itemsCount = $itemsCount->fetchColumn();

        $pageCount = ceil($itemsCount / $threadLimit);
        if ($page > $pageCount) {
            $page = 1;
        }
        $visibleItemsCount = $page * $threadLimit - $threadLimit;
        $visiblePageCount = 5;
        $threads = db()->prepare("SELECT FT.*, A.username, A.realname FROM ForumThreads FT INNER JOIN Accounts A ON A.id = FT.accountID WHERE FT.categoryID = ? AND FT.isPinned = ? ORDER BY FT.updatedDate DESC LIMIT $visibleItemsCount, $threadLimit");
        $threads->execute(array($category["id"], 0));
        $threads = array_map(function ($thread) {
						$thread["user"] = [
							'id' => $thread['accountID'],
							'username' => $thread['username'],
							'displayName' => $thread['realname'],
							'avatar' => AvatarService::get($thread['accountID'], $thread['realname'])
						];
						
						return $thread;
				}, $threads->fetchAll());
				
        $pinnedThreads = [];

        if ($itemsCount > 0) {
            $pinnedThreads = db()->prepare("SELECT FT.*, A.username, A.realname FROM ForumThreads FT INNER JOIN Accounts A ON A.id = FT.accountID WHERE FT.categoryID = ? AND FT.isPinned = ? ORDER BY FT.updatedDate DESC");
            $pinnedThreads->execute(array($category["id"], 1));
            $pinnedThreads = array_map(function ($thread) {
	            $thread["user"] = [
		            'id' => $thread['accountID'],
		            'username' => $thread['username'],
		            'displayName' => $thread['realname'],
		            'avatar' => AvatarService::get($thread['accountID'], $thread['realname'])
	            ];
	            
	            return $thread;
            }, $pinnedThreads->fetchAll());
        }
				
        return $this->view('forum.category', compact('category', 'threads', 'pinnedThreads', 'page', 'pageCount', 'visiblePageCount'));
    }
}