<?php

require_once __DIR__ . '/common.php';

require_once __DIR__ . '/common.php';
header('Content-Type: application/json; charset=utf-8');

function upload_fail(string $message, int $errno = 1): void
{
    echo json_encode([
        'errno' => $errno,
        'message' => $message,
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    upload_fail('Method not allowed');
}

$token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ($_POST['csrf_token'] ?? '');
if (!csrf_check($token)) {
    upload_fail('CSRF 校验失败');
}

if (!current_user_id()) {
    upload_fail('请先登录');
}

if (is_ip_blacklisted()) {
    upload_fail('当前 IP 已被限制上传');
}

if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
    upload_fail('未收到文件');
}

$file = $_FILES['file'];
if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
    upload_fail('上传失败（错误码：' . (int)($file['error'] ?? -1) . '）');
}

$maxSize = 10 * 1024 * 1024;
if (($file['size'] ?? 0) > $maxSize) {
    upload_fail('附件大小不能超过 10MB');
}

$ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
$allowedExt = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'md', 'zip', 'rar', '7z'];
if (!in_array($ext, $allowedExt, true)) {
    upload_fail('附件类型不支持');
}

$tmpPath = $file['tmp_name'] ?? '';
if ($tmpPath === '' || !is_uploaded_file($tmpPath)) {
    upload_fail('临时文件不可用');
}

$mimeOk = true;
$mime = '';
if (function_exists('finfo_open')) {
    $mimeOk = false;
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    if ($finfo) {
        $mime = finfo_file($finfo, $tmpPath);
        finfo_close($finfo);
        $allowedMime = [
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-powerpoint',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'text/plain',
            'text/markdown',
            'application/zip',
            'application/x-zip-compressed',
            'application/x-rar-compressed',
            'application/vnd.rar',
            'application/x-7z-compressed',
            'application/octet-stream',
        ];
        if (in_array($mime, $allowedMime, true)) {
            $mimeOk = true;
        }
    }
}

if (!$mimeOk) {
    upload_fail('附件类型校验失败');
}

$dir = BASE_PATH . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'attachments';
if (!is_dir($dir)) {
    @mkdir($dir, 0777, true);
}

$uid = (int)current_user_id();
$filename = 'file' . $uid . '_' . date('YmdHis') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
$target = $dir . DIRECTORY_SEPARATOR . $filename;

if (!@move_uploaded_file($tmpPath, $target)) {
    upload_fail('保存附件失败');
}

$displayName = basename((string)($file['name'] ?? '附件'));
if ($displayName === '') {
    $displayName = '附件';
}

$url = '/uploads/attachments/' . $filename;

record_media_file(
    'attachment',
    $url,
    (string)($file['name'] ?? $displayName),
    (int)($file['size'] ?? 0),
    (string)$mime,
    $uid
);

echo json_encode([
    'errno' => 0,
    'data' => [
        'url' => $url,
        'name' => $displayName,
    ],
], JSON_UNESCAPED_UNICODE);
