<?php

namespace App\Http\Controllers\Master;

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

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

		return view('backend.pages.master.region.index', [
			'region' => Region::with('head')->get()
		]);
  }

	public function create()
	{
		$this->checkAuthorization(auth()->user(), ['region.create']);
		return view('backend.pages.master.region.create', [
			'users' => Admin::getUserWhereRoleIsNot('Medical Representatif')
		]);
	}

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

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

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

	public function edit($id)
	{
		$this->checkAuthorization(auth()->user(), ['region.edit']);
		return view('backend.pages.master.region.edit', [
			'region' => Region::findOrfail($id),
			'users' => Admin::getUserWhereRoleIsNot('Medical Representatif')
		]);
	}

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

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

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

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

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