<?php

namespace App\Model;

use Nette\Database\SqlLiteral;

class CommentManager extends BaseManager
{
    public function addComment($userId, $data): void
    {
        $this->database->table('comments')
            ->insert([
                'article_id' => $data['article_id'],
                'parent_comment_id' => $data['parent_comment_id'],
                'user_id' => $userId,
                'created_at' => new SqlLiteral('NOW()'),
                'updated_at' => new SqlLiteral('NOW()'),
                'text' => $data['text'],
            ]);
    }

    public function deleteComment($commentId): void
    {
        $this->database->table('comments')
            ->update([
                'deleted_at' => new SqlLiteral('NOW()'),
            ]);
    }

    public function rateComment($userId, $commentId): void
    {
        $rateRow = $this->database->table('user_liked_comment')
            ->where('user_id', $userId)
            ->where('comment_id', $commentId)
            ->fetch();

        if ($rateRow != null)
            return;

        $this->database->table('user_liked_comment')
            ->insert([
                'user_id' => $userId,
                'comment_id' => $commentId
            ]);

        $this->database->table('comments')
            ->where('id', $commentId)
            ->update([
                'likes' => $this->getLikes($commentId)
            ]);
    }

    function getLikes($commentId): int
    {
        return $this->database->table('user_liked_comment')
            ->where('comment_id', $commentId)->count();
    }
}