<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Http\Requests\StoreCategoryRequest;
use App\Http\Requests\UpdateCategoryRequest;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    function __construct()
    { 

    $this->middleware('permission:show category', ['only' => ['index']]);
    $this->middleware('permission:add category', ['only' => ['create','store']]);
    $this->middleware('permission:update category', ['only' => ['edit','update']]);
    $this->middleware('permission:delete category', ['only' => ['destroy']]);

    }

    public function index()
    {
        $categories =  Category::all();
        return view('pages.Categories.index',compact('categories'));
    }

   
    public function create()
    {
        //
    }

    public function store(StoreCategoryRequest $request)
    {
        //
    }

    public function show(Category $category)
    {
        //
    }

    public function edit(Category $category)
    {
        //
    }

    public function update(UpdateCategoryRequest $request, Category $category)
    {
        //dd($request->all());
        try {

            $validated = $request->validated();
            $category = Category::findOrFail($request->id);
           
            $category->name = $request->name;
            $category->save();

            toastr()->success(trans('messages.Update'));
            return redirect()->route('categories.index');
        }
        catch
        (\Exception $e) {
            return redirect()->back()->withErrors(['error' => $e->getMessage()]);
        }

    }

    public function destroy(Request $request)
    {
        try {
            
            $category = Category::where('id',$request->id)->first();
            $category->delete();
            toastr()->error(trans('messages.Delete'));
           return redirect()->route('categories.index');
       }

       catch (\Exception $e){
       return redirect()->back()->withErrors(['error' => $e->getMessage()]);
       }
    }


}
