<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

class Permission extends BaseModel
{
    protected $fillable=['user_id' ,'submodule_id'];
    use HasFactory;

    public function getPermittedSubmoduleIdListByUserId($user_id){

        return self::where('user_id',$user_id)->pluck('submodule_id');
    }

    public  function insertUserPermission($inputData)
    {
        $result = [];

        $roleDatas = $inputData['userRole'];

        $returnData = [];

        if(!empty($roleDatas)) {

            $user_permission_delete = self::where('user_id' , $inputData['employee_id'])->delete();

            foreach ($roleDatas as $roleData)
            {
                $insertData = [ 'user_id' => $inputData['employee_id'] , 'submodule_id' => $roleData] ;
                $returnData = self::create($insertData);
            }

            $result['data'] = $returnData;
        }

        return $result;
    }
    public function getModuleByUserId($user_id,$type){
        if($type > 1)
        {
            return Module::select(['modules.id','modules.name'])
                ->join('submodules', 'submodules.module_id', '=', 'modules.id')
                ->join('permissions', 'permissions.submodule_id', '=', 'submodules.id')
                ->where('permissions.user_id',$user_id)
                ->groupBy('modules.id','modules.name')
                ->pluck('modules.name');
        }else {
            return Module::where('status', 1)->pluck('name');
        }

    }
    public function getPermissionByUserId($user_id,$only_key){
        $query = Module::select(['modules.id as module_id','modules.name as module_name','submodules.key',
           'submodules.id as submodule_id','submodules.name as submodule_name',
           'permissions.id as permission_id', 'permissions.user_id as user_id' ])
           ->join('submodules', 'submodules.module_id', '=', 'modules.id')
           ->join('permissions', 'permissions.submodule_id', '=', 'submodules.id')
           ->where('permissions.user_id',$user_id);
            if(!empty($only_key)) {
                $result =  $query->pluck($only_key);
            }else{
                $result =  $query->get();
            }

        return $result;
    }
    public function getRouteNameListByUserId($user_id){
        $permissions = $this->getPermissionByUserId($user_id,'submodules.key');
        $route_list = [];
        $system_config_route_key_list = config('route_keys');

        if(!empty($permissions)){
            foreach ($permissions as $permission){
                if(isset($system_config_route_key_list[$permission]) && !empty($system_config_route_key_list[$permission])){
                    $route_list = array_merge($route_list,$system_config_route_key_list[$permission]);
                }
            }
        }

        return $route_list;
    }
}
