<?php

namespace Main\Controllers\Blog;

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

class CommentController extends Controller
{
		protected string $route_type = 'blog';
		
    public function store($postId)
    {
        validate([
            'message' => 'required'
        ]);
	    
		    if (recaptcha()->isEnabled('reply_blog_post') && !recaptcha()->verify()) {
			    return back()->flash('error', t__('Spam detected!'));
		    }
	    
		    if (auth()->check() && auth()->user()->can('MANAGE_BLOG')) {
			    $accessibleStatuses = ['draft', 'published'];
		    } else {
			    $accessibleStatuses = ['published'];
		    }
		    $accessibleStatuses = implode(", ", array_map(function($status) {
			    return "'$status'";
		    }, $accessibleStatuses));

        $post = db()->prepare("SELECT N.*, A.username, A.realname, NC.name as categoryName, NC.slug as categorySlug FROM News N INNER JOIN Accounts A ON N.accountID = A.id INNER JOIN NewsCategories NC ON N.categoryID = NC.id WHERE N.id = ? AND N.status IN ($accessibleStatuses)");
		    $post->execute(array($postId));
		    $post = $post->fetch();

        if (!$post) abort_404();
				
				if (modules('blog')->settings('commentsStatus') == 0 || $post["commentsStatus"] == 0) abort_404();

        $commentBannedStatus = db()->prepare("SELECT * FROM BannedAccounts WHERE accountID = ? AND categoryID = ? AND (expiryDate > ? OR expiryDate = ?)");
        $commentBannedStatus->execute(array(auth()->user()->id(), 3, datetime(), '1000-01-01 00:00:00'));
        $commentBannedStatus = $commentBannedStatus->fetch(PDO::FETCH_ASSOC);

        if ($commentBannedStatus) {
          return back()->flash('error', t__('You are banned from commenting.'));
        }
	    
		    if (auth()->user()->isStaff()) {
			    $status = 'published';
		    } else {
			    $status = 'moderation';
		    }
				
				$message = sanitize(input("message"));

        $insertNewsComments = db()->prepare("INSERT INTO NewsComments (accountID, message, newsID, status, creationDate) VALUES (?, ?, ?, ?, ?)");
        $insertNewsComments->execute(array(auth()->user()->id(), $message, $postId, $status == 'published' ? '1' : '0', datetime()));
        $commentID = db()->lastInsertId();
        $notificationsVariables = $commentID;
        $insertNotifications = db()->prepare("INSERT INTO Notifications (accountID, type, variables, creationDate) VALUES (?, ?, ?, ?)");
        $insertNotifications->execute(array(auth()->user()->id(), 2, $notificationsVariables, datetime()));
	    
				JobDispatcher::dispatch((new SendDiscordWebhook('blog.post.commented', [
					"username" => auth()->user()->displayName(),
					"title" => $post["title"],
					"comment" => $message,
					"message" => $message,
					"url" => website_url(url('blog.posts.show', ['slug' => $post["slug"]])),
					"dashboard_url" => website_url("/dashboard/blog/comments/$commentID/edit"),
				])));
	    
		    if ($status == 'published') {
			    return back()->flash('success', t__('Your comment has been successfully sent.'));
		    } else {
			    return back()->flash('success', t__('Your comment will be visible to public after a mod-check.'));
	      }
    }
}