<?php

namespace App\Http\Controllers\Master;

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

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

		return view('backend.pages.master.cost.index', [
			'costs' => CostCentre::all()
		]);
  }

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

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

		CostCentre::create([
			'code' => $request->code,
			'name' => $request->name
		]);

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

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

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

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

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

	public function destroy($id)
	{
		$this->checkAuthorization(auth()->user(), ['cost.delete']);
		$cost = CostCentre::findOrfail($id);
		AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Cost Centre Table (' . $cost->name . ')');

		$cost->delete();
		session()->flash('success', 'Cost has been deleted.');
		return redirect()->back();
	}
}