<?php

namespace App\Http\Controllers\Master;

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

class RayonController extends Controller
{
  public function index()
  {
		$this->checkAuthorization(auth()->user(), ['rayon.view']);
		return view('backend.pages.master.rayon.index', [
			'rayons' => Rayon::all()
		]);
  }

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

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

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

		session()->flash('success', 'Rayon has been created.');
		return redirect()->route('admin.rayon.index');
	}

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

	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'
		]);

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

		session()->flash('success', 'Rayon has been updated.');
		return redirect()->route('admin.rayon.index');
	}

	public function destroy($id)
	{
		$this->checkAuthorization(auth()->user(), ['rayon.delete']);
		Rayon::findOrfail($id)->delete();

		session()->flash('success', 'Rayon has been deleted.');
		return redirect()->route('admin.rayon.index');
	}
}