<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\AppSession;

class EnsureNoValidSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //if not valid session, redirect to /pro/request-sms-login-token
        $sessionKey = $request->cookie("sessionKey");

        if(!$sessionKey){
            return $next($request);
        }

        $appSession = AppSession::where("session_key",$sessionKey)->first();

        if(!$appSession){
            return $next($request);
        }

        if(!$appSession->is_active){
            return $next($request);
        }

        return redirect("/dashboard");

    }
}
