<?php

namespace App\Http\Controllers\Master;

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

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

		return view('backend.pages.master.rayon.index', [
			'rayons' => Rayon::with('cabang')->get()
		]);
  }

	public function create()
	{
		$this->checkAuthorization(auth()->user(), ['rayon.create']);
		return view('backend.pages.master.rayon.create', [
			'cabangs' => Cabang::all()
		]);
	}

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

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

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

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

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

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

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

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

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