<?php

namespace App\Http\Controllers\Api\Hrms\Roles;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use \App\Models\Hrms\UserRole;
use \App\Models\Hrms\UserPermissions;
use Validator;
use Auth;

class RolesPermissionController extends Controller
{
    //UserRole
    public function rolesCreateUpdate(Request $request){

        $auth=Auth::user();

        $validator=validator($request->all(),[
            'role_name'=>'required',
            'status'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first(),
            ];

        } else {

            try{

                $data=[
                    'role_name','status',
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                if($request->id>0){

                    try{
                        $roles=UserRole::findOrFail($request['id']);
                        $roles->update($obj);

                    } catch (\Exception $e) {
                        return response(['error' => true, 'message' => 'Invalid Id to update'], 404); 
                    }
                }else{

                    $checkRoles=UserRole::where('role_name',$request['role_name'])->where('is_disabled','0')
                            ->where('organisation_id',$auth['active_organisation'])
                            ->first();

                    if($checkRoles !=null){

                        $response=[
                            'message'=>"Roles already exist",
                            'success'=>false,
                            'vendor'=>$checkRoles
                        ];

                        return response()->json($response);
                    }

                    $roles=UserRole::create($obj);
                }

                return response()->json([
                    'status'=>200,
                    'message'=> $request->id>0 ? 'Roles update successfully':'Roles created cuccessfully',
                    'roles'=>$roles
                ],200);
                
            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }


    public function getRoles(Request $request){

        $user=Auth::user();

        if($user!=null){

            $roleList=UserRole::where('is_disabled','0')
               ->where('organisation_id',$user['active_organisation']);

            $roleList=$this->fetchuserbyquery($roleList,$request);
            $count=$roleList->count();
            $sortOrder = ($request['sortOrder'] == 1) ? 'desc' : 'asc'; 
            $sortBy = $request['sortBy'] ?? 'id'; 

            $roleList = $roleList->orderby($sortBy,$sortOrder)
                ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                ->get();

            $response=[
                'roleList'=>$roleList,
                'count'=>$count,
                'message'=>'Successful',
            ];

        } else {
            $response=[
                'roleList'=>$roleList,
                'count'=>$count,
                'message'=>'Invalid User'
            ];
        }

        return response()->json($response);
    }
    
    // Filter Users
    public function fetchuserbyquery($roleList,$request){

        if(isset($request['search']) && $request['search']!='') {
            $keyword = "%".$request['search']."%";
            $roleList = $roleList->whereRaw(" (role_name like ? or status like ?) ", 
            array($keyword , $keyword));
        }

        // get custom_date data by transaction_date
        if ($request['status']!='' && isset($request['status'])) {
            $status = $request->status;
            $roleList = $roleList->where('status', $status);
        }

        // get custom_date data by transaction_date
        if ($request['custom_date']!='' && isset($request['custom_date'])) {
            $customDate = $request->custom_date;
            $roleList = $roleList->whereDate('created_at', $customDate);
        }

        // get fromDate toDate data by created_at
        if ($request['fromDate']!='' && isset($request['toDate'])) {
            $fromDate = $request->fromDate;
            $toDate = $request->toDate;
        
            // 'fromDate' and 'toDate'
            $roleList = $roleList->whereBetween('created_at', [$fromDate, $toDate]);
        }

        return $roleList;
    }

    public function detailsRoles(Request $request){

        $auth=Auth::user();

        try{

            $roleList=UserRole::where('id',$request['id'])
                ->where('organisation_id',$auth['active_organisation'])
                ->first();

            $response=[
                'success'=>true,
                'roleList'=>$roleList
            ];

            return response()->json($response);

        } catch (\Exception $e) {
            return response(['error' => true, 'message' => $e->getMessage()], 404); 
        }
    }

    public function deleteRoles(Request $request){

        $auth=Auth::user();
        
        $validator=validator($request->all(),[
           'id'=>'required|integer'
        ]);

       if ($validator->fails()) { 
           return [
               'success' => false, 
               'message' => $validator->errors()->first(),
           ];

       } else {

           try{
                $roleList =  UserRole::where('id',$request->input('id'))
                                        ->where('organisation_id',$auth['active_organisation'])
                                        ->first();

                $roleList['is_disabled']='1';
                $roleList->update();

                $response=[
                    'success'=>true,
                    'message'=>'Role Deleted successfully.'
                ];

                return response()->json($response);

            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
       }
    }



    //UserPermissions
    public function permissionsCreateUpdate(Request $request){

        $auth=Auth::user();

        $validator=validator($request->all(),[
            'role_id'=>'required',
            'modules' => 'required|array',
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first(),
            ];

        } else {

            try{

                $data=[
                    'role_id','modules','role_name'
                ];
                
                foreach ($data as $key => $value) {
                    if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                        $obj[$value]=$request[$value];
                    }
                }

                $obj['modules'] = isset($request['modules']) ? json_encode($request['modules']) : null;

                if($request->id>0){

                    try{
                        $permissions=UserPermissions::findOrFail($request['id']);
                        $permissions->update($obj);

                    } catch (\Exception $e) {
                        return response(['error' => true, 'message' => 'Invalid Id to update'], 404); 
                    }
                }else{

                    $checkPermissions=UserPermissions::where('role_id',$request['role_id'])
                    ->where('is_disabled','0')->where('organisation_id',$auth['active_organisation'])->first();

                    if($checkPermissions !=null){

                        $response=[
                            'message'=>"Permissions already exist",
                            'success'=>false,
                            'vendor'=>$checkPermissions
                        ];

                        return response()->json($response);
                    }

                    $permissions=UserPermissions::create($obj);
                }

                return response()->json([
                    'status'=>200,
                    'message'=> $request->id>0 ? 'Permissions update successfully':'Permissions created cuccessfully',
                    'permissions'=>$permissions
                ],200);
                
            } catch (\Exception $e) {
                return response(['error' => true, 'message' => $e->getMessage()], 404); 
            }
        }
    }

    public function getPermissions(Request $request){

        $user=Auth::user();

        if($user!=null){

            $permissionList=UserPermissions::where('is_disabled','0')
               ->where('organisation_id',$user['active_organisation']);

            $count=$permissionList->count();
            $sortOrder = ($request['sortOrder'] == 1) ? 'desc' : 'asc'; 
            $sortBy = $request['sortBy'] ?? 'id'; 

            $permissionList = $permissionList->orderby($sortBy,$sortOrder)
                ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                ->get();

            $response=[
                'permissionList'=>$permissionList,
                'count'=>$count,
                'message'=>'Successful',
            ];

        } else {
            $response=[
                'permission_list'=>$permissionList,
                'count'=>$count,
                'message'=>'Invalid User'
            ];
        }

        return response()->json($response);
    }
}
