<?php

namespace Dashboard\Controllers\Help;

use Dashboard\Core\Controller;
use Dashboard\Services\SlugService;
use Verot\Upload\Upload;

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

    public function index()
    {
        $topics = db()->query("SELECT * FROM HelpTopics ORDER BY `order` ASC, id DESC");
        $topics = $topics->fetchAll();
        return view('help.topics.index', compact('topics'));
    }

    public function create()
    {
        return view('help.topics.create');
    }

    public function store()
    {
        validate([
            'name' => 'required',
            'description' => 'required',
            'image' => 'required|uploaded_file',
						'order' => 'required|numeric',
        ]);

        $upload = new Upload($_FILES["image"]);
        $imageID = md5(uniqid(rand(0, 9999)));
        if ($upload->uploaded) {
            $upload->allowed = array("image/*");
            $upload->file_new_name_body = $imageID;
            $upload->process(__ROOT__ . "/apps/main/public/images/help/topics/");
            if ($upload->processed) {
	              $slug = SlugService::preventDuplicate(input("name"), 'HelpTopics');
                $insertHelpTopics = db()->prepare("INSERT INTO HelpTopics (name, slug, description, `order`, imageID, imageType) VALUES (?, ?, ?, ?, ?, ?)");
                $insertHelpTopics->execute(array(input("name"), $slug, input("description"), input("order"), $imageID, $upload->file_dst_name_ext));
                return back()->flash("success", t__('Topic added successfully!'));
            }
        } else {
            return back()->flash("error", t__('An error occupied while uploading an image: %error%', ['%error%' => $upload->error]));
        }
    }

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

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

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

    public function update($id)
    {
        validate([
            'name' => 'required',
            'description' => 'required',
		        'order' => 'required|numeric',
        ]);
	    
		    $topic = db()->prepare("SELECT * FROM HelpTopics WHERE id = ?");
		    $topic->execute(array($id));
		    $topic = $topic->fetch();
		    
		    if (!$topic) return view('404');

        if (input()->file('image')->size) {
            $upload = new Upload($_FILES["image"]);
            $imageID = md5(uniqid(rand(0, 9999)));
            if ($upload->uploaded) {
                $upload->allowed = array("image/*");
                $upload->file_overwrite = true;
                $upload->file_new_name_body = $imageID;
                $upload->process(__ROOT__ . "/apps/main/public/images/help/topics/");
                if ($upload->processed) {
                    $updateHelpTopics = db()->prepare("UPDATE HelpTopics SET imageID = ?, imageType = ? WHERE id = ?");
                    $updateHelpTopics->execute(array($imageID, $upload->file_dst_name_ext, $id));
                } else {
                    return back()->flash("error", t__('An error occupied while uploading an image: %error%', ['%error%' => $upload->error]));
                }
            }
        }
	    
		    if ($topic["name"] != input("name")) {
			    $slug = SlugService::preventDuplicate(input("name"), 'HelpTopics');
		    } else {
			    $slug = $topic["slug"];
		    }

        $updateHelpTopics = db()->prepare("UPDATE HelpTopics SET name = ?, slug = ?, description = ?, `order` = ? WHERE id = ?");
        $updateHelpTopics->execute(array(input("name"), $slug, input("description"), input("order"), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

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