<?php

namespace App\Http\Controllers\Master;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;

class CategoriesController extends Controller
{
    public function __construct()
    {
        $this->middleware(['permission:branches.index'])->only('index');
        $this->middleware(['permission:branches.create'])->only('save');
        $this->middleware(['permission:branches.edit'])->only('update');
        $this->middleware(['permission:branches.delete'])->only('delete');
    }

    public function index()
    {
        $title = "category";
        $categories = Category::orderBy('id', 'desc')->get();

        return view('master.category', compact('title','categories'));
    }

    public function save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:categories'
        ]);

        $category = Category::create([
            'name' => $request->input('name'),
            'description' => $request->input('description')
        ]);

        if($category){
            //redirect dengan pesan sukses
            return redirect()->route('category')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('category')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function update(Request $request, Category $category)
    {
        $this->validate($request, [
            'name' => 'required|unique:categories,name,'.$category->id
        ]);

        $category = Category::findOrFail($category->id);
        $category->update([
            'name' => $request->input('name'),
            'description' => $request->input('description')
        ]);

        if($category){
            //redirect dengan pesan sukses
            return redirect()->route('category')->with(['success' => 'Data Berhasil Disimpan!']);
        }else{
            //redirect dengan pesan error
            return redirect()->route('category')->with(['error' => 'Data Gagal Disimpan!']);
        }
    }

    public function delete(Category $category)
    {
        $category->delete();

        return redirect()->route('category')->with('success', 'Data Berhasil Dihapus');
    }

}
