<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Illuminate\Contracts\Encryption\DecryptException;
use Auth;
use DB;
use App\User;
use EF;

class PermissionController extends Controller
{
    public function index()
    {
      
    	return view('permission.manage_permission',['permission_list' => $this::getAllPermission()]);

    }

    public function storePermission(Request $request)
    {
        if(isset($request->pass) && $request->pass == "reqtocreateper")
        {
            if($request->isMethod('post') && $request->ajax())
            {
    

                $call_back = ['status' => false, 'message' => NULL];

                parent::successMessage('Required Validation.');

                $object = $request->input();

                $request->validate([

                    'module'         => 'required|min:0|max:255|in:'.implode(',',EF::getModuleList()),
                    'feature'        => 'required|min:0|max:255|unique:permissions,name',
                ]);


                if(DB::table('permissions')->where(['module' => $request->module, 'name' => $request->name])->count() == 0)
                {
                    DB::transaction(function () use ($object) {

                        $data = [

                            'name'   => $object['feature'],
                            'module' => $object['module']
                        ];


                        Permission::create($data);

                    });


                    $call_back['status']  = true;

                    $call_back['message'] = 'Permission has created succssfully';


                }
                else
                {
                    $call_back['message'] = 'Permission has already found';
                }


                return $call_back;

            }
            else
            {
                return view('permission.add_permission',[

                    'permission_list' => DB::table('permissions')->orderBy('module','asc')->get()

                ]);
            }
        }

        return redirect()->back();
    }

    // public function storePermission(Request $request)
    // {
    // 	parent::successMessage('Required Validation.');

    // 	$object = $request->input();
    	

    // 	$flag = DB::transaction(function () use ($object) {

	//     	$data = [

	//     		'name'   => $object['feature'],
	//     		'module' => $object['module']

	//     	];


    //     	Permission::create($data);
            
    //     });

    // 	if($flag)
    // 	{
    // 		parent::successMessage('Permission has been created.');
    // 	}


    // 	return redirect()->back();

    // }


    public function updatePermission(Request $request)
    {
    	parent::successMessage('Required Validation.');

    	try
    	{
    		$object = $request->input();

    		$object['permission'] = decrypt($object['permission']);

    		$flag = DB::transaction(function () use ($object) {

		    	$data = [

		    		'name'   => $object['feature'],
	    			'module' => $object['module']

		    	];

		    	$permission = Permission::find($object['permission']);

		    	if(isset($permission))
		    	{
	        		$permission->update($data);
		    	}

	            
	        });

	    	if($flag)
	    	{
	    		parent::successMessage('Permission has been created.');
	    	}
		}
		catch (DecryptException $e) 
		{
		            
		}

    	
    	return redirect()->back();

    }

    public function storeAssignPermission(Request $request)
    {
        try
        {
            parent::errorMessage('Try again!');

            $flag = false;

            $count = 0;

            $assign_permisson_list = [];

            $form_collect = $request->input();

            $permission_list = $this->getAllPermission();


            $user_id = decrypt($form_collect['user']);

            $user = new User;

            $user = $user->getUserById($user_id);

            if(isset($user->id))
            {
                if(isset($form_collect['permission_list']))
                {
                    $assign_permisson_list = $form_collect['permission_list'];
                }

                dd($assign_permisson_list);

                foreach ($permission_list as $permission) 
                {
                    $flag = false;

                    $count = 0;

                    foreach ($assign_permisson_list as $hasPermission) 
                    {

                        if($permission->id == $hasPermission)
                        {
                            if(!$user->hasAnyPermission([$hasPermission]))
                            {
                                $user->givePermissionTo($hasPermission);

                            }

                            unset($assign_permisson_list[$count]);

                            $flag = true;

                            break;
                        }

                        $count++;
                    }

                    if($flag == false && $permission->name != "All")
                    {
                        if($user->hasAnyPermission($permission->id))
                        {
                            $user->revokePermissionTo($permission->id);
                        }
                    }
                }

                parent::successMessage('Permission has been granted');
            }


        }
        catch (DecryptException $e) 
        {
                    
        }

        return redirect()->back();
    }

    function assignPermission($user,$permission)
    {
        
        if(\Request::ajax())
        {
            $flag = 'false';

            try 
            {

                $permission = decrypt($permission);

                $user_id       = decrypt($user);

                $user = new User;

                $user = $user->getUserById($user_id);

                $permission = Permission::find($permission); 


                if(isset($user->id) && isset($permission->id))
                {

                    if($user->hasAnyPermission($permission->id))
                    {

                       $user->revokePermissionTo($permission->id);

                        $flag = 'unchecked';
                    }
                    else
                    {
                        $user->givePermissionTo($permission->id);

                        $flag = 'checked';

                    }


                }
                
            } 
            catch (DecryptException $e) 
            {
                
            }

            return json_encode($flag);
        }

 
        return redirect()->back();
    }

    public function assignModulePermission($user,$module,$flag)
    {
        if(\Request::ajax())
        {
            try
            {
                $user_id = decrypt($user);
                $module  = decrypt($module);

                $user = new User;

                $user = $user->getUserById($user_id);

                if(isset($user->id))
                {
                    $permission_list = $this->getPermissionByModule($module); 
                    
                    foreach($permission_list as $rows)
                    {
                        if($flag == "true")
                        {
                           if(!$user->hasAnyPermission($rows->id))
                           {
                              $user->givePermissionTo($rows->id);
                           }  
                        }
                        else if($flag == "false")
                        {
                            $user->revokePermissionTo($rows->id);

                        } 

                    }

                    $flag = "true";

                    
                }

                

            } 
            catch (DecryptException $e) 
            {
                
            }

            return $flag;
        }
    }

    public function getModuleWisePermission($user,$module)
    {

    	return view('permission.module_wise_permission',
    		[
    			'permission_list' => $this->getPermissionByModule($module),
    			'module' => $module,
    			'user'   => $user
    		]
    	);
    }

    function showAssignPermission($id)
    {
    	if(\Request::ajax())
    	{

            try 
            {
                $view = '<input type="hidden" name="user" value="'.$id.'">';

                $id = decrypt($id);

                $user = new User;

                $user = $user->getUserById($id);

                if(isset($user->id))
                {
                	foreach (EF::getModuleList() as $rows) 
	                {
	                    $view.= $this->getModuleWisePermission($user,$rows);
	                }

                	return $view;

                }
            } 
            catch (DecryptException $e) 
            {
                
            }

			
    	}

    	return redirect()->back();
    }


    // DB PART 
    public function getAllPermission()
    {
    	return Permission::orderBy('id','asc')->get();
    }

    public function getPermissionByModule($module)
    {
    	return Permission::where('module',$module)->orderBy('id','asc')->get();
    }
    // END DB PART
}
