<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;
use Dashboard\Core\Jobs\JobDispatcher;
use Dashboard\Jobs\SendDiscordWebhook;
use PDO;

class ChangelogController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_CHANGELOG');
    }

    public function index()
    {
        $changelogs = db()->query("SELECT * FROM Changelogs ORDER BY id DESC");
		    $changelogs = $changelogs->fetchAll(PDO::FETCH_ASSOC);

        return view('changelog.index', compact('changelogs'));
    }

    public function create()
    {
				$tags = db()->query("SELECT * FROM ChangelogTags ORDER BY id DESC");
				$tags = $tags->fetchAll(PDO::FETCH_ASSOC);
				
        return view('changelog.create', compact('tags'));
    }

    public function store()
    {
        validate([
            'title' => 'required',
        ]);
				
        $insertChangelogs = db()->prepare("INSERT INTO Changelogs (title, creationDate) VALUES (?, ?)");
		    $insertChangelogs->execute(array(input("title"), datetime()));
				$changelogID = db()->lastInsertId();
	    
		    if (count(array_filter($_POST["items"]))) {
			    $insertChangelogItems = db()->prepare("INSERT INTO ChangelogItems (changelogID, tagID, content) VALUES (?, ?, ?)");
			    foreach ($_POST["items"] as $key => $item) {
				    $tagID = strip_tags($_POST["tags"][$key]);
				    $content = $_POST["items"][$key];
				    $insertChangelogItems->execute(array($changelogID, $tagID, $content));
			    }
		    }

		    JobDispatcher::dispatch((new SendDiscordWebhook('changelog.published', [
			    "username" => auth()->user()->displayName(),
			    "title" => input("title"),
			    "url" => websiteUrl("/changelog/$changelogID")
		    ])));
				
        return back()->flash("success", t__('Changelog has been added successfully!'));
    }

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

        if (!$changelog) return view('404');
				
				$changelogItems = db()->prepare("SELECT I.*, T.name as tagName FROM ChangelogItems I INNER JOIN ChangelogTags T ON I.tagID = T.id WHERE I.changelogID = ?");
				$changelogItems->execute(array($id));
				$changelog['items'] = $changelogItems->fetchAll(PDO::FETCH_ASSOC);
	    
		    $tags = db()->query("SELECT * FROM ChangelogTags ORDER BY id DESC");
		    $tags = $tags->fetchAll(PDO::FETCH_ASSOC);

        return view('changelog.edit', compact('changelog', 'tags'));
    }

    public function update($id)
    {
        validate([
            'title' => 'required',
        ]);

        $updateChangelogs = db()->prepare("UPDATE Changelogs SET title = ? WHERE id = ?");
		    $updateChangelogs->execute(array(input("title"), $id));
				
				$deleteChangelogItems = db()->prepare("DELETE FROM ChangelogItems WHERE changelogID = ?");
				$deleteChangelogItems->execute(array($id));
		    if (count(array_filter($_POST["items"]))) {
			    $insertChangelogItems = db()->prepare("INSERT INTO ChangelogItems (changelogID, tagID, content) VALUES (?, ?, ?)");
			    foreach ($_POST["items"] as $key => $item) {
				    $tagID = strip_tags($_POST["tags"][$key]);
				    $content = $_POST["items"][$key];
				    $insertChangelogItems->execute(array($id, $tagID, $content));
			    }
		    }
				
				
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

    public function destroy($id)
    {
        $deleteChangelogs = db()->prepare("DELETE FROM Changelogs WHERE id = ?");
	      $deleteChangelogs->execute(array($id));
				$deleteChangelogItems = db()->prepare("DELETE FROM ChangelogItems WHERE changelogID = ?");
				$deleteChangelogItems->execute(array($id));
				
        return back();
    }
}