<?php
header('Content-Type: application/json; charset=utf-8');

// CORS 头
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 处理 OPTIONS 请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 启动会话获取登录状态
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$cookieDomain = '';
if (preg_match('/(^|\.)catdsn\.com$/i', $host)) {
    $cookieDomain = '.catdsn.com';
}
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
session_set_cookie_params([
    'lifetime' => 60 * 60 * 24 * 30,
    'path' => '/',
    'domain' => $cookieDomain,
    'secure' => $secure,
    'httponly' => true,
    'samesite' => 'Lax',
]);
session_start();

$allow = array(
    'hall-post/index',
    'hall-post/worship-index',
    'hall-post/long-light-list',
    'user-post/user-center',
    'libation-post/libation-list',
    'libation-post/message-libation-list',
    'libation-post/get-user-memorial-record',
    'libation-post/get-record-by-libation-id',
    'libation-post/offer-libation',
    'libation-post/special-meal',
    'libation-post/huaquan-list',
    'message-post/add-message',
    'login/handle',
    'hall-page/xjd-bridge',
);

// 获取请求路径（支持 GET 和 POST）
$p = isset($_GET['p']) ? $_GET['p'] : '';
if (empty($p)) {
    // 尝试从 POST 数据中获取
    $postData = file_get_contents('php://input');
    parse_str($postData, $postParams);
    $p = isset($postParams['p']) ? $postParams['p'] : '';
}

// 获取访客ID（支持 Cookie 和 URL 参数）
function get_guest_id() {
    // 1. 检查 Cookie（优先）
    if (!empty($_COOKIE['sm_guest_id'])) {
        $guestId = preg_replace('/[^A-Za-z0-9_-]/', '', $_COOKIE['sm_guest_id']);
        if (strlen($guestId) >= 8) {
            return $guestId;
        }
    }
    
    // 2. 检查 URL 参数
    if (!empty($_GET['guest_id'])) {
        $guestId = preg_replace('/[^A-Za-z0-9_-]/', '', $_GET['guest_id']);
        if (strlen($guestId) >= 8) {
            return $guestId;
        }
    }
    
    // 3. 检查 POST 参数
    $postData = file_get_contents('php://input');
    parse_str($postData, $postParams);
    if (!empty($postParams['guest_id'])) {
        $guestId = preg_replace('/[^A-Za-z0-9_-]/', '', $postParams['guest_id']);
        if (strlen($guestId) >= 8) {
            return $guestId;
        }
    }
    
    // 4. 检查 Session
    if (!empty($_SESSION['user_email'])) {
        return md5($_SESSION['user_email']);
    }
    
    return null;
}

// 获取用户余额（统一管理）
function get_balance($userKey) {
    $dataFile = __DIR__ . '/data/user_balances.json';
    $list = [];
    if (is_readable($dataFile)) {
        $list = json_decode(file_get_contents($dataFile), true) ?: [];
    }
    if (!isset($list[$userKey])) {
        $list[$userKey] = ['money' => 0, 'gift_money' => 0];
    }
    return $list[$userKey];
}

// 保存余额
function save_balance($userKey, $money, $gift) {
    $dataFile = __DIR__ . '/data/user_balances.json';
    $list = [];
    if (is_readable($dataFile)) {
        $list = json_decode(file_get_contents($dataFile), true) ?: [];
    }
    $list[$userKey] = [
        'money' => round($money, 2),
        'gift_money' => round($gift, 2),
    ];
    $dir = dirname($dataFile);
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    @file_put_contents($dataFile, json_encode($list, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), LOCK_EX);
    return $list[$userKey];
}

// 获取祭品价格
function get_libation_price($libation_id) {
    $dataFile = __DIR__ . '/data/libation_prices.json';
    $list = [];
    if (is_readable($dataFile)) {
        $list = json_decode(file_get_contents($dataFile), true) ?: [];
    }
    return isset($list[$libation_id]) ? floatval($list[$libation_id]) : 0;
}

// 处理 libation-post/huaquan-list - 返回本地花圈数据（不需要登录）
if ($p === 'libation-post/huaquan-list') {
    $dataFile = __DIR__ . '/data/huaquan_list.json';
    if (is_readable($dataFile)) {
        $data = json_decode(file_get_contents($dataFile), true);
        if ($data) {
            echo json_encode(['code' => 1, 'data' => $data]);
            exit;
        }
    }
    echo json_encode(['code' => 0, 'message' => '获取花圈列表失败']);
    exit;
}

