<?php
// 简化版视频上传API
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$response = [
    'success' => false,
    'message' => '未知错误'
];

try {
    // 检查是否有文件上传
    if (!isset($_FILES['video'])) {
        $response['message'] = '请选择要上传的视频文件';
        echo json_encode($response);
        exit;
    }

    $file = $_FILES['video'];
    
    // 检查上传错误
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errors = [
            UPLOAD_ERR_INI_SIZE => '文件超过php.ini限制',
            UPLOAD_ERR_FORM_SIZE => '文件超过表单限制',
            UPLOAD_ERR_PARTIAL => '文件部分上传',
            UPLOAD_ERR_NO_FILE => '无文件上传',
            UPLOAD_ERR_NO_TMP_DIR => '缺少临时目录',
            UPLOAD_ERR_CANT_WRITE => '写入失败',
            UPLOAD_ERR_EXTENSION => '扩展阻止'
        ];
        $response['message'] = '上传失败: ' . (isset($errors[$file['error']]) ? $errors[$file['error']] : '未知错误');
        echo json_encode($response);
        exit;
    }

    // 获取视频类型
    $videoType = isset($_POST['video_type']) ? $_POST['video_type'] : 'other';
    $videoName = isset($_POST['video_name']) ? $_POST['video_name'] : pathinfo($file['name'], PATHINFO_FILENAME);

    // 确定存储目录
    if ($videoType === 'opening') {
        $uploadDir = __DIR__ . '/../videos/opening/';
        $storagePath = 'videos/opening/';
    } elseif ($videoType === 'host') {
        $uploadDir = __DIR__ . '/../videos/host/';
        $storagePath = 'videos/host/';
    } else {
        $uploadDir = __DIR__ . '/../videos/';
        $storagePath = 'videos/';
    }

    // 确保目录存在
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    // 生成文件名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $newFileName = uniqid() . '.' . $ext;
    $destination = $uploadDir . $newFileName;

    // 移动文件
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        // 写入数据库
        require_once __DIR__ . '/../config.php';
        global $pdo;

        $videoId = 'vid_' . uniqid();
        $stmt = $pdo->prepare("INSERT INTO video_assets (video_id, video_name, video_type, storage_path, file_name, file_size, format, is_active) VALUES (?, ?, ?, ?, ?, ?, ?, 1)");
        $stmt->execute([
            $videoId,
            $videoName,
            $videoType,
            $storagePath,
            $newFileName,
            $file['size'],
            strtoupper($ext)
        ]);

        $response['success'] = true;
        $response['message'] = '上传成功';
        $response['video_id'] = $videoId;
        $response['file_name'] = $newFileName;
    } else {
        $response['message'] = '文件保存失败';
    }

} catch (Exception $e) {
    $response['message'] = '服务器错误: ' . $e->getMessage();
}

echo json_encode($response);
?>