<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckXenForoUserState
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if( \Auth::guest() )
            return $next($request);

        if( \Auth::user()->security_lock === 'change' )
            return $this->deny( $request, "Password must be changed." );
        else if( \Auth::user()->security_lock === 'reset' )
            return $this->deny( $request, "Password must be reset.");

        if( \Auth::user()->user_state === 'valid' )
            return $next($request);

        else if( \Auth::user()->user_state === 'email_confirm' || \Auth::user()->user_state === 'email_confirm_edit' )
            return $this->deny( $request, "You must verify your email address." );
        else if( \Auth::user()->user_state === 'email_bounce' )
            return $this->deny( $request, "Invalid email address." );
        else if( \Auth::user()->user_state === 'rejected' )
            return $this->deny( $request, "Your account is currently rejected." );
        else if( \Auth::user()->user_state === 'disabled' )
            return $this->deny( $request, "Your account is currently disabled." );

        return $this->deny($request, "Invalid user state.");
    }

    private function deny(Request $request, string $reason): Response
    {
        if($request->expectsJson())
            return \response()->json(['error' => 'forbidden', 'reason' => $reason], 403);

        return response()->view('pages.user_state', [
            'reason' => $reason,
        ], 403 );
    }
}
