<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Comment;
use App\Models\Knowledge;
use App\Models\KnowledgeView;
use App\Models\LikeDislike;
use Illuminate\Http\Request;

class KnowledgeController extends Controller
{
    public function storeComment(Request $request, $id)
    {
        $request->validate([
            'comment'    => 'required|string',
            'comment_id' => 'nullable|integer',
        ]);

        $user      = auth()->user();
        $knowledge = Knowledge::active();

        if ($request->comment_id) {
            $knowledge->whereHas('comments', function ($comment) use ($request) {
                $comment->where('id', $request->comment_id);
            });
        }

        $knowledge = $knowledge->findOrFail($id);

        $comment               = new Comment();
        $comment->knowledge_id = $knowledge->id;
        $comment->user_id      = $user->id;
        $comment->comment_id   = $request->comment_id ?? 0;
        $comment->quote        = purifyHtml($request->comment);
        $comment->save();

        $notify[] = ['success', 'Comment added successfully'];
        return back()->withNotify($notify);
    }
  

    public function storeLikeDislike(Request $request, $id)
    {
        $request->validate([
            'type' => 'required|in:like,dislike',
        ]);

        $knowledge = Knowledge::active()->find($id);

        if (!$knowledge) {
            return response()->json([
                'status'  => 'error',
                'message' => 'Knowledge not found',
            ]);
        }

        $user = auth()->user();

        $likeDislike = LikeDislike::where('user_id', $user->id)->where('knowledge_id', $id)->first();

        if ($likeDislike) {
            if ($likeDislike->type === $request->type) {
                $likeDislike->delete();
                $likeDislike = null;
            } else {
                $likeDislike->type = $request->type;
                $likeDislike->save();
            }
        } else {
            $likeDislike               = new LikeDislike();
            $likeDislike->user_id      = $user->id;
            $likeDislike->knowledge_id = $knowledge->id;
            $likeDislike->type         = $request->type;
            $likeDislike->save();
        }

        $likeCount    = $knowledge->likes()->count();
        $dislikeCount = $knowledge->dislikes()->count();

        return response()->json([
            'status'        => 'success',
            'message'       => 'saved',
            'like_dislike'  => $likeDislike,
            'like_count'    => $likeCount,
            'dislike_count' => $dislikeCount,
        ]);
    }
}
