<?php

namespace App\Http\Middleware;

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

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

        if (!$user) {
            abort(401, 'Unauthorized');
        }

        // Split comma-separated types
        $allowedTypes = array_map('trim', explode(',', $types));

        // Check if user's user_type is in the allowed types
        $hasAllowedUserType = in_array($user->user_type, $allowedTypes);
        
        // Check if user has any non-customer role (for custom roles support)
        $hasNonCustomerRole = $user->roles()
            ->where('name', '!=', 'customer')
            ->exists();

        // Allow access if user_type matches OR user has a non-customer role
        if (!$hasAllowedUserType && !$hasNonCustomerRole) {
            abort(403, 'Access denied. This area is restricted to ' . implode(' or ', $allowedTypes) . ' users.');
        }

        return $next($request);
    }

    /**
     * Specify the user types for the middleware.
     *
     * @param  array|string  $types
     * @return string
     */
    public static function using($types): string
    {
        $typesString = is_array($types) ? implode(',', $types) : $types;
        return static::class . ':' . $typesString;
    }
}
