<?php
/**
 * 官网聊天室 API 代理
 * 用于解决跨域问题
 */

header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

// 不需要登录检查，因为官网聊天室是公开的

// 官网 API 地址 (dre 目录是域名绑定的根目录)
$API_BASE = 'https://ww.a116.vip/api/chat.php';

// 获取请求参数
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

// 构建目标 URL - 需要传递 action 参数
$queryParams = $_GET;
$url = $API_BASE;
if (!empty($queryParams)) {
    $url .= '?' . http_build_query($queryParams);
}

// 初始化 cURL
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

// 设置请求方法
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    curl_setopt($ch, CURLOPT_POST, true);
    
    // 获取 POST 数据
    $postData = file_get_contents('php://input');
    
    // 如果是图片上传（FormData），需要转发文件
    if (empty($postData) && !empty($_FILES)) {
        // 图片上传，使用 multipart/form-data
        $curlPostData = $_POST;
        
        // 处理文件上传
        foreach ($_FILES as $key => $file) {
            if ($file['error'] === UPLOAD_ERR_OK) {
                $curlPostData[$key] = new CURLFile($file['tmp_name'], $file['type'], $file['name']);
            }
        }
        
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPostData);
    } elseif (empty($postData)) {
        // 普通表单提交
        $postData = http_build_query($_POST);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    } else {
        // JSON 数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        // 设置请求头
        $headers = array('Content-Type: application/json');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
}

// 执行请求
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$errorNo = curl_errno($ch);

curl_close($ch);

if ($error) {
    echo json_encode(array('success' => false, 'msg' => '请求失败：' . $error));
    exit;
}

if ($httpCode !== 200) {
    echo json_encode(array('success' => false, 'msg' => 'HTTP 错误：' . $httpCode));
    exit;
}

if ($response === false) {
    echo json_encode(array('success' => false, 'msg' => '响应为空'));
    exit;
}

// 返回官网 API 的响应
echo $response;
