<?php

// Configurar zona horaria de México
date_default_timezone_set('America/Mexico_City');

// Archivo de entrada alternativo con CORS completo
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");

// Manejar preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Pasar el header Authorization a $_SERVER si no está disponible
if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
    // Primero intentar con X-Auth-Token (más compatible con cPanel)
    if (isset($_SERVER['HTTP_X_AUTH_TOKEN'])) {
        $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer ' . $_SERVER['HTTP_X_AUTH_TOKEN'];
    } elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
        $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    } elseif (function_exists('apache_request_headers')) {
        $headers = apache_request_headers();
        if (isset($headers['X-Auth-Token'])) {
            $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer ' . $headers['X-Auth-Token'];
        } elseif (isset($headers['Authorization'])) {
            $_SERVER['HTTP_AUTHORIZATION'] = $headers['Authorization'];
        } elseif (isset($headers['authorization'])) {
            $_SERVER['HTTP_AUTHORIZATION'] = $headers['authorization'];
        }
    } elseif (function_exists('getallheaders')) {
        $headers = getallheaders();
        if (isset($headers['X-Auth-Token'])) {
            $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer ' . $headers['X-Auth-Token'];
        } elseif (isset($headers['Authorization'])) {
            $_SERVER['HTTP_AUTHORIZATION'] = $headers['Authorization'];
        } elseif (isset($headers['authorization'])) {
            $_SERVER['HTTP_AUTHORIZATION'] = $headers['authorization'];
        }
    } else {
        foreach ($_SERVER as $key => $value) {
            if (stripos($key, 'x_auth_token') !== false) {
                $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer ' . $value;
                break;
            } elseif (stripos($key, 'authorization') !== false) {
                $_SERVER['HTTP_AUTHORIZATION'] = $value;
                break;
            }
        }
    }
}

// Redirigir al API principal
$path = $_GET['path'] ?? '';
$_GET['path'] = $path;
require_once 'reportes/funciones_php/api.php';
?>
