<?php
@set_time_limit(0);
@ini_set('memory_limit', '512M');
@header('Content-Type: application/json; charset=UTF-8');
include dirname(__DIR__) . '/includes/common.php';

if($islogin != 1) {
    exit(json_encode(['code' => -1, 'msg' => '未登录']));
}

$act = isset($_GET['act']) ? $_GET['act'] : '';

if ($act == 'submit') {
    $qq = isset($_POST['qq']) ? trim($_POST['qq']) : '';
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';
    $domain = isset($_POST['domain']) ? trim($_POST['domain']) : '';

    if (empty($qq)) {
        exit(json_encode(['code' => 0, 'msg' => '请输入QQ号']));
    }

    if (empty($content)) {
        exit(json_encode(['code' => 0, 'msg' => '请输入反馈内容']));
    }

    if (!preg_match('/^[1-9][0-9]{4,10}$/', $qq)) {
        exit(json_encode(['code' => 0, 'msg' => 'QQ号格式不正确']));
    }

    $fileUrls = [];
    if (!empty($_FILES['files'])) {
        $uploadDir = dirname(__DIR__) . '/assets/fankui/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        if (file_exists($uploadDir)) {
            @chmod($uploadDir, 0777);
        }

        $files = $_FILES['files'];
        $fileCount = count($files['name']);

        $allowedImages = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
        $allowedVideos = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm'];

        $scheme = 'http';
        if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
            $scheme = strtolower(trim(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])[0]));
        } elseif (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
            $scheme = 'https';
        }
        if ($scheme !== 'http' && $scheme !== 'https') $scheme = 'http';

        $host = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
            $host = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_HOST'])[0]);
        } elseif (!empty($_SERVER['HTTP_HOST'])) {
            $host = $_SERVER['HTTP_HOST'];
        }

        $baseUrl = '';
        $localurl = trim((string)($conf['localurl'] ?? ''));
        if ($localurl !== '' && preg_match('~^https?://~i', $localurl)) {
            $baseUrl = rtrim($localurl, '/');
        } elseif ($host !== '') {
            $scriptName = str_replace('\\', '/', (string)($_SERVER['SCRIPT_NAME'] ?? ''));
            $webRoot = rtrim(str_replace('\\', '/', dirname(dirname($scriptName))), '/');
            if ($webRoot === '/' || $webRoot === '.') $webRoot = '';
            $baseUrl = $scheme . '://' . $host . $webRoot;
        }

        for ($i = 0; $i < $fileCount; $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
                if (!in_array($ext, $allowedImages) && !in_array($ext, $allowedVideos)) {
                    continue;
                }

                $newName = uniqid() . '.' . $ext;
                $targetPath = $uploadDir . $newName;

                if (move_uploaded_file($files['tmp_name'][$i], $targetPath)) {
                    @chmod($targetPath, 0666);
                    if ($baseUrl !== '') {
                        $fileUrls[] = $baseUrl . '/assets/fankui/' . $newName;
                    }
                }
            }
        }
    }

    $bug_time = isset($_POST['bug_time']) ? trim($_POST['bug_time']) : '';

    $sendData = [
        'qq' => $qq,
        'content' => $content,
        'domain' => $domain,
        'files' => json_encode($fileUrls, JSON_UNESCAPED_UNICODE),
        'bug_time' => $bug_time
    ];

    $fankuiUrl = 'https://fankui.nmtxqq.cn/index.php';

    $postData = http_build_query($sendData);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $fankuiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
        'Content-Length: ' . strlen($postData)
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if (!$response || $httpCode !== 200) {
        exit(json_encode([
            'code' => 0,
            'msg' => '服务器请求失败: HTTP ' . $httpCode . ', Error: ' . $curlError
        ]));
    }

    $result = json_decode($response, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        exit(json_encode([
            'code' => 0,
            'msg' => '服务器返回数据解析失败: ' . json_last_error_msg()
        ]));
    }

    if (isset($result['code']) && $result['code'] == 1) {
        exit(json_encode([
            'code' => 1,
            'msg' => '反馈提交成功',
            'data' => [
                'files' => $fileUrls
            ]
        ]));
    } else {
        exit(json_encode([
            'code' => 0,
            'msg' => $result['msg'] ?? '提交到服务器失败'
        ]));
    }
}

exit(json_encode(['code' => 0, 'msg' => '未知操作']));
