<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\BlogRepository;

class BlogController extends Controller
{
    protected $blogRepo;
    public function __construct(BlogRepository $blogRepository)
    {
        $this->blogRepo = $blogRepository;
    }


    public function index()
    {

        return $this->blogRepo->indexPage();
    }

    public function createPage()
    {
        return $this->blogRepo->createPage();

    }

    public function edit($id)
    {
        return $this->blogRepo->editPage($id);

    }

    public function store(Request $request)
    {
        $request->validate([
            'heading' => 'required|max:255',
            'description' => 'required',
            'blog_image' => 'required|image'
        ]);
        try {
            $review = $this->blogRepo->create($request->all());
            if ($request->hasFile('blog_image')) {
                $review->addMediaFromRequest('blog_image')->toMediaCollection('blog_image');
            }
            return redirect()->route('admin.blog.list')->with('success', 'Blog Successfully Added');
        } catch (\Exception $e) {
            dd($e->getMessage());
            return redirect()->back()->with('error', $e->getMessage());
        }

    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'heading' => 'required|max:255',
            'description' => 'required',
        ]);
        try {
            $update = $this->blogRepo->update($request->all(), $id);
            if ($request->hasFile('blog_image')) {
                $update->clearMediaCollection('blog_image');
                $update->addMediaFromRequest('blog_image')->toMediaCollection('blog_image');
            }
            return redirect()->route('admin.blog.list')->with('success', 'Blog Successfully Updated');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());

        }

    }

    public function delete(Request $request)
    {
        $this->blogRepo->delete($request->id);
        return response()->json(['success' => 'Record successfully deleted!']);
    }
}
