<?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 = 50 * 1024 * 1024;
if (($file['size'] ?? 0) > $maxSize) {
    upload_fail('视频大小不能超过 50MB');
}

$ext = strtolower(pathinfo($file['name'] ?? '', PATHINFO_EXTENSION));
$allowedExt = ['mp4', 'webm', 'ogg'];
if (!in_array($ext, $allowedExt, true)) {
    upload_fail('仅支持 MP4 / WEBM / OGG');
}

$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 = [
            'video/mp4',
            'video/webm',
            'video/ogg',
            'application/octet-stream',
        ];
        if (in_array($mime, $allowedMime, true)) {
            $mimeOk = true;
        }
    }
}

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

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

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

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

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

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

echo json_encode([
    'errno' => 0,
    'data' => [
        'url' => $url,
        'name' => (string)($file['name'] ?? '视频'),
    ],
], JSON_UNESCAPED_UNICODE);
