<?php

namespace App\Http\Controllers;

use App\CustomClass\Helper;
use App\Models\ClientRole;
use App\Models\Menu;
use App\Models\RoleWiseMenu;
use App\Models\RoleWiseService;
use App\Models\Services;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
class AccessControlController extends Controller
{
    public function index(){
        $user= Auth::user();
        $clientId= $user->client_id;
        $roles= ['0'=>'Select Role'] + ClientRole::where('client_id',$clientId)->pluck('title', 'id')->all();
        $detailsRole=ClientRole::with('updatedBy')->where('client_id',$clientId)->orderBy('title','ASC')->get();
        return view('backend.accessControl.index',compact('roles','detailsRole'));
    }
    public function roleCreateModal(){
        return view('backend.accessControl.roleCreateModal');
    }
    public function roleSave(Request $request){
        $clientId= Auth::user()->client_id;
        $exist= ClientRole::where('title',$request->role_title)->where('client_id',$clientId)->count();
        if($exist){
            return redirect()->back()->with('error','This role already registered!');
        }
        $n= new ClientRole;
        $n->title= $request->role_title;
        $n->summary= $request->summary;
        $n->client_id= $clientId;
        $n->created_by= Auth::id();
        $n->updated_by= Auth::id();
        $n->save();
        return redirect()->back()->with('success','New role created successfully!');
    }

    public function roleEditModal( $id){
        $role= ClientRole::where('client_id',Auth::user()->client_id)->where('id',$id)->first();
        if($role){
            return view('backend.accessControl.roleEditModal')->with('role',$role);
        }

    }
    public function roleUpdate( Request $request){
        try {
            $role = ClientRole::where('client_id', Auth::user()->client_id)->where('id', $request->id)->first();
            if ($role) {
                $exists= ClientRole::where('client_id', Auth::user()->client_id)->where('title', $request->role_title)->where('id','!=',$request->id)->first();

                if($exists){
                    return redirect()->back()->with('error','This role already exists!');
                }
                $role->title= $request->role_title;
                $role->summary= $request->summary;
                $role->updated_by= Auth::id();
                $role->save();
                return redirect()->back()->with('success','Role updated successfully!');
            }
        }
        catch (\Exception $e){
            return $e;
        }
    }
    public function deleteRole( $roleId){
        $remain= ClientRole::where('client_id', Auth::user()->client_id)->count();
        if($remain==1){
            return redirect()->back()->with('error','Sorry You can\'t delete all role!');
        }
        $exists= ClientRole::where('client_id', Auth::user()->client_id)->where('id', $roleId)->first();
        if($exists){
            ClientRole::destroy($roleId);
            return redirect()->back()->with('success','Role deleted successfully!');
        }else{
            return redirect()->back()->with('error','Sorry You are not author of this Account!');
        }

    }

    public function loadMenuByRole($clientRoleId){
        if($clientRoleId==0){
            return "<h3 style='margin-top:100px; text-align: center;'>Please select Role for permission !</h3>";
        }
        $validation= ClientRole::where('id',$clientRoleId)->where('client_id',Auth::user()->client_id)->count();
        if($validation<1){
            return "<h3 style='margin-top:100px; text-align: center;'>Sorry ! You are trying in wrong way</h3>";
        }
        $existsMenu= RoleWiseMenu::with('menus')->where('client_wise_role_id',$clientRoleId)->get();
        $menus= Menu::orderBy('view_order','ASC')->get();
        return view('backend.accessControl.loadMenu',compact('existsMenu','menus','clientRoleId'));
    }

