<?php
 
namespace App\Http\Middleware;

use App\Helpers\Security;
use App\Models\SecurityEvent;
use App\Providers\RouteServiceProvider;

use App\Notifications\SlackNotification;

use Closure;
use Notification;
 
class Bouncer
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $role
     * @return mixed
     */

    public function handle($_request, Closure $_next, ...$_bounceable)
    {
        // Kill the session if the user is not allowed to login.
        /*if(!$_request->user()->canLogin()) {
            Auth::logout();

            return response()->json(['detail' => 'Suspended Account'], 401);
        }*/

        if($_request->user()->canDo($_bounceable)) {
            if($_request->method() != 'GET') {
                SecurityEvent::create([
                    'user_id'       => $_request->user()->id,
                    'ip'            => Security::real_ip(),
                    'user_agent'    => $_request->userAgent(),
                    'route'         => $_request->path(),
                    'payload'       => $_request->input('password') ? 'OBSCURED FOR SECURITY' : json_encode($_request->input()),
                    'description'   => 'Successful pass requiring: '  . join(', ', $_bounceable),
                ]);
            }

            return $_next($_request);
        }

        SecurityEvent::create([
            'user_id'       => $_request->user()->id,
            'ip'            => Security::real_ip(),
            'user_agent'    => $_request->userAgent(),
            'route'         => $_request->path(),
            'payload'       => $_request->input('password') ? 'OBSCURED FOR SECURITY' : json_encode($_request->input()),
            'description'   => 'Failed pass requiring: '  . join(', ', $_bounceable) . 'using method: ' . $_request->method(),
        ]);

        Notification::route('slack', env('SECURITY_HOOK'))->notify(new SlackNotification('['. env('SLACK_NAME') .'] BOUNCER ALERT: ' . Security::real_ip() . ' failed to access ' . $_request->path() . ' using ' . $_request->header('user-agent') . ' which requires: ' . join(', ', $_bounceable)));

        return response()->json(['detail' => 'Insufficient Permissions'], 401);
        
    }
 
}