<?php

namespace App\Http\Middleware;

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

class EnsureRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  ...$roles  Allowed roles for this route
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        $user = $request->user();

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

        // Check if user has one of the allowed roles
        if (!in_array($user->role, $roles)) {
            abort(403, 'No tienes permiso para acceder a esta página.');
        }

        // Check if coach is active (not pending or suspended)
        if ($user->isCoach() && !$user->isActive()) {
            if ($user->isPending()) {
                return redirect()->route('pending.approval')
                    ->with('warning', 'Tu cuenta está pendiente de aprobación.');
            }
            
            abort(403, 'Tu cuenta ha sido suspendida. Contacta al administrador.');
        }

        return $next($request);
    }
}
