<?php

namespace App\Http\Middleware;

use Closure;

use App\Models\AppSession;

class EnsureValidClientSession
{
    /**
     * 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");

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

        if(!$appSession){
            return $this->redirectToLogIn();
        }

        if(!$appSession->is_active){
            return $this->redirectToLogIn();
        }

        if ($appSession->session_type !== 'CLIENT') {
            return $this->redirectToLogIn();
        }

        return $next($request);
    }

    private function redirectToLogIn(){
        return redirect("/join");
    }
}
