<?php
// 启用详细错误报告
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 记录错误日志
$logFile = __DIR__ . '/../logs/upload_errors.log';
if (!is_dir(__DIR__ . '/../logs')) {
    mkdir(__DIR__ . '/../logs', 0755, true);
}

function logError($message) {
    global $logFile;
    $logEntry = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
    file_put_contents($logFile, $logEntry, FILE_APPEND);
}

// 记录请求信息
logError('=== 新请求 ===');
logError('请求方法: ' . $_SERVER['REQUEST_METHOD']);
logError('请求路径: ' . $_SERVER['REQUEST_URI']);
logError('PHP版本: ' . phpversion());

try {
    // 设置响应头
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');

    // 处理OPTIONS请求
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        exit(json_encode(['success' => true, 'message' => 'Preflight OK']));
    }

    // 加载数据库配置
    require_once __DIR__ . '/../config.php';

    // 检查文件上传
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['video'])) {
        logError('收到文件上传请求');
        logError('文件名: ' . $_FILES['video']['name']);
        logError('文件大小: ' . $_FILES['video']['size']);
        logError('错误码: ' . $_FILES['video']['error']);
        
        if ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
            $errorMsg = '上传失败，错误码: ' . $_FILES['video']['error'];
            logError($errorMsg);
            echo json_encode(['success' => false, 'message' => $errorMsg]);
            exit;
        }
        
        // 尝试移动文件
        $uploadDir = __DIR__ . '/../videos/host/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $newFileName = uniqid() . '.' . pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
        $destination = $uploadDir . $newFileName;
        
        logError('目标路径: ' . $destination);
        
        if (move_uploaded_file($_FILES['video']['tmp_name'], $destination)) {
            logError('文件移动成功');
            echo json_encode([
                'success' => true,
                'message' => '上传成功',
                'filename' => $newFileName
            ]);
        } else {
            $errorMsg = '文件移动失败';
            logError($errorMsg);
            echo json_encode(['success' => false, 'message' => $errorMsg]);
        }
        exit;
    }
    
    echo json_encode(['success' => false, 'message' => '无效请求']);
    
} catch (Exception $e) {
    $errorMsg = '异常: ' . $e->getMessage() . ' | ' . $e->getFile() . ':' . $e->getLine();
    logError($errorMsg);
    echo json_encode(['success' => false, 'message' => '服务器错误: ' . $e->getMessage()]);
}
?>