<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\AppSession;

class EnsureOnlyStrangerSession
{
    /**
     * 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);
        }

        if ($appSession->session_type === 'STRANGER') {
            return $next($request);
        }

        if ($appSession->session_type === 'PRO')
            return redirect("/dashboard");
        else
            return redirect("/");

    }
}
