<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;

class ForumThreadController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_FORUM');
    }

    public function index()
    {
        $threads = db()->query("SELECT COUNT(FT.id) FROM ForumThreads FT INNER JOIN Accounts A ON FT.accountID = A.id INNER JOIN ForumCategories FC ON FT.categoryID = FC.id ORDER BY FT.id DESC");
        $itemsCount = $threads->fetchColumn();

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

        $visiblePageCount = 5;
        $limit = 50;

        $itemsCount = $itemsCount;
        $pageCount = ceil($itemsCount / $limit);
        if ($page > $pageCount) {
            $page = 1;
        }

        $visibleItemsCount = $page * $limit - $limit;
        $threads = db()->query("SELECT FT.*, A.username, A.realname, FC.name as categoryName FROM ForumThreads FT INNER JOIN Accounts A ON FT.accountID = A.id INNER JOIN ForumCategories FC ON FT.categoryID = FC.id ORDER BY FT.id DESC LIMIT $visibleItemsCount, $limit");

        if (isset($_GET["search"])) {
            if (get("search") != null) {
                $threads = db()->prepare("SELECT FT.*, A.username, A.realname, FC.name as categoryName FROM ForumThreads FT INNER JOIN Accounts A ON FT.accountID = A.id INNER JOIN ForumCategories FC ON FT.categoryID = FC.id WHERE FT.title LIKE :search OR (A.realname LIKE :search OR A.username LIKE :search) OR FC.name LIKE :search ORDER BY FT.id DESC");
                $threads->execute(array(
                    "search" => '%' . get("search") . '%'
                ));
            }
        }

        $threads = $threads->fetchAll();

        return view('forum.threads.index', compact('threads', 'page', 'visiblePageCount', 'pageCount'));
    }

    public function destroy($id)
    {
      $deleteThread = db()->prepare("DELETE FROM ForumThreads WHERE id = ?");
      $deleteThread->execute(array($id));

      return back();
    }
}