<?php
// 简单文件上传服务 - 安全版本
$uploadDir = './';
$allowedTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'image/webp', 'video/mp4'];
$maxSize = 50 * 1024 * 1024; // 50MB

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');

// 网页上传表单
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>文件上传 - 公网中转服务</title>
    <style>
        body { max-width: 600px; margin: 50px auto; font-family: Arial; }
        .box { padding: 30px; border: 2px dashed #4a90e2; border-radius: 10px; text-align: center; }
        button { background: #4a90e2; color: white; padding: 12px 24px; border: none; border-radius: 6px; cursor: pointer; margin-top:15px; }
        input { margin: 10px 0; }
        .link { margin-top:20px; padding:10px; background:#f5f5f5; border-radius:6px; word-break:break-all; display:none; }
    </style>
</head>
<body>
    <div class="box">
        <h2>📤 本地文件上传</h2>
        <p>支持图片/视频，生成公网链接</p>
        <form id="uploadForm" enctype="multipart/form-data">
            <input type="file" name="file" required>
            <br>
            <button type="submit">上传文件</button>
        </form>
        <div class="link" id="linkBox"></div>
    </div>

    <script>
        const form = document.getElementById('uploadForm');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(form);
            const res = await fetch('/upload.php', {
                method: 'POST',
                body: formData
            });
            const data = await res.json();
            const linkBox = document.getElementById('linkBox');
            if (data.url) {
                linkBox.innerText = data.url;
                linkBox.style.display = 'block';
                navigator.clipboard.writeText(data.url);
                alert('链接已复制！');
            } else {
                linkBox.innerText = '上传失败：' + data.error;
                linkBox.style.display = 'block';
            }
        });
    </script>
</body>
</html>
<?php
exit;
}

// API 上传处理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['file'])) {
        echo json_encode(['error' => '请选择文件']);
        exit;
    }

    $file = $_FILES['file'];
    $fileName = basename($file['name']);
    $fileType = $file['type'];
    $fileSize = $file['size'];
    $fileTmp = $file['tmp_name'];

    if (!in_array($fileType, $allowedTypes)) {
        echo json_encode(['error' => '不支持的文件类型']);
        exit;
    }

    if ($fileSize > $maxSize) {
        echo json_encode(['error' => '文件不能超过50MB']);
        exit;
    }

    $destPath = $uploadDir . $fileName;
    if (move_uploaded_file($fileTmp, $destPath)) {
        $url = 'https://' . $_SERVER['HTTP_HOST'] . '/' . rawurlencode($fileName);
        echo json_encode(['url' => $url]);
    } else {
        echo json_encode(['error' => '上传失败']);
    }
    exit;
}
?>