<?php

namespace Dashboard\Controllers\Support;

use Dashboard\Core\Controller;

class QuickAnswerController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_SUPPORT');
    }

    public function index()
    {
        $supportAnswers = db()->query("SELECT * FROM SupportAnswers ORDER BY id DESC");
        $supportAnswers = $supportAnswers->fetchAll();
        return view('support.quick-answers.index', compact('supportAnswers'));
    }

    public function create()
    {
        return view('support.quick-answers.create');
    }

    public function store()
    {
        validate([
            'title' => 'required',
            'content' => 'required',
        ]);

        $insertSupportAnswers = db()->prepare("INSERT INTO SupportAnswers (title, content) VALUES (?, ?)");
        $insertSupportAnswers->execute(array(input("title"), filteredContent($_POST["content"])));
        return back()->flash("success", t__('Answer has been added successfully!'));
    }

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

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

        return view('support.quick-answers.edit', compact('supportAnswer'));
    }

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

        $updateSupportAnswers = db()->prepare("UPDATE SupportAnswers SET title = ?, content = ? WHERE id = ?");
        $updateSupportAnswers->execute(array(input("title"), filteredContent($_POST["content"]), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

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