<?php
/*
 * Depto de Engenharia e Automação - Master Automação - Autor: Derlivon Silva
 * CashVolta — Landing + proxy unificado.
 * Prefixo público /cashvolta/* → backend em localhost:8086.
 */
$prefixo = '/cashvolta';
$path = ltrim((string)($_SERVER['PATH_INFO'] ?? ''), '/');

/* Landing quando path vazio */
if ($path === '') {
    ?><!doctype html>
    <html lang="pt-BR"><head><meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CashVolta</title>
    <style>body{font-family:system-ui;background:linear-gradient(160deg,#0f172a,#1e1b4b);color:#f1f5f9;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:20px}
    .box{max-width:480px;width:100%;text-align:center}
    .logo{font-size:4rem;margin-bottom:.5rem}h1{color:#f59e0b;font-size:2.5rem;margin:0 0 .3rem}
    .sub{color:#94a3b8;margin-bottom:2.5rem}
    .card{display:block;background:rgba(30,41,59,.85);border:1px solid rgba(255,255,255,.08);border-radius:14px;padding:1.4rem 1.5rem;margin-bottom:1rem;text-decoration:none;color:#f1f5f9}
    .card:hover{border-color:#f59e0b}
    .card .titulo{font-size:1.2rem;font-weight:700;color:#f59e0b;margin-bottom:.3rem}
    .card .desc{color:#94a3b8;font-size:.9rem}
    .rodape{color:rgba(148,163,184,.4);font-size:.75rem;margin-top:2rem}</style>
    </head><body><div class="box">
    <div class="logo">💵</div><h1>CashVolta</h1>
    <div class="sub">Cashback que traz o cliente de volta</div>
    <a href="/cashvolta/master/login" class="card">
      <div class="titulo">🎛️ Painel Master</div>
      <div class="desc">Gerenciar lojistas, criar acessos, gerar chaves de tablet</div></a>
    <a href="/cashvolta/lojista/login" class="card">
      <div class="titulo">🏪 Painel do Lojista</div>
      <div class="desc">Dashboard executivo, clientes, configurações do programa</div></a>
    <div class="rodape">Depto de Engenharia e Automação</div>
    </div></body></html>
    <?php
    exit;
}

/* Proxy pra localhost:8086/$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 = '';
if (!in_array($method, ['GET', 'HEAD'], true)) {
    $body = file_get_contents('php://input') ?: '';
}

$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;
        $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,
        '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: backend Fideliza fora do ar', 'alvo'=>$target], JSON_UNESCAPED_UNICODE);
    exit;
}

$httpCode = 200;
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: /master → /fideliza/master */
    if ($nome === 'location') {
        $valor = trim(substr($linha, strpos($linha, ':') + 1));
        if (strlen($valor) > 0 && $valor[0] === '/' && strpos($valor, $prefixo) !== 0) {
            $linha = 'Location: ' . $prefixo . $valor;
        }
    }

    /* Set-Cookie: path=/ → path=/fideliza */
    if ($nome === 'set-cookie') {
        $linha = preg_replace('#(;\s*[Pp]ath\s*=\s*)/([;\s]|$)#', '$1' . $prefixo . '$2', $linha);
        if (stripos($linha, 'path=') === false) {
            $linha .= '; Path=' . $prefixo;
        }
    }

    header($linha, false);
}

/* Reescreve HTML: href/action/src que começam com "/" viram "/fideliza/..." */
$ct = '';
foreach ($http_response_header ?? [] as $h) {
    if (preg_match('/^content-type:\s*(.+)$/i', trim($h), $m)) { $ct = strtolower($m[1]); break; }
}
if (strpos($ct, 'text/html') !== false && $respBody !== '') {
    $respBody = preg_replace_callback(
        '#\b(href|action|src|formaction)\s*=\s*"(/[^"]*)"#i',
        function ($m) use ($prefixo) {
            $url = $m[2];
            if (strpos($url, $prefixo . '/') === 0 || $url === $prefixo) return $m[0];
            if (strpos($url, '//') === 0) return $m[0];
            return $m[1] . '="' . $prefixo . $url . '"';
        },
        $respBody
    );
    // Também versão single-quote
    $respBody = preg_replace_callback(
        "#\b(href|action|src|formaction)\s*=\s*'(/[^']*)'#i",
        function ($m) use ($prefixo) {
            $url = $m[2];
            if (strpos($url, $prefixo . '/') === 0 || $url === $prefixo) return $m[0];
            if (strpos($url, '//') === 0) return $m[0];
            return $m[1] . "='" . $prefixo . $url . "'";
        },
        $respBody
    );
}

http_response_code($httpCode);
echo $respBody;