<?php

namespace Dashboard\Controllers\Help;

use Dashboard\Core\Controller;

class ArticleController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_HELP_CENTER');
    }

    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;

        $articles = db()->query("SELECT count(HA.id) FROM HelpArticles HA INNER JOIN Accounts A ON HA.accountID = A.id INNER JOIN HelpTopics HT ON HA.topicID = HT.id ORDER BY HA.`order` ASC, HA.id DESC");
        $itemsCount = $articles->fetchColumn();
        $pageCount = ceil($itemsCount / $limit);
        if ($page > $pageCount) {
            $page = 1;
        }
        $visibleItemsCount = $page * $limit - $limit;
        $articles = db()->query("SELECT HA.*, A.username, A.realname, HT.name as topicName FROM HelpArticles HA INNER JOIN Accounts A ON HA.accountID = A.id INNER JOIN HelpTopics HT ON HA.topicID = HT.id ORDER BY HA.`order` ASC, HA.id DESC LIMIT $visibleItemsCount, $limit");

        if (isset($_GET["search"])) {
            if (get("search") != null) {
                $articles = db()->prepare("SELECT HA.*, A.username, A.realname, HT.name as topicName FROM HelpArticles HA INNER JOIN Accounts A ON HA.accountID = A.id INNER JOIN HelpTopics HT ON HA.topicID = HT.id WHERE HA.title LIKE :search OR HT.name LIKE :search ORDER BY HA.`order` ASC, HA.id DESC");
                $articles->execute(array(
                    "search" => '%' . get("search") . '%'
                ));
            }
        }

        $articles = array_map(function ($article) {
            if ($article["likesCount"] != 0 || $article["dislikesCount"] != 0) {
                $article["usefulPercent"] = intval(($article["likesCount"] * 100) / ($article["likesCount"] + $article["dislikesCount"]));
            } else {
                $article["usefulPercent"] = 0;
            }
            return $article;
        }, $articles->fetchAll());

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

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

        return view('help.articles.create', compact('topics'));
    }

    public function store()
    {
        validate([
            'title' => 'required',
            'topicID' => 'required',
            'content' => 'required',
		        'order' => 'required|numeric',
        ]);
	    
		    $slug = slugify(input("title"));

        $insertHelp = db()->prepare("INSERT INTO HelpArticles (accountID, title, slug, topicID, content, views, likesCount, dislikesCount, `order`, updateDate, creationDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $insertHelp->execute(array(auth()->user()->id(), input("title"), $slug, input("topicID"), filteredContent($_POST["content"]), 0, 0, 0, input("order"), datetime(), datetime()));
        return back()->flash('success', t__('Article added successfully!'));
    }

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

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

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

        return view('help.articles.edit', compact('article', 'topics'));
    }

    public function update($id)
    {
        validate([
            'title' => 'required',
            'topicID' => 'required',
            'content' => 'required',
		        'order' => 'required|numeric',
        ]);
	    
		    $slug = slugify(input("title"));

        $updateHelp = db()->prepare("UPDATE HelpArticles SET title = ?, slug = ?, topicID = ?, content = ?, `order` = ?, updateDate = ? WHERE id = ?");
        $updateHelp->execute(array(input("title"), $slug, input("topicID"), filteredContent($_POST["content"]), input("order"), datetime(), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

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