<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;

class SuggestionController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_SUGGESTIONS');
    }

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

        $visiblePageCount = 5;
        $limit = 50;

        $suggestions = db()->query("SELECT count(S.id) FROM Suggestions S INNER JOIN Accounts A ON S.accountID = A.id INNER JOIN SuggestionCategories SC ON S.categoryID = SC.id ORDER BY S.id DESC");
        $itemsCount = $suggestions->fetchColumn();
        $pageCount = ceil($itemsCount / $limit);
        if ($page > $pageCount) {
            $page = 1;
        }
        $visibleItemsCount = $page * $limit - $limit;
        $suggestions = db()->query("SELECT S.*, A.username, A.realname, SC.name as categoryName FROM Suggestions S INNER JOIN Accounts A ON S.accountID = A.id INNER JOIN SuggestionCategories SC ON S.categoryID = SC.id ORDER BY S.id DESC LIMIT $visibleItemsCount, $limit");

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

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

    public function create()
    {
        $categories = db()->query("SELECT * FROM SuggestionCategories ORDER BY id DESC");
        $categories = $categories->fetchAll();

        return view('suggestions.create', compact('categories'));
    }

    public function store()
    {
        validate([
            'title' => 'required',
            'categoryID' => 'required',
            'content' => 'required',
            'views' => 'required',
            'likesCount' => 'required',
            'dislikesCount' => 'required',
        ]);
	    
		    $slug = slugify(input("title"));

        $insertSuggestions = db()->prepare("INSERT INTO Suggestions (accountID, categoryID, title, slug, content, views, likesCount, dislikesCount, updatedDate, creationDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $insertSuggestions->execute(array(auth()->user()->id(), input("categoryID"), input("title"), $slug, input("content"), input("views"), input("likesCount"), input("dislikesCount"), datetime(), datetime()));
        return back()->flash("success", t__('Suggestion has been added successfully!'));
    }

    public function edit($id)
    {
        $suggestion = db()->prepare("SELECT * FROM Suggestions WHERE id = ?");
        $suggestion->execute(array($id));
        $suggestion = $suggestion->fetch();

        if (!$suggestion) return view('404');

        $categories = db()->query("SELECT * FROM SuggestionCategories ORDER BY id DESC");
        $categories = $categories->fetchAll();

        return view('suggestions.edit', compact('suggestion', 'categories'));
    }

    public function update($id)
    {
        validate([
            'title' => 'required',
            'categoryID' => 'required',
            'content' => 'required',
            'views' => 'required',
            'likesCount' => 'required',
            'dislikesCount' => 'required',
        ]);
	    
		    $slug = slugify(input("title"));

        $updateSuggestions = db()->prepare("UPDATE Suggestions SET title = ?, slug = ?, categoryID = ?, content = ?, views = ?, likesCount = ?, dislikesCount = ?, updatedDate = ? WHERE id = ?");
        $updateSuggestions->execute(array(input("title"), $slug, input("categoryID"), input("content"), input("views"), input("likesCount"), input("dislikesCount"), datetime(), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

    public function destroy($id)
    {
        $deleteSuggestions = db()->prepare("DELETE FROM Suggestions WHERE id = ?");
        $deleteSuggestions->execute(array($id));
        return back();
    }
}