<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class FixAuthorizationHeader
{
    public function handle(Request $request, Closure $next)
    {
        // 🧩 Algunos hostings no pasan HTTP_AUTHORIZATION, así que lo restauramos manualmente
        if (! $request->headers->has('Authorization')) {
            $auth = null;

            // Apache puede guardarlo en REDIRECT_HTTP_AUTHORIZATION
            if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
                $auth = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
            } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
                $auth = $_SERVER['HTTP_AUTHORIZATION'];
            } elseif (function_exists('apache_request_headers')) {
                $headers = apache_request_headers();
                if (isset($headers['Authorization'])) {
                    $auth = $headers['Authorization'];
                }
            }

            if ($auth) {
                $request->headers->set('Authorization', $auth);
            }
        }

        return $next($request);
    }
}
