<?php

namespace Main\Controllers\Suggestion;

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

class CategoryController extends Controller
{
		protected string $route_type = 'suggestions';
		
    public function show($slug)
    {
        $category = db()->prepare("SELECT * FROM SuggestionCategories WHERE slug = ?");
        $category->execute(array($slug));
        $category = $category->fetch(PDO::FETCH_ASSOC);

        if (!$category) abort_404();
	    
		    SeoService::set('suggestions.categories.show', [
			    'category_name' => $category['name'],
		    ]);

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

        $suggestionLimit = 20;

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

        $pageCount = ceil($itemsCount / $suggestionLimit);
        if ($page > $pageCount) {
            $page = 1;
        }
        $visibleItemsCount = $page * $suggestionLimit - $suggestionLimit;
        $visiblePageCount = 5;
	    
		    switch (get("sort")) {
			    case "recent-activity":
				    $sort = "S.updatedDate";
				    break;
			    case "likes":
				    $sort = "S.likesCount";
				    break;
			    default:
				    $sort = "S.creationDate";
				    break;
		    }

        $suggestions = db()->prepare("SELECT S.*, A.username, A.realname FROM Suggestions S INNER JOIN Accounts A ON A.id = S.accountID WHERE S.categoryID = ? ORDER BY $sort DESC LIMIT $visibleItemsCount, $suggestionLimit");
        $suggestions->execute(array($category["id"]));
		    $suggestions = array_map(function ($suggestion) {
			    $suggestion["user"] = [
				    'id' => $suggestion["accountID"],
				    'username' => $suggestion["username"],
				    'displayName' => $suggestion["realname"],
				    'avatar' => AvatarService::get($suggestion["accountID"], $suggestion["realname"]),
			    ];
			    
			    return $suggestion;
		    }, $suggestions->fetchAll(PDO::FETCH_ASSOC));
				
        $categories = db()->query("SELECT * FROM SuggestionCategories");
        $categories = $categories->fetchAll(PDO::FETCH_ASSOC);

        return $this->view('suggestions.index', compact('category', 'suggestions', 'categories', 'page', 'pageCount', 'visiblePageCount'));
    }
}