<?php

namespace App\Http\Controllers\Settings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\MenuModelPermission;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Yajra\DataTables\DataTables;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
        $this->middleware('permission:role-list|role-create|role-edit|role-delete', ['only' => ['index','store']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Role::select(['id','name'])->where('name', '!=', 'SuperAdmin')->paginate(10);
        if ($request->ajax()) {
            $sort_by   = $request->get('sortby');
            $sort_type = $request->get('sorttype');
            $query     = $request->get('query');

            if(!empty($query) && !empty($sort_by) && $query!=" ")
            {
              $data = Role::query()->select(['id','name'])->where('name', 'like', '%'.$query.'%')->where('name', '!=', 'SuperAdmin')->paginate($sort_by);
            }
            elseif($sort_by)
            {
              $data = Role::select(['id','name'])->where('name', '!=', 'SuperAdmin')->paginate($sort_by);
            }
            else
            {
              $data = Role::select(['id','name'])->where('name', '!=', 'SuperAdmin')->paginate(10);
            }
            return view('roles.table', compact('data'));
        }
        else
        {
            return view('roles.index',compact('data'));
        }

    }

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $modulePermissions = \Session::get('modulePermissions');
        $modules = MenuModelPermission::with("permissions", "childModules")
            ->where('parent_id', null)
            ->whereIn('code', $modulePermissions)
            ->orderBy('priority','ASC')
            ->get();

        return view('roles.create', compact('modules'));
    }

    /**
     * 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',
            // 'permission' => 'required',
        ]);
        $permissions = [];
        $permissions = $request->input('permission');

        $role = Role::create(['name' => $request->input('name')]);
        $role->syncPermissions($permissions);

        return redirect()->route('roles.index')
                        ->with('success','Role created successfully');
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $role = Role::find($id);
        $rolePermissions = Permission::join("role_has_permissions","role_has_permissions.permission_id","=","permissions.id")
            ->where("role_has_permissions.role_id",$id)
            ->get();

        return view('roles.show',compact('role','rolePermissions'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $modulePermissions = \Session::get('modulePermissions');
        $role            = Role::find($id);
        $permission      = Permission::get();
        $modules         = MenuModelPermission::with("permissions", "childModules")
            ->where('parent_id', null)
            ->whereIn('code', $modulePermissions)
            ->orderBy('priority','ASC')
            ->get();

        $rolePermissions = $role->permissions->pluck('name')->toArray();

        return view('roles.edit',compact('role','permission','rolePermissions','modules'));
    }

    /**
     * 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',
            // 'permission' => 'required',
        ]);*/
        $permissions = [];
        $permissions = $request->input('permission');
        $role = Role::find($id);
        /*$role->name = $request->input('name');
        $role->save();*/

        $role->syncPermissions($permissions);

        $session = $this->setPermissionSession();
        return redirect()->route('roles.index')->with('success','Role updated successfully');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        Role::where('id',$request->id)->delete();
        $Redirect = 'roles';
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
    }

    public function editRole(Request $request, $id)
    {
        $role    = Role::find($id);
        $modules = MenuModelPermission::select(['code','menu_name'])
            ->where('parent_id', null)
            ->orderBy('priority','ASC')
            ->get();

        return view('roles.edit-role', compact('role','modules'));
    }

    public function updateRole(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:roles,name,'.$id,
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->route('roles.index')->with('error', $validator->getMessageBag()->first());
        }

        $role = Role::find($id);

        $role->update(['name' => $request->name]);

        if(isset($request->landing_page_code) && $request->landing_page_code != '') {
            $role->update(['landing_page_code' => $request->landing_page_code]);
        }

        return response()->json([
            'success'=>true,
            'message'=>'Role updated successfully'
        ]);
    }

    public function setPermissionSession()
    {
        $roles = Auth::user()->roles->pluck('id')->all();

            $rolePermissions = Permission::select('permissions.name')
                ->join("role_has_permissions","role_has_permissions.permission_id","=","permissions.id")
                ->whereIn("role_has_permissions.role_id", $roles)
                ->groupBy('permissions.id')
                ->get();

            $permissionsArray = $rolePermissions->pluck('name')->mapWithKeys(function ($permission) {
                return [$permission => $permission];
            })->toArray();

            Session::put('rolePermissions', $permissionsArray);
    }
}
