<?php
// 详细调试版上传API
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

// 创建日志目录
$logDir = __DIR__ . '/../logs';
if (!is_dir($logDir)) {
    mkdir($logDir, 0755, true);
}

function logMessage($msg) {
    global $logDir;
    file_put_contents($logDir . '/upload_debug.log', '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n", FILE_APPEND);
}

logMessage('=== 新上传请求 ===');
logMessage('PHP版本: ' . phpversion());
logMessage('请求方法: ' . $_SERVER['REQUEST_METHOD']);
logMessage('客户端IP: ' . ($_SERVER['REMOTE_ADDR'] ?? '未知'));

try {
    // 检查是否有文件上传
    if (!isset($_FILES['video'])) {
        logMessage('错误: 没有文件上传');
        echo json_encode(['success' => false, 'message' => '请选择要上传的视频文件']);
        exit;
    }

    $file = $_FILES['video'];
    
    logMessage('文件名: ' . $file['name']);
    logMessage('文件类型: ' . $file['type']);
    logMessage('文件大小: ' . $file['size'] . ' bytes');
    logMessage('临时文件: ' . $file['tmp_name']);
    logMessage('错误码: ' . $file['error']);

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

    // 检查临时文件
    if (!file_exists($file['tmp_name'])) {
        $errorMsg = '临时文件不存在: ' . $file['tmp_name'];
        logMessage('错误: ' . $errorMsg);
        echo json_encode(['success' => false, 'message' => $errorMsg]);
        exit;
    }
    logMessage('临时文件存在');

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

    logMessage('视频类型: ' . $videoType);
    logMessage('视频名称: ' . $videoName);

    // 确定存储目录
    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)) {
        logMessage('创建目录: ' . $uploadDir);
        mkdir($uploadDir, 0755, true);
    }

    // 检查目录权限
    if (!is_writable($uploadDir)) {
        $errorMsg = '目录不可写: ' . $uploadDir;
        logMessage('错误: ' . $errorMsg);
        echo json_encode(['success' => false, 'message' => $errorMsg]);
        exit;
    }
    logMessage('目标目录可写: ' . $uploadDir);

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

    logMessage('目标文件: ' . $destination);

    // 移动文件
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        logMessage('文件移动成功');
        
        // 写入数据库
        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)
        ]);

        logMessage('数据库写入成功: ' . $videoId);
        echo json_encode([
            'success' => true,
            'message' => '上传成功',
            'video_id' => $videoId,
            'file_name' => $newFileName
        ]);
    } else {
        $errorMsg = '文件保存失败';
        logMessage('错误: ' . $errorMsg);
        echo json_encode(['success' => false, 'message' => $errorMsg]);
    }

} catch (Exception $e) {
    $errorMsg = '服务器错误: ' . $e->getMessage() . ' | ' . $e->getFile() . ':' . $e->getLine();
    logMessage('异常: ' . $errorMsg);
    echo json_encode(['success' => false, 'message' => $errorMsg]);
}
?>