<?php

namespace App\Http\Controllers;

use App\Http\Requests\CategoryRequest;
use App\Models\Category;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\View;

class CategoryController extends Controller
{
    use AuthorizesRequests;

    public function index()
    {
        $this->authorize('viewAny', Category::class);

        return View::make('categories.index',
            ['categories' => Category::all()]);
    }

    public function create()
    {
        $this->authorize('create', Category::class);

        return View::make('categories.create');
    }

    public function store(CategoryRequest $request)
    {
        $this->authorize('create', Category::class);

        Category::create($request->validated());

        $request->session()->flash('status', 'Category added!');
        return Redirect::route('categories.index');
    }

    public function show(Category $category)
    {
        $this->authorize('view', $category);

        return View::make('categories.show', ['category' => $category]);
    }

    public function edit(Category $category)
    {
        $this->authorize('update', $category);

        return View::make('categories.edit', ['category' => $category]);
    }

    public function update(CategoryRequest $request, Category $category)
    {
        $this->authorize('update', $category);

        $category->update($request->validated());

        $request->session()->flash('status', 'Category updated!');
        return Redirect::route('categories.index');
    }

    public function destroy(Category $category)
    {
        $this->authorize('delete', $category);

        $category->delete();

        Request::session()->flash('status', 'Category deleted!');
        return Redirect::route('categories.index');
    }
}