    public function loadServiceByRole($clientRoleId){
        if($clientRoleId==0){
            return "<h3 style='margin-top:100px; text-align: center;'>Please select Role for permission !</h3>";
        }
        $validation= ClientRole::where('id',$clientRoleId)->where('client_id',Auth::user()->client_id)->count();
        if($validation<1){
            return "<h3 style='float:left ;text-align: center; width: 100%;'>Sorry ! You are trying in wrong way</h3>";
        }
        $existsService= RoleWiseService::with('service')->where('client_wise_role_id',$clientRoleId)->get();
        $services= Services::orderBy('title','ASC')->get();
        return view('backend.accessControl.loadService',compact('existsService','services','clientRoleId'));
    }
    public function updateMenuByRole(Request $request){
        $existsMenus=[];
        $clientRoleId=$request->clientRoleId;
        $roleWiseMenu= RoleWiseMenu::with('menus')->where('client_wise_role_id',$clientRoleId)->get();
        foreach ($roleWiseMenu as $value){
            $existsMenus[]=$value->menus->id;
        }
        $newMenu= count($request['newMenuId'])>0?$request['newMenuId']: [] ; //1 2
        $insertedMenu= array_diff($newMenu,$existsMenus); //will insert
        $deletedMenu= array_diff($existsMenus,$newMenu); //will delete
        if(count($deletedMenu)>0){
            RoleWiseMenu::where(function ($query) use ($deletedMenu,$clientRoleId) {
                    $query->whereIn('system_menu_id',$deletedMenu)
                        ->where('client_wise_role_id',$clientRoleId);
                })
                ->delete();
        }
        if(count($insertedMenu)>0){
            foreach($insertedMenu as $val){
                $insert= new RoleWiseMenu;
                $insert->client_wise_role_id=$clientRoleId;
                $insert->system_menu_id=$val;
                $insert->created_by=Auth::id();
                $insert->updated_by=Auth::id();
                $insert->save();
            }

        }
        return redirect()->back()->with('success','Permission operation successful!');

    }
    public function updateServiceByRole(Request $request){
        $existsService=[];
        $clientRoleId=$request->clientRoleId;
        $roleWiseService= RoleWiseService::with('service')->where('client_wise_role_id',$clientRoleId)->get();
        foreach ($roleWiseService as $value){
            $existsService[]=$value->service->id;
        }
        $newService= count($request['newServiceId'])>0?$request['newServiceId']: [] ; //1 2
        $insertedService= array_diff($newService,$existsService); //will insert
        $deletedService= array_diff($existsService,$newService); //will delete
        if(count($deletedService)>0){
            RoleWiseService::where(function ($query) use ($deletedService,$clientRoleId) {
                $query->whereIn('system_service_id',$deletedService)
                    ->where('client_wise_role_id',$clientRoleId);
            })
                ->delete();
        }
        if(count($insertedService)>0){
            foreach($insertedService as $val){
                $insert= new RoleWiseService;
                $insert->client_wise_role_id=$clientRoleId;
                $insert->system_service_id=$val;
                $insert->created_by=Auth::id();
                $insert->updated_by=Auth::id();
                $insert->save();
            }

        }
        return redirect()->back()->with('success','Permission operation successful!');

    }
    public function permission( $roleId){
        $role= ClientRole::where('client_id',Auth::user()->client_id)->where('id',$roleId)->first();
        if($role){
            return view('backend.accessControl.permission')->with('role',$role);
        }
        return redirect()->back()->with('error','Access denied!');

    }
    public function permissionSave( Request $request){
        //return Helper::urlGroupCheck(1,["designation.index","designation.create","designation.store"]);
        /*
                 * Menu Array Pattern: menuName#route#icon
                 * Route Array Pattern: only unique route names
                 * */
        $newArray=[]; //contain all menu and submenu
        $newRoutes=[];
        $menuArray=[
            'dashboard'=>'dashboard#pe-7s-graph',
            'user'=>'user#pe-7s-users',
            'rota_setup'=>'rota-setup#pe-7s-news-paper',
            'leave_exchange_manage'=>'leave-manage#pe-7s-next-2',
            'reports'=>'null#pe-7s-note2',
            'basic_setup'=>'null#pe-7s-tools', //route#icon
            'my_rota'=>'my-rota#pe-7s-news-paper',
            'my_report'=>'my-report#pe-7s-news-paper',
            'event_setup'=>'event#pe-7s-date',
            'leave_or_exchange'=>'user-leave#pe-7s-next-2',
            'access_control'=>'acl#pe-7s-unlock',
        ];

//Routes making start because after sub menu making I have to put menu's route into route array
        if(isset($request->routes)){
            foreach ($request->routes as $routes){
                $routes= json_decode($routes);
                foreach ($routes as $route){
                    $newRoutes[]=$route;
                }
            }
            $newRoutes= array_unique($newRoutes);
            $newRoutes= array_values($newRoutes);
        }


//Menu submenu making start
        foreach ($menuArray as $menu=>$value){
            if(isset($request->$menu)){
                if(is_array($request->$menu)) {
                    foreach ($request->$menu as $menuJson) {
                        $newArray[$menu . "#" . $value][] = $menuJson; //menuName#route#icon
                    }
                }else{
                    $newArray[$menu . "#" . $value] = 'null';
                    $internalRoute= json_decode($request->$menu,true);
                    if(is_array($internalRoute)){ //other url in the main menu page
                        foreach ($internalRoute['others'] as $other){
                            $newRoutes[]=$other;
                            $newRoutes[]=$internalRoute['route']; //route name of main menu
                        }
                    }else{
                        $newRoutes[]=$request->$menu;
                    }

                }
            }
        }
        if(count($newRoutes)>0){
            $newRoutes= array_unique($newRoutes);
        }
        $role= ClientRole::where('id',$request->role_id)->where('client_id',Auth::user()->client_id)->first();
        if($role){
            $role->menus= json_encode($newArray);
            $role->routes= json_encode($newRoutes);
            $role->updated_by=Auth::id();
            $role->save();
            return redirect()->back()->with('success','Data updated successfully!');
        }

    }

}
