<?php

namespace App\Http\Middleware;

use Closure;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class CorsMiddleware

{
    // public function handle($request, Closure $next)
    // {
    //     $headers = [];
    //     $headers['Access-Control-Allow-Origin']  = '*';
    //     $headers['Access-Control-Allow-Methods']     = 'POST, GET, OPTIONS, PUT, DELETE';
    //     $headers['Access-Control-Allow-Credentials'] = 'true';
    //     $headers['Access-Control-Max-Age']           = '86400';
    //     $headers['Access-Control-Allow-Headers']     = 'Content-Type,Token,Id, X-Requested-With';

    //     if ($request->isMethod('OPTIONS')) {
    //         return response('', 200, $headers);
    //     }
    //     $response = $next($request);
    //     foreach ($headers as $key => $value) {
    //         $response->header($key, $value);
    //     }
    //     return $response;
    // }
    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Token, Id, X-Requested-With',
        ];

        if ($request->isMethod('OPTIONS')) {
            return response('', 200)->withHeaders($headers);
        }

        $response = $next($request);

        // Verificar si la respuesta es una instancia de BinaryFileResponse
        if ($response instanceof BinaryFileResponse) {
            foreach ($headers as $key => $value) {
                $response->headers->set($key, $value);
            }
        } else {
            foreach ($headers as $key => $value) {
                $response->header($key, $value);
            }
        }

        return $response;
    }
}
