<?php

namespace App\Http\Middleware;

use App\MultiProject;
use Closure;
use Zizaco\Entrust\Middleware\EntrustPermission;

use Illuminate\Support\Facades\Auth;

 

class CustomEntrustMiddleware extends  EntrustPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $permissions, $validateAll = false)
    {
        // Get the project ID from the request
        // return $next($request);
        $projectId = $request->cookie('current_project_id');
      
        if(empty($projectId)){
        $mproject=  MultiProject::where('name','like','Super Admin')->first();     
          
            if(empty($mproject)){
                abort(403);
            }
           
            $projectId=  $mproject->id;
            $user = Auth::user();
        //     $role = $user->roles()->whereHas('projects', function ($query) use ($projectId) {
        //         $query->where('multi_project_id', $projectId);
        //     })      
        //   ->first(); 
        $role = $user->roles()
        ->whereHas('projects', function ($query) use ($projectId) {
            $query->where('multi_project_id', $projectId);
        })
        ->get()
        ->filter(function ($r) use ($permissions) {
            return $r->hasPermission($permissions);
        });
            if (!$user || !$role || (sizeof($role) == 0)) {
                abort(403, 'Unauthorized action.');
            }
            $permission_= encrypt($permissions);
            $request->merge([
                'permission' =>$permission_,
                 
            ]);
            // dd(encrypt($mproject->id));
            setcookie('current_project_id',  encrypt( $mproject->id),time() + 86400, '/');
            $response = $next($request);

            // Add the encrypted project ID as a cookie to the response
            return $response->withCookie(cookie('current_project_id', encrypt( $mproject->id)));
                // return $next($request);

            
        }
    //    $decrypt_id= $projectId;
    try{
        $projectId= decrypt($projectId);
    }
    catch(\Exception $e){
        abort(403, 'Unauthorized action.'); 
    }
      
      
       
      
        $user = Auth::user();
        $role = $user->roles()
    ->whereHas('projects', function ($query) use ($projectId) {
        $query->where('multi_project_id', $projectId);
    })
    ->get()
    ->filter(function ($r) use ($permissions) {
        return $r->hasPermission($permissions);
    });
 
    //     $role = $user->roles()->whereHas('projects', function ($query) use ($projectId) {
    //         $query->where('multi_project_id', $projectId);
    //     })      
    //   ->first();
      
        if (!$user || !$role || (sizeof($role) == 0)) {
            abort(403, 'Unauthorized action.');
        }
       $permission_= encrypt($permissions);
        $request->merge([
            'permission' =>$permission_,
             
        ]);
      
            return $next($request);
       

       
    }
    
}
