<?php
/**
 * Función mejorada para obtener el header Authorization
 * Compatible con diferentes configuraciones de servidor
 */
function getAuthorizationHeader() {
    $authHeader = null;

    // Método 1: HTTP_AUTHORIZATION (estándar)
    if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $authHeader = $_SERVER['HTTP_AUTHORIZATION'];
    }
    // Método 2: REDIRECT_HTTP_AUTHORIZATION (Apache con mod_rewrite)
    elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $authHeader = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    }
    // Método 3: getallheaders() - función PHP
    elseif (function_exists('getallheaders')) {
        $headers = getallheaders();
        if (isset($headers['Authorization'])) {
            $authHeader = $headers['Authorization'];
        } elseif (isset($headers['authorization'])) {
            $authHeader = $headers['authorization'];
        }
    }
    // Método 4: apache_request_headers() - específico de Apache
    elseif (function_exists('apache_request_headers')) {
        $headers = apache_request_headers();
        foreach ($headers as $header => $value) {
            if (strcasecmp($header, 'Authorization') == 0) {
                $authHeader = $value;
                break;
            }
        }
    }
    // Método 5: PHP_AUTH_* (Basic Auth)
    elseif (isset($_SERVER['PHP_AUTH_USER'])) {
        $authHeader = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . ($_SERVER['PHP_AUTH_PW'] ?? ''));
    }

    return $authHeader;
}

/**
 * Extrae el token Bearer del header Authorization
 */
function getBearerToken() {
    $authHeader = getAuthorizationHeader();
    if ($authHeader) {
        if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
            return $matches[1];
        }
    }
    return null;
}

// Ejemplo de uso en tu API:
/*
// En lugar de:
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (empty($authHeader)) {
    $authHeader = getallheaders()['Authorization'] ?? '';
}

// Usa:
require_once 'get_auth_header.php';
$authHeader = getAuthorizationHeader();

// O si solo necesitas el token:
$token = getBearerToken();
*/
?>