<?php

namespace App\Http\Controllers;

use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoleController extends GenericController
{
    public function __construct()
    {
        $this->setModel(new Role());
    }

    public function index(){
        return parent::getListView();
    }

    public function ajaxList(Request $request){
        return parent::dataList($request);
    }

    public function save(Request $request)
    {
        $role =  new Role();
        if($request->get('_id')!=0) $role = Role::find($request->get('_id'));

        //dd($request);

        $role->nom = $request->get('name');
        if($role->save()){
            $menus = DB::table('menus')->select('*')->get();
            $role->menus()->detach();
            foreach($menus as $menu){
                if($request->has('aut_'.$menu->id)){
                    $role->menus()->attach($menu->id);
                }
            }
        }
        return redirect()->back()->with('success','Operation performed successfully');
    }
}