<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use App\Models\Role;
use App\Models\Permission;
use Validator;
use DB;
class RoleController extends Controller
{
    public function index(){

        $data['title1'] = "Roles List";
    	$data['title2'] = "Roles Add";
        $data['all_roles'] = Role::orderBy('display_name','ASC')->get();
    	$data['all_permissions'] = Permission::orderBy('display_name','ASC')->get();
    	return view('admin.role.index',$data);
    }
    public function store(Request $request){
        $this->validate($request,[
            'name'         => 'required|unique:roles,name',
            'display_name' => 'required',
            'permission' => 'required',
        ]);
        $role = new Role();
        $role->name         = $request->name;
        $role->display_name = $request->display_name;
        $role->save();
        if (!empty($request->input('permission'))) {
            foreach ($request->input('permission') as $key => $value) {
            $role->attachPermission($value);
            }
        }
        
        return back()->with('msg','Data Insert successful !');
    }
    public function edit($id){
        $data['title'] = "Role Edit";
        $data['role'] = Role::find($id);
        $data['all_permissions'] = Permission::get();
        $data['rolePermissions'] = $rolePermissions = DB::table("permission_role")->where("permission_role.role_id",$id)->lists('permission_role.permission_id','permission_role.permission_id');
        return view('admin.role.edit',$data);
    }

    public function update(Request $request,$id){
        $this->validate($request,[
            'name'         => 'required',
            'display_name' => 'required',
            'permission' => 'required',
        ]);
        $role = Role::find($id);
        $role->name         = $request->name;
        $role->display_name = $request->display_name;
        $role->update();

        if (!empty($request->input('permission'))) {
            DB::table("permission_role")->where("permission_role.role_id",$id)
            ->delete();
            foreach ($request->input('permission') as $key => $value) {
                $role->attachPermission($value);
            }
        }

 
        return redirect('admin/roles')->with('msg','Data Update successful !');
    }

    public function destroy($id){
    	Role::whereId($id)->delete();
    	return back()->with('msg','Data Delete successful !');
    }
}
