<?php

namespace App\Http\Controllers\Master;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Kategori;
use App\Helpers\AuditTrailHelper;

class CategoryController extends Controller
{
  public function index()
  {
		$this->checkAuthorization(auth()->user(), ['category.view']);
		session()->put('redirect_url', route('admin.category.index'));

		return view('backend.pages.master.category.index', [
			'categories' => Kategori::all()
		]);
  }

	public function create()
	{
		$this->checkAuthorization(auth()->user(), ['category.create']);
		return view('backend.pages.master.category.create');
	}

	public function store(Request $request)
	{
		$this->checkAuthorization(auth()->user(), ['category.create']);
		$request->validate([
			'name' => 'required|unique:kategori,name',
			'account_number' => 'required|unique:kategori,account_number'
		]);

		Kategori::create([
			'name' => $request->name,
			'account_number' => $request->account_number
		]);

		AuditTrailHelper::AddAuditTrail('Insert', 'Insert New Record at Category Table (' . $request->name . ')');
		session()->flash('success', 'Category has been created.');
		return redirect()->back();
	}

	public function edit($id)
	{
		$this->checkAuthorization(auth()->user(), ['category.edit']);
		return view('backend.pages.master.category.edit', [
			'category' => Kategori::findOrfail($id)
		]);
	}

	public function update(Request $request, $id)
	{
		$this->checkAuthorization(auth()->user(), ['category.edit']);
		$request->validate([
			'name' => 'required|unique:kategori,name,' . $id . ',id',
			'account_number' => 'required|unique:kategori,account_number,' . $id . ',id'
		]);

		Kategori::findOrfail($id)->update([
			'name' => $request->name,
			'account_number' => $request->account_number
		]);

		AuditTrailHelper::AddAuditTrail('Update', 'Update Record at Category Table (' . $request->name . ')');
		session()->flash('success', 'Category has been updated.');
		return redirect()->back();
	}

	public function destroy($id)
	{
		$this->checkAuthorization(auth()->user(), ['category.delete']);
		$kategori = Kategori::findOrfail($id);
		$kategori->delete();

		AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Category Table (' . $kategori->name . ')');
		session()->flash('success', 'Category has been deleted.');
		return redirect()->back();
	}
}