<?php

namespace App\Http\Middleware;

use Closure;
use App\User;

class Permissions
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next, $perm)
  {
    if($perm == "SHARE"){
      if ($request->user() == null){
        \View::share('allperms', []);
        \View::share('adminpages', []);
        return $next($request);
      }
      \View::share('allperms', $request->user()->getPerms());
      \View::share('adminpages', $request->user()->getAdmin());
      return $next($request);
    }
    if( $request->user()->hasPerm($perm)){
      return $next($request);
    }else{
      return redirect('/')->with('message','You don\'t have permission to access this page');
    }
  }
}
