<?php

namespace App\Http\Controllers\Blog;

use App\Http\Requests\Blog\CommentRequest;
use App\Http\Requests\Blog\PostLikeRequest;
use App\Http\Requests\Blog\PostUnlikeRequest;
use App\Models\Tag;
use App\Models\Like;
use App\Models\Post;
use App\Models\Comment;
use App\Models\Category;
use App\Models\UserProfile;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Notifications\NewCommentAdded;

class BlogController extends Controller
{
    public function __construct()
    {
        $this->middleware("web");
    }

    public function index()
    {
        $posts = collect();

        $categories = collect();
        $allCategories = Category::all();

        foreach ($allCategories as $c) {
            if (Post::where([
                    "category_id" => $c->id,
                    "is_confirmed" => true,
                    "is_active" => true
                ])->count() > 0) {
                $categories->push($c);
            }
        }

        foreach ($categories as $category) {
            $tempPosts = Post::where([
                "category_id" => $category->id,
                "is_confirmed" => true,
                "is_active" => true
            ])
                ->orderBy("created_at", "desc")
                ->take(3)
                ->get();

            foreach ($tempPosts as $post) {
                $posts->push($post);
            }
        }

        $posts = $posts->flatten(1);

        return view("blog.index")->with([
            "latestPosts" => Post::where([
                "is_confirmed" => true,
                "is_active" => true
            ])->orderBy("created_at", "desc")->take(5)->get(),
            "posts" => $posts
        ]);
    }

    public function about()
    {
        return view("blog.about");
    }

    public function showCategory($category)
    {
        if (Category::whereName(ucfirst($category))->count() == 0) {
            return abort(404);
        }

        if (Post::where([
                "category_id" => Category::whereName(ucfirst($category))->first()->id,
                "is_confirmed" => true,
                "is_active" => true
            ])->count() == 0) {
            return abort(404);
        }

        $posts = Post::where([
            "category_id" => Category::whereName(ucfirst($category))->first()->id,
            "is_confirmed" => true,
            "is_active" => true
        ])
            ->orderBy("created_at", "desc")
            ->paginate(8);

        return view("blog.category")->with([
            "category" => Category::whereName(ucfirst($category))->first(),
            "posts" => $posts
        ]);
    }

    public function showPost(Request $request, $category, $slug)
    {
        $post = Post::where([
            "slug" => $slug,
            "is_confirmed" => true,
            "is_active" => true
        ])->firstOrFail();

        if ($post->isLiked($request->ip())) {
            $likedId = Like::where([
                "post_id" => $post->id,
                "ip_address" => $request->ip()
            ])->firstOrFail()->id;
        } else $likedId = null;

        if (auth()->check()) $comments = $post->comment;
        else $comments = $post->comment()->where([
            "post_id" => $post->id,
            "is_active" => true,
        ])->get();

        return view("blog.post")->with([
            "comments" => $comments,
            "category" => $category,
            "likeCounter" => $post->total_likes,
            "post" => $post,
            "ip" => $request->ip(),
            "likedId" => $likedId
        ]);
    }

    public function showTagPosts($tag)
    {
        return view("blog.tag")->with([
            "tag" => $tag,
            "posts" => Tag::whereName($tag)
                ->firstOrFail()
                ->post()
                ->where([
                    "is_confirmed" => true,
                    "is_active" => true,
                ])
                ->orderBy("created_at", "desc")
                ->paginate(5)
        ]);
    }

    public function showProfile($profileLink)
    {
        $userProfile = UserProfile::where("profile_link", $profileLink)->firstOrFail();

        $posts = Post::where([
            "user_id" => $userProfile->user_id,
            "is_confirmed" => true,
            "is_active" => true,
        ])
            ->orderBy("created_at", "desc")
            ->paginate(5);

        if ($posts->count() == 0) {
            return abort(404);
        }

        return view("blog.profile")->with("posts", $posts);
    }

    public function comment(CommentRequest $request)
    {
        $comment = new Comment();

        $comment->post_id = $request->post_id;
        $comment->name = $request->name;
        $comment->email = $request->email;
        $comment->comment = $request->comment;

        $comment->save();

        $commentedPost = Post::find($request->post_id);

        $commentedPost->user->notify(new NewCommentAdded("Have new comment for review"));

        return response()->json([
            "type" => "alert-success",
            "message" => "Comment submited successfully and will be published after review."
        ]);
    }

    public function like(PostLikeRequest $request)
    {
        $like = new Like();
        $post = Post::find($request->post_id);
        $likes = $post->like->all();

        foreach ($likes as $l) {
            if ($l->post_id == $request->post_id && $l->ip_address == $request->ip()) {
                return false;
            }
        }

        $like->post_id = $request->post_id;
        $like->ip_address = $request->ip();

        $like->save();

        $post->increment("total_likes");
        $post->save();

        return response()->json([
            "unlike_id" => $like->id,
            "likeCounter" => $post->total_likes
        ]);
    }

    public function unlike(PostUnlikeRequest $request)
    {
        $like = Like::find($request->unlike_id);
        $post = Post::find($like->post_id);
        $like->delete();

        $post->decrement("total_likes");
        $post->save();

        return response()->json([
            "post_id" => $post->id,
            "likeCounter" => $post->total_likes
        ]);
    }
}
