<?php

namespace App\Http\Middleware;

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

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Always allow these routes (public routes)
        $publicRoutes = [
            '/',
            'login',
            'register',
            'password/reset*',
            'email/verify*',
            'logout'
        ];

        foreach ($publicRoutes as $route) {
            if ($request->is($route)) {
                return $next($request);
            }
        }

        // If user isn't authenticated, redirect to login
        if (!Auth::check()) {
            return redirect()->route('login');
        }

        // Get the authenticated user
        $user = $request->user();

        // If user is admin, allow access
        if ($user->role === 'admin') {
            return $next($request);
        }

        // If user is trying to access admin routes but isn't admin
        if ($request->is('admin*')) {
            // Redirect to role-specific dashboard
            return $this->redirectToRoleDashboard($user->role);
        }

        // For all other authenticated users, allow access to non-admin routes
        return $next($request);
    }

    /**
     * Redirect user to their role-specific dashboard
     */
    protected function redirectToRoleDashboard(string $role): Response
    {
        $routeMap = [
            'passenger' => 'passenger.dashboard',
            'captain' => 'captain.dashboard',
            // Add other roles as needed
        ];

        return redirect()->route(
            $routeMap[$role] ?? 'dashboard' // Fallback to default dashboard
        );
    }
}