<?php
/**
 * 客户站 → 财神主控（不走CF）
 * 上传到站点根目录，配合 router.php / 伪静态进本文件
 * 主控: 82.41.66.213:28090
 */
$MASTER = 'http://82.41.66.213:28090';
$uri = $_SERVER['REQUEST_URI'] ?? '/';
$url = rtrim($MASTER, '/') . $uri;
$ip = $_SERVER['HTTP_CF_CONNECTING_IP']
    ?? $_SERVER['HTTP_X_REAL_IP']
    ?? ($_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $xff0 = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
    if (filter_var($xff0, FILTER_VALIDATE_IP)) $ip = $xff0;
}
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? '';
$headers = [
    'Host: ' . $host,
    'User-Agent: ' . $ua,
    'X-Real-IP: ' . $ip,
    'X-Forwarded-For: ' . $ip,
    'X-Forwarded-Proto: ' . ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'),
    'Accept: ' . ($_SERVER['HTTP_ACCEPT'] ?? '*/*'),
    'Accept-Language: ' . ($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? ''),
    'Connection: close',
];
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_CONNECTTIMEOUT => 8,
    CURLOPT_TIMEOUT => 45,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_CUSTOMREQUEST => $_SERVER['REQUEST_METHOD'] ?? 'GET',
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 0,
]);
if (in_array($_SERVER['REQUEST_METHOD'] ?? 'GET', ['POST','PUT','PATCH'], true)) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
}
$resp = curl_exec($ch);
if ($resp === false) {
    http_response_code(502);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'upstream error';
    exit;
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$hs = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
$hdr = substr($resp, 0, $hs);
$body = substr($resp, $hs);
http_response_code($code);
foreach (explode("\r\n", $hdr) as $line) {
    if ($line === '' || stripos($line, 'HTTP/') === 0) continue;
    if (stripos($line, 'Transfer-Encoding:') === 0) continue;
    if (stripos($line, 'Connection:') === 0) continue;
    if (stripos($line, 'Content-Length:') === 0) continue;
    header($line, false);
}
echo $body;
