<?php

namespace App\Http\Controllers\Blog\Articles;

use App\Http\Controllers\Controller;
use App\Http\Requests\Blog\ArticleCommentAddRequest;
use App\Models\Article;
use App\Models\ArticleComment;
use Illuminate\Http\Request;

class CommentsController extends Controller
{
    /**
     * add product comment
     */
    public function add(ArticleCommentAddRequest $request, Article $article)
    {
        /** @var \App\Models\User $user */
        $user = auth()->user();

        if (!$article->comment_status) {
            return redirect()->back();
        }

        $article->articleComments()->create([
            'user_id' => $user->id,
            'content' => $request->content,
            'reply_to' => $request->exists('reply_to') && $request->reply_to != null && $request->reply_to != 0 ? $request->reply_to : null,
            'status' => $user->type == 'owner' || $user->type == 'admin' ? 'publish' : 'awaiting',
        ]);

        if ($user->type == 'owner' || $user->type == 'admin')
            return redirect()->back()->with('message', [__('messages.comment_published')]);
        else
            return redirect()->back()->with('message', [__('messages.comment_submited')]);
    }

    /**
     * like comment
     */
    public function like(Request $request, ArticleComment $comment)
    {
        $liked_comments = $request->session()->get('blog_liked_comments', []);
        $disliked_comments = $request->session()->get('blog_disliked_comments', []);

        if (!in_array($comment->id, $liked_comments) && !in_array($comment->id, $disliked_comments)) {
            $comment->update([
                'vote_up' => $comment->vote_up + 1
            ]);

            $liked_comments[] = $comment->id;
            session(['blog_liked_comments' => $liked_comments]);
        }

        return redirect()->back();
    }

    /**
     * dislike comment
     */
    public function dislike(Request $request, ArticleComment $comment)
    {
        $liked_comments = $request->session()->get('blog_liked_comments', []);
        $disliked_comments = $request->session()->get('blog_disliked_comments', []);

        if (!in_array($comment->id, $liked_comments) && !in_array($comment->id, $disliked_comments)) {
            $comment->update([
                'vote_down' => $comment->vote_down + 1
            ]);

            $disliked_comments[] = $comment->id;
            session(['blog_disliked_comments' => $disliked_comments]);
        }

        return redirect()->back();
    }
}