// 处理 user-post/user-center - 优先使用访客ID（与充值系统兼容）
if ($p === 'user-post/user-center') {
    // 优先从 POST 参数获取 guest_id
    $userKey = '';
    if (!empty($_POST['guest_id'])) {
        $userKey = preg_replace('/[^A-Za-z0-9_-]/', '', $_POST['guest_id']);
        if (strlen($userKey) < 8) $userKey = '';
    }
    // 其次从 Cookie/URL 获取
    if (empty($userKey)) {
        $userKey = get_guest_id();
    }

    if (!$userKey) {
        // 完全没有任何标识，返回默认值
        echo json_encode([
            'code' => 1,
            'data' => [
                'user_id' => '',
                'nickname' => '游客用户',
                'money' => 0,
                'gift_money' => 0,
            ]
        ]);
        exit;
    }

    // 获取本地余额
    $balance = get_balance($userKey);

    echo json_encode([
        'code' => 1,
        'data' => [
            'user_id' => $userKey,
            'nickname' => '孝爱用户',
            'money' => $balance['money'],
            'gift_money' => $balance['gift_money'],
        ]
    ]);
    exit;
}

// 处理 libation-post/offer-libation - 扣款
if ($p === 'libation-post/offer-libation') {
    // 优先从 POST 参数获取 guest_id
    $userKey = '';
    if (!empty($_POST['guest_id'])) {
        $userKey = preg_replace('/[^A-Za-z0-9_-]/', '', $_POST['guest_id']);
        if (strlen($userKey) < 8) $userKey = '';
    }
    if (empty($userKey)) {
        $userKey = get_guest_id();
    }

    if (!$userKey) {
        echo json_encode(['code' => 0, 'message' => '请先登录']);
        exit;
    }
    
    $body = file_get_contents('php://input');
    parse_str($body, $params);
    $hall_id = isset($params['hall_id']) ? intval($params['hall_id']) : 0;
    $libation_id = isset($params['libation_id']) ? intval($params['libation_id']) : 0;
    
    // 获取祭品价格
    $libationPrice = get_libation_price($libation_id);
    if ($libationPrice <= 0) {
        $libationPrice = 10; // 默认价格
    }
    
    // 获取当前余额
    $balance = get_balance($userKey);
    $currentGiftMoney = floatval($balance['gift_money']);
    
    if ($currentGiftMoney < $libationPrice) {
        echo json_encode([
            'code' => 0,
            'message' => '余额不足，福币不足无法购买祭品'
        ]);
        exit;
    }
    
    // 扣款
    $newBalance = save_balance($userKey, $balance['money'], $currentGiftMoney - $libationPrice);
    
    // 调用后端API完成祭品赠送
    $url = 'https://m.xinjidian.com/libation-post/offer-libation';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 45);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/x-www-form-urlencoded',
        'User-Agent: Mozilla/5.0 (compatible; sm.catdsn-proxy/1.0)',
    ));
    $out = curl_exec($ch);
    curl_close($ch);
    
    echo json_encode([
        'code' => 1,
        'message' => '赠送成功',
        'data' => [
            'money' => $newBalance['money'],
            'gift_money' => $newBalance['gift_money'],
        ]
    ]);
    exit;
}

if ($p === '' || !in_array($p, $allow, true)) {
    http_response_code(400);
    echo json_encode(array('code' => 0, 'message' => 'invalid proxy path'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('code' => 0, 'message' => 'method not allowed'));
    exit;
}

$url = 'https://m.xinjidian.com/' . $p;
$body = file_get_contents('php://input');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded',
    'User-Agent: Mozilla/5.0 (compatible; sm.catdsn-proxy/1.0)',
));

$out = curl_exec($ch);
$errno = curl_errno($ch);
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($errno !== 0 || $out === false) {
    http_response_code(502);
    echo json_encode(array('code' => 0, 'message' => 'upstream error'));
    exit;
}

http_response_code($code > 0 ? $code : 200);
echo $out;
