<?php

namespace App\Presentation\Comment;

use App\Model\CommentManager;
use App\Presentation\BasePresenter;

class CommentPresenter extends BasePresenter
{
    private CommentManager $commentManager;

    public function __construct(CommentManager $commentManager)
    {
        parent::__construct();
        $this->commentManager = $commentManager;
    }

    public function actionAdd(): void
    {
        if (!$this->getUser()->isLoggedIn())
        {
            $this->error("User is not logged in", 403);
        }

        $payload = $this->getPayloadJsonAndCheckRequest(['article_id', 'text']);
        $this->commentManager->addComment($this->getUser()->getId(), $payload);
        $this->sendJson(['success' => true]);
    }

    public function renderDelete($commentId): void
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->error('User is not logged in', 403);
        }

        if (!$this->getUser()->isAllowed('comments', 'delete')) {
            $this->error('You do not have permission to delete comments', 403);
        }

        $this->commentManager->deleteComment($commentId);
        $this->sendJson(['success' => true]);
    }

    public function actionRate($commentId): void
    {
        if (!$this->getUser()->isLoggedIn()) {
            $this->error('User is not logged in', 403);
        }

        $this->commentManager->rateComment($this->getUser()->getId(), $commentId);
        $this->sendJson(['success' => true]);

        /*
        try {
            $this->commentManager->rateComment($this->getUser()->getId(), $commentId);
            $this->sendJson(['success' => true]);
        }catch (\Exception) {
            $this->error("Comment is not exists!", 400);
        }*/
    }
}