<?php
// 最终版本上传API
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// 配置
$maxFileSize = 1024 * 1024 * 1024; // 1GB
$allowedTypes = ['video/mp4', 'video/quicktime', 'video/webm', 'video/ogg'];
$allowedExtensions = ['mp4', 'mov', 'webm', 'ogg'];

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

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

function getVideoDuration($filePath) {
    try {
        $ffmpegPath = 'ffmpeg';
        $command = escapeshellcmd($ffmpegPath . ' -i "' . $filePath . '" 2>&1');
        $output = shell_exec($command);
        
        if (preg_match('/Duration: (\d{2}):(\d{2}):(\d{2})\.\d+/', $output, $matches)) {
            return ($matches[1] * 3600) + ($matches[2] * 60) + $matches[3];
        }
    } catch (Exception $e) {
        logMessage('计算视频时长失败: ' . $e->getMessage());
    }
    
    return 0.00;
}

function sendResponse($success, $message, $data = null) {
    $response = [
        'success' => $success,
        'message' => $message
    ];
    if ($data) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

logMessage('=== 新上传请求 ===');
logMessage('PHP版本: ' . phpversion());
logMessage('请求方法: ' . $_SERVER['REQUEST_METHOD']);

try {
    // 处理OPTIONS请求
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        sendResponse(true, 'Preflight OK');
    }

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

    $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);
        sendResponse(false, $errorMsg);
    }

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

    // 检查文件大小
    if ($file['size'] > $maxFileSize) {
        $errorMsg = '文件大小超过限制（最大500MB）';
        logMessage('错误: ' . $errorMsg);
        sendResponse(false, $errorMsg);
    }

    // 检查文件扩展名
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExtensions)) {
        $errorMsg = '不支持的文件格式，仅支持: ' . implode(', ', $allowedExtensions);
        logMessage('错误: ' . $errorMsg);
        sendResponse(false, $errorMsg);
    }

    // 获取视频类型
    $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);
        sendResponse(false, $errorMsg);
    }

    // 生成文件名
    $newFileName = uniqid() . '.' . $ext;
    $destination = $uploadDir . $newFileName;

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

    // 移动文件
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        logMessage('文件移动成功');
        
        // 更新文件权限
        chmod($destination, 0644);
        
        // 写入数据库
        require_once __DIR__ . '/../config.php';
        global $pdo;

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

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

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