<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MemberAuthenticate
{
    public function handle(Request $request, Closure $next): mixed
    {
        if (! Auth::guard('web')->check()) {
            return redirect()->route('login');
        }

        $user = Auth::guard('web')->user();

        if (in_array($user->status, ['inactive', 'lapsed'])) {
            Auth::guard('web')->logout();
            return redirect()->route('login')->withErrors(['email' => 'Your membership is inactive. Please contact JAM Corner.']);
        }

        if ($user->status === 'suspended') {
            $msg = 'Your membership is currently suspended.';
            if ($user->suspended_until) {
                $msg .= ' Until ' . $user->suspended_until->format('d M Y') . '.';
            }
            Auth::guard('web')->logout();
            return redirect()->route('login')->withErrors(['email' => $msg]);
        }

        return $next($request);
    }
}
