<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
header('Content-Type: application/json');

// Si es una solicitud OPTIONS, terminar aquí
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Recopilar toda la información de headers
$debug_info = [
    'method' => $_SERVER['REQUEST_METHOD'],
    'all_headers' => getallheaders(),
    'server_auth' => $_SERVER['HTTP_AUTHORIZATION'] ?? 'not set',
    'php_auth_user' => $_SERVER['PHP_AUTH_USER'] ?? 'not set',
    'php_auth_pw' => $_SERVER['PHP_AUTH_PW'] ?? 'not set',
    'redirect_auth' => $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? 'not set',
    'all_server_vars' => []
];

// Buscar cualquier variable que contenga "AUTH" o "authorization"
foreach ($_SERVER as $key => $value) {
    if (stripos($key, 'AUTH') !== false || stripos($key, 'authorization') !== false) {
        $debug_info['all_server_vars'][$key] = $value;
    }
}

// Método alternativo para Apache
if (function_exists('apache_request_headers')) {
    $headers = apache_request_headers();
    foreach ($headers as $header => $value) {
        if (strcasecmp($header, 'Authorization') == 0) {
            $debug_info['apache_auth'] = $value;
        }
    }
}

// Intentar obtener el header de diferentes formas
$auth_header = null;

// Método 1: HTTP_AUTHORIZATION
if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
    $auth_header = $_SERVER['HTTP_AUTHORIZATION'];
    $debug_info['found_via'] = 'HTTP_AUTHORIZATION';
}
// Método 2: REDIRECT_HTTP_AUTHORIZATION (común en Apache con mod_rewrite)
elseif (!empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
    $auth_header = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    $debug_info['found_via'] = 'REDIRECT_HTTP_AUTHORIZATION';
}
// Método 3: getallheaders()
elseif (function_exists('getallheaders')) {
    $headers = getallheaders();
    if (isset($headers['Authorization'])) {
        $auth_header = $headers['Authorization'];
        $debug_info['found_via'] = 'getallheaders()[Authorization]';
    } elseif (isset($headers['authorization'])) {
        $auth_header = $headers['authorization'];
        $debug_info['found_via'] = 'getallheaders()[authorization]';
    }
}
// Método 4: apache_request_headers()
elseif (function_exists('apache_request_headers')) {
    $headers = apache_request_headers();
    foreach ($headers as $header => $value) {
        if (strcasecmp($header, 'Authorization') == 0) {
            $auth_header = $value;
            $debug_info['found_via'] = 'apache_request_headers';
            break;
        }
    }
}

$debug_info['final_auth_header'] = $auth_header ?? 'NOT FOUND';

echo json_encode($debug_info, JSON_PRETTY_PRINT);
?>