<?php

namespace App\Http\Middleware;

use App\Models\AppSession;
use Closure;

class ProAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $sessionKey = $request->cookie('sessionKey');
        $appSession = AppSession::where('session_key', $sessionKey)->where('is_active', true)->first();
        $authenticated = $sessionKey && $appSession;
        $currentRouteName = $request->route()->getName();

        if (!$authenticated) {
            return redirect()->route('login');
        }

        // - is_two_step_sms_auth_completed
        if (!$appSession->is_two_step_sms_auth_completed) {
            if ($currentRouteName != 'confirm_sms_auth_token' && $currentRouteName != 'post-confirm_sms_auth_token') {
                return redirect()->route('confirm_sms_auth_token');
            }
            return $next($request);
        }

        // - is_password_temporary
        if (!!$appSession->pro->is_password_temporary) {
            if ($currentRouteName != 'set_password' && $currentRouteName != 'post-set_password') {
                return redirect()->route('set_password');
            }
            return $next($request);
        }

        // - are_security_questions_set
        if (!$appSession->pro->are_security_questions_set) {
            if ($currentRouteName != 'set_security_questions' && $currentRouteName != 'post-set_security_questions') {
                return redirect()->route('set_security_questions');
            }
            return $next($request);
        }

        return $next($request);
    }
}
