<?php
/*
 * Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva
 * Fideliza — Proxy reverso pra rotear:
 *   http://177.23.184.123:8085/fideliza-proxy.php/xxx
 * pra
 *   http://127.0.0.1:8086/xxx
 * no mesmo servidor 24h.
 *
 * Usa streams HTTP nativos do PHP (não depende de curl nem mod_rewrite).
 * Path vem via PATH_INFO ($_SERVER['PATH_INFO']) ou ?path=.
 */

// Path alvo — prioridade: PATH_INFO > ?path=
$path = '';
if (!empty($_SERVER['PATH_INFO'])) {
    $path = ltrim((string)$_SERVER['PATH_INFO'], '/');
} elseif (!empty($_GET['path'])) {
    $path = ltrim((string)$_GET['path'], '/');
    unset($_GET['path']);
}

$qs = $_GET;

$target = 'http://127.0.0.1:8086/' . $path;
if (!empty($qs)) $target .= '?' . http_build_query($qs);

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

// Body: repassa bruto pra qualquer método com corpo
$body = '';
if (!in_array($method, ['GET', 'HEAD'], true)) {
    $body = file_get_contents('php://input') ?: '';
}

// Reconstrói headers do request
$hdrLines = [];
foreach ($_SERVER as $k => $v) {
    if (!is_string($v)) continue;
    if (strpos($k, 'HTTP_') === 0) {
        $name = str_replace('_', '-', substr($k, 5));
        $lc = strtolower($name);
        if (in_array($lc, ['host', 'connection', 'content-length', 'accept-encoding', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto'], true)) continue;
        // Cabeça-hífen: manter capitalização "canônica" (não crítica pra HTTP)
        $hdrLines[] = $name . ': ' . $v;
    }
}
if (!empty($_SERVER['CONTENT_TYPE'])) $hdrLines[] = 'Content-Type: ' . $_SERVER['CONTENT_TYPE'];
$hdrLines[] = 'X-Real-IP: ' . ($_SERVER['REMOTE_ADDR'] ?? '');
$hdrLines[] = 'X-Forwarded-Via: fideliza-proxy';

$ctx = stream_context_create([
    'http' => [
        'method'         => $method,
        'header'         => implode("\r\n", $hdrLines),
        'content'        => $body,
        'ignore_errors'  => true,  // pega body mesmo em 4xx/5xx
        'timeout'        => 60,
        'follow_location'=> 0,
    ],
]);

$respBody = @file_get_contents($target, false, $ctx);
if ($respBody === false) {
    http_response_code(502);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'ok'   => false,
        'erro' => 'proxy: falha ao contactar backend Fideliza',
        'alvo' => $target,
        'hint' => 'servidor 8086 pode não estar rodando',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// $http_response_header é auto-populado pela stream HTTP
$httpCode = 200;
// Prefixo público — pra reescrever Location: /master → Location: /fideliza-proxy.php/master
$scriptPrefixo = '/fideliza-proxy.php';
foreach ($http_response_header ?? [] as $linha) {
    if (preg_match('#^HTTP/[\d.]+\s+(\d+)#', $linha, $m)) {
        $httpCode = (int)$m[1];
        continue;
    }
    if (strpos($linha, ':') === false) continue;
    $nome = strtolower(trim(strtok($linha, ':')));
    if (in_array($nome, ['transfer-encoding', 'content-length', 'connection', 'content-encoding'], true)) continue;

    // Reescreve Location absoluto (path-only, começando com /) pra ir via proxy.
    // Ex: "Location: /master" → "Location: /fideliza-proxy.php/master"
    // Se já for URL absoluta http:// ou path já com prefixo, mantém.
    if ($nome === 'location') {
        $valor = trim(substr($linha, strpos($linha, ':') + 1));
        if (strlen($valor) > 0 && $valor[0] === '/' && strpos($valor, $scriptPrefixo) !== 0) {
            $linha = 'Location: ' . $scriptPrefixo . $valor;
        }
    }

    // Reescreve Set-Cookie: path=/ → path=/fideliza-proxy.php pra cookie ficar no escopo do proxy
    if ($nome === 'set-cookie') {
        $linha = preg_replace('#(;\s*[Pp]ath\s*=\s*)/([;\s]|$)#', '$1' . $scriptPrefixo . '$2', $linha);
        // Se não tinha Path=, adiciona o do proxy pra evitar cookie global
        if (stripos($linha, 'path=') === false) {
            $linha .= '; Path=' . $scriptPrefixo;
        }
    }

    header($linha, false);
}

http_response_code($httpCode);
echo $respBody;
