<?php

namespace Dashboard\Controllers\Support;

use Dashboard\Core\Controller;
use Dashboard\Core\Jobs\JobDispatcher;
use Dashboard\Jobs\SendDiscordWebhook;
use Dashboard\Jobs\SendEmail;
use Dashboard\Libs\Discord;
use PDO;

class MessageController extends Controller
{
    public function __construct()
    {
        abort_perm(['MANAGE_SUPPORT', 'MANAGE_SUPPORT_TICKETS']);
    }

    public function store($id)
    {
      $support = db()->prepare("SELECT S.*, A.username, A.realname, A.email, SC.name as categoryName FROM Supports S INNER JOIN Accounts A ON S.accountID = A.id INNER JOIN SupportCategories SC ON S.categoryID = SC.id WHERE S.id = ?");
      $support->execute(array($id));
      $support = $support->fetch();
	    
	    if (!$support) return view('404');
	    
	    if (!auth()->user()->canManageSupportCategory('REPLY_TICKETS', $support["categoryID"]))
		    abort_403();

      validate([
        'message' => 'required'
      ]);

      $insertSupportMessages = db()->prepare("INSERT INTO SupportMessages (accountID,supportID, message, writeLocation, creationDate) VALUES (?, ?, ?, ?, ?)");
      $insertSupportMessages->execute(array(auth()->user()->id(), $support["id"], filteredContent($_POST["message"]), 2, datetime()));
      $updateSupports = db()->prepare("UPDATE Supports SET updateDate = ?, statusID = ?, readStatus = ? WHERE id = ? AND accountID = ?");
      $updateSupports->execute(array(datetime(), 2, 0, $id, $support["accountID"]));

      if (!moduleIsDisabled('discord') && moduleSettings('discord', 'ticketStatus') == '1' && $support['discordChannelID'] != null) {
        $discord = new Discord(moduleSettings('discord', 'clientID'), moduleSettings('discord', 'clientSecret'), moduleSettings('discord', 'botToken'));
        $discord->sendTicketMessage(
          $support['discordChannelID'],
          auth()->user()->id(),
          auth()->user()->displayName(),
          strip_tags($_POST["message"]),
          true
        );
      }

      if (moduleSettings('support', 'sendEmailOnAnswered') == '1') {
	      $title = moduleSettings('support', 'answeredEmailTitle');
	      $search = array("%username%", "%subject%", "%category%", "%url%");
	      $replace = array($support["realname"], $support["title"], $support["categoryName"], websiteUrl() . "/support/tickets/".$support["id"]);
	      $emailContent = str_replace($search, $replace, moduleSettings('support', 'answeredEmailTemplate'));
				JobDispatcher::dispatch((new SendEmail($support["email"], $title, $emailContent)));
      }
	    
	    JobDispatcher::dispatch((new SendDiscordWebhook('support.ticket.answered', [
		    "username" => auth()->user()->displayName(),
		    "category" => $support["categoryName"],
		    "title" => $support["title"],
		    "message" => strip_tags(input('message')),
		    "dashboard_url" => websiteUrl("/dashboard/support/tickets/$id")
	    ])));

      return back()->flash('success', t__('Message has been sent successfully!'));
    }

    public function destroy($id)
    {
        $supportMessage = db()->prepare("SELECT SM.id, S.categoryID FROM SupportMessages SM INNER JOIN Supports S ON S.id = SM.supportID WHERE SM.id = ?");
        $supportMessage->execute(array($id));
		    $supportMessage = $supportMessage->fetch(PDO::FETCH_ASSOC);
	    
		    if (!$supportMessage) return view('404');
		    
		    if (!auth()->user()->canManageSupportCategory('DELETE_MESSAGES', $supportMessage["categoryID"]))
			    abort_403();
	    
		    $deleteSupportMessages = db()->prepare("DELETE FROM SupportMessages WHERE id = ?");
		    $deleteSupportMessages->execute(array($supportMessage["id"]));

        return back();
    }
}