<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class CheckUserDataMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check()) {
            $user = Auth::user();
            if (
                empty(trim($user->firstname)) ||
                empty(trim($user->lastname)) ||
                empty(trim($user->username)) ||
                (Str::length(trim($user->phone)) < 5) ||
                empty(trim($user->address1)) ||
                empty(trim($user->address2)) ||
                empty(trim($user->city)) ||
                (Str::length(trim($user->zip)) < 2) ||
                empty(trim($user->region))
            ) {
                return redirect()->route('member.account')
                    ->with('failed', 'Please complete your user data!');
            }
        }
        return $next($request);
    }
}
