<?php

namespace App\Http\Controllers\Backend\userRole;

use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\User;
use Auth;
use DB;

class RoleController extends Controller
{
    function __construct()
    {
         $this->middleware('permission:role-list|role-create|role-edit|role-delete', ['only' => ['index','show']]);
         $this->middleware('permission:role-create', ['only' => ['create','store']]);
         $this->middleware('permission:role-edit', ['only' => ['edit','update']]);
         $this->middleware('permission:role-delete', ['only' => ['destroy']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if(Auth::user()->role == 'superadmin'){
            $roles = Role::whereNotIn('name', ['superadmin'])->get();
        }elseif(Auth::user()->role == 'admin'){
            $roles = Role::whereNotIn('name', ['superadmin','admin'])->get();
        }else{
            $userRoleName = Auth::user()->role;
            $roles = Role::whereNotIn('name', ['superadmin','admin',$userRoleName])->get();
        }
        
        return view('admin.userRole.roles.index',compact('roles'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $permissions = Permission::get();
        $permissionGroups = User::getpermissionGroups();

        return view('admin.userRole.roles.create',compact('permissions','permissionGroups'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {   
        $this->validate($request, [
            'name' => 'required|unique:roles,name',
            'permissions' => 'nullable',
        ]);
        
        $roleName = strtolower($request->input('name'));
        $role = Role::create(['name' => $roleName , 'guard_name'=> 'web']);
        $role->syncPermissions($request->input('permissions'));

        Toastr::success('Role Updated Successfully.', 'Success', ["progressbar" => true]);
        return redirect()->route('roles.index')->with('message','Successfully User Updated');
       
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
       //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $role = Role::find($id);
        $allPermissions = Permission::get();
        $rolePermissions = DB::table("role_has_permissions")->where("role_has_permissions.role_id",$id)
            ->pluck('role_has_permissions.permission_id','role_has_permissions.permission_id')
            ->all();
        $permissionGroups = User::getpermissionGroups();

        return view('admin.userRole.roles.edit',compact('role','allPermissions','rolePermissions','permissionGroups'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|unique:roles,name, '.$id,
            'permissions' => 'nullable',
        ]);
        
        $role = Role::find($id);
        $roleName = strtolower($request->input('name'));

        //To check role is superadmin or admin or user...
        if($roleName != $role->name){
            if (in_array($role->name, ['superadmin', 'admin'])) {
                Toastr::error('Sorry, This role name you can not change.!', 'Error', ["progressbar" => true]);
                return redirect()->back();
            }else{
                $role->name = $roleName;
            }
        }else{
            $role->name = $roleName;
        }

        if($role->save()){
            $role->syncPermissions($request->input('permissions'));
            
            Toastr::success('Role Updated Successfully.', 'Success', ["progressbar" => true]);
            return redirect()->route('roles.index')->with('message','Successfully User Updated');
        }else{
            Toastr::error('Soething is wrong!.', 'Error', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Role::find($id);
        if($role->delete()){
            return redirect()->route('roles.index')->with('message','Successfully Role Deleted');;
        }else{
            return redirect()->back();
        }
        
    }
}
