<?php

namespace App\Http\Controllers\Site;

use App\Http\Controllers\SiteController;
use App\Models\Blog;
use App\Models\BlogComment;
use Illuminate\Http\Request;

class BlogController extends SiteController {
	public function index() {
		$pagePayload = new \stdClass();

		$pagePayload->title = 'Postagens';
		$pagePayload->posts = Blog::query()->with('blogCategory')->get();
		$pagePayload->siteManagement = getSiteManagement('blog');
		$navPayload = getNavSiteManagement();	
		return view('site.pages.blog.blogPage', [
			'pagePayload' => $pagePayload,
			'navPayload'  => $navPayload
		]);
	}

	public function show(Blog $blog) {
		$pagePayload = new \stdClass();

		$pagePayload->title = $blog->title;

		$comments = BlogComment::query()
			->where([
				['blog_id', $blog->id],
				['reply_id', null],
				['approved', 1],
			])
			->with('replies', function ($query) {
				$query
					->where('approved', 1)
					->with('replies', function ($query) {
						$query->where('approved', 1);
					});
			})
			->get();

		// echo '<pre>';die(json_encode($comments, JSON_PRETTY_PRINT));
		$pagePayload->siteManagement = getSiteManagement('blog');
		$navPayload = getNavSiteManagement();
		return view('site.pages.blog.blogViewPage', [
			'pagePayload' => $pagePayload,
			'post' => $blog,
			'comments' => $comments,
			'navPayload'  => $navPayload
		]);
	}

	public function saveComment(Request $request, Blog $blog) {
		$comment = new BlogComment();
		$comment->blog_id = $blog->id;

		$post = $request->all();

		$comment->fill($post)->save();

		return redirect()->route('blog.show', ['blog' => $blog->slug]);
	}
}
