<?php

namespace App\Http\Middleware;


use Closure;
use Session;
use DB;
use App\SystemUsers;
use App\Designation;

class CheckLogin
{
     /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

  public function handle($request, Closure $next)
    {
        if (!$request->session()->has('current_user')) {
            return redirect(url('/admin-login'))->withErrors("You need to be logged in");
        }

        $id = Session::get('current_user.user_id');
        $system_user = SystemUsers::find((int) $id);

        $privillage_keys = [];
        
        if ($system_user) {
            $privillages = json_decode($system_user->privillages);
            $collection = collect($privillages)->map(function ($privillage) {
                return $privillage->id;
            })->toArray();

            $privillage_keys = array_merge($collection, $privillage_keys);
        
            $designation = Designation::find((int) $system_user->designation);
            if ($designation) {
                $privillages = json_decode($designation->privillages);
                $collection = collect($privillages)->map(function ($privillage) {
                    return $privillage->id;
                })->toArray();
                
                $privillage_keys = array_merge($collection, $privillage_keys);
                // dd($privillage_keys);
                Session::put('current_user.privillages.keys', $privillage_keys);
            } else {
                Session::put('current_user.privillages.keys', $privillage_keys);
            }

        }
       
        return $next($request);
    }
}
