<?php

namespace App\Http\Middleware;

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

/**
 * Middleware CORS para compatibilidade com diferentes origens
 * 
 * Este middleware garante que a API funcione corretamente
 * com diferentes clientes e em ambientes como cPanel.
 * 
 * @author Manus AI Assistant
 * @version 1.0
 */
class CorsMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Para requisições OPTIONS (preflight), retorna resposta imediata
        if ($request->getMethod() === 'OPTIONS') {
            return response('', 200)
                ->header('Access-Control-Allow-Origin', '*')
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-authorization, X-Authorization, X-Requested-With')
                ->header('Access-Control-Max-Age', '86400');
        }

        $response = $next($request);

        // Adiciona headers CORS à resposta
        $response->headers->set('Access-Control-Allow-Origin', '*');
        $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-authorization, X-Authorization, X-Requested-With');
        $response->headers->set('Access-Control-Expose-Headers', 'Authorization');

        return $response;
    }
}

