<?php

namespace Main\Controllers\Blog;

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

class TagController extends Controller
{
		protected string $route_type = 'blog';
	
    public function show($slug)
    {
		    $tag = db()->prepare("SELECT * FROM NewsTags WHERE slug = ?");
		    $tag->execute(array($slug));
		    $tag = $tag->fetch();
		    
		    if (!$tag) abort_404();
	    
		    if (auth()->check() && auth()->user()->can('MANAGE_BLOG')) {
			    $accessibleStatuses = ['draft', 'published'];
		    } else {
			    $accessibleStatuses = ['published'];
		    }
		    $accessibleStatuses = implode(", ", array_map(function($status) {
			    return "'$status'";
		    }, $accessibleStatuses));
			
        if (isset($_GET["page"])) {
            if (!is_numeric($_GET["page"])) {
                $_GET["page"] = 1;
            }
            $page = intval($_GET["page"]);
        } else {
            $page = 1;
        }
	    
		    $newsLimit = 6;

        $itemsCount = db()->prepare("SELECT count(N.id) from News N INNER JOIN NewsTags NT ON N.id = NT.newsID WHERE NT.slug = ? AND N.status IN ($accessibleStatuses)");
        $itemsCount->execute(array($slug));
        $itemsCount = $itemsCount->fetchColumn();

        $pageCount = ceil($itemsCount / $newsLimit);
        if ($page > $pageCount) {
            $page = 1;
        }
        $visibleItemsCount = $page * $newsLimit - $newsLimit;
        $visiblePageCount = 5;
	    
		    SeoService::set('blog.tags.show', [
			    'tag' => $tag['name'],
		    ]);
	    
		    $posts = db()->prepare("SELECT N.*, NC.name as categoryName, NC.slug as categorySlug, A.username, A.realname from News N INNER JOIN NewsCategories NC ON N.categoryID = NC.id INNER JOIN NewsTags NT ON N.id = NT.newsID INNER JOIN Accounts A ON N.accountID = A.id WHERE NT.slug = ? AND N.status IN ($accessibleStatuses) ORDER BY N.id DESC LIMIT $visibleItemsCount, $newsLimit");
		    $posts->execute(array($slug));
		    $posts = $posts->fetchAll(PDO::FETCH_ASSOC);
		    $posts = array_map(function($post) {
			    $newsCount = db()->prepare("SELECT COUNT(id) FROM NewsComments WHERE newsID = ? AND status = ? ORDER BY id DESC");
			    $newsCount->execute(array($post["id"], 1));
			    $post["commentsCount"] = $newsCount->fetchColumn();
			    
			    $post["user"] = [
				    'id' => $post["accountID"],
				    'username' => $post["username"],
				    'displayName' => $post["realname"],
				    'avatar' => AvatarService::get($post["accountID"], $post["realname"]),
			    ];
			    
			    $post["category"] = [
				    'id' => $post["categoryID"],
				    'name' => $post["categoryName"],
				    'slug' => $post["categorySlug"],
			    ];
			    
			    $post['image']  = "/assets/core/images/blog/posts/" . $post['imageID'] . "." . $post['imageType'];
			    
			    return $post;
		    }, $posts);

        return $this->view('blog.tag', compact('posts', 'slug', 'page', 'pageCount', 'visiblePageCount', 'tag'));
    }
}