<?php

namespace App\Http\Controllers;
use App\Models\Area;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\Role;

class AreaController extends Controller
{

    public function __construct() {
    $this->middleware('can:area.index')->only('index','show');
    $this->middleware('can:area.create')->only('create','store');
    $this->middleware('can:area.edit')->only('edit','update');
    $this->middleware('can:area.destroy')->only('destroy');
    }
    public function index()
    {
        $areas = Area::all();
        return view('area.index',compact('areas'));
    }

    public function create()
    {
        $roles = Role::all();
        return view('area.create',compact('roles'));
    }


    public function store(Request $request)
    {
        $request->validate([
            'name'=>'required'
        ]);

        $area = Area::create($request->except(['roles']));

        $area->areas()->sync($request->roles);

        return redirect()->route('area.edit',$area)->with('info','El área se creo correctamente');
    }


    public function show(area $area)
    {
        return view('area.show',compact('area'));
    }


    public function edit(area $area)
    {
        $roles = Role::all();
        return view('area.edit',compact('area','roles'));
    }


    public function update(Request $request, area $area)
    {
        $request->validate([
            'name'=>'required'
        ]);

        $area->update($request->except(['roles']));

        $area->areas()->sync($request->roles);

        return redirect()->route('area.edit',$area)->with('info','El área se actualizo correctamente');
    }


    public function destroy(area $area)
    {
        $area->areas()->detach();
        $area->delete();
        session()->flash('swal',[
            'icon'=>'success',
            'title'=>'Eliminado!',
            'text'=>'Se ha eliminado el registro correctamente'
        ]);
        return redirect()->route('area.index');
    }
}
