<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use App\Models\AppSession;

class EnsureUserLoggedIn
{
    public function handle(Request $request, Closure $next)
    {
        //if user is not logged in redirect to /login
        $sessionKey = Cookie::get(config('app.sessionKeyName'));

        if(!User::isLoggedIn($sessionKey)){
            return redirect(route('log-in'));
        }

        $appSession = AppSession::where('session_key', $sessionKey)->first();
        $user = $appSession->user;
        if($user->is_password_temporary){
            // return redirect(route('update-password'));
        }

        return $next($request);
    }
}
