<?php

namespace App\Http\Middleware;

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

// ══════════════════════════════════════════════════════════════════
//  EnsureMember Middleware
//
//  Protects all member routes.
//  Applied AFTER the 'auth' and 'verified' middleware.
//
//  Checks two things:
//    1. The user has the 'member' role (not an unrecognised role)
//    2. The user account is active (not suspended by admin)
//
//  Why check is_active?
//    If Mahmoud needs to suspend a member (spam, abuse etc.)
//    he sets is_active = false in the admin panel.
//    This middleware immediately blocks that member on
//    their next request — no need to delete the account.
// ══════════════════════════════════════════════════════════════════

class EnsureMember
{
    public function handle(Request $request, Closure $next): Response
    {
        // Double-check user is authenticated
        if (! auth()->check()) {
            return redirect()->route('login');
        }

        $user = auth()->user();

        // Check account is active
        if (! $user->is_active) {
            auth()->logout();

            $request->session()->invalidate();
            $request->session()->regenerateToken();

            return redirect()->route('login')
                ->withErrors([
                    'email' => __('auth.account_suspended'),
                ]);
        }

        // Admins should never access member routes directly
        // They have their own admin panel
        if ($user->isAdmin()) {
            return redirect()->route('admin.dashboard');
        }

        return $next($request);
    }
}
