<?php
// PHP 7.3兼容版上传API
// 最早期调试：立即记录请求到达
file_put_contents(dirname(__DIR__) . '/logs/upload_debug.log', '[' . date('Y-m-d H:i:s') . '] SCRIPT_REACHED: ' . $_SERVER['REQUEST_METHOD'] . ' size=' . ($_SERVER['CONTENT_LENGTH'] ?? 'unknown') . "\n", FILE_APPEND);

error_reporting(E_ALL);
ini_set('display_errors', 0);

// 自定义错误处理器
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    $msg = "[$errno] $errstr in $errfile:$errline";
    file_put_contents(dirname(__DIR__) . '/logs/upload_debug.log', '[' . date('Y-m-d H:i:s') . '] ERROR: ' . $msg . "\n", FILE_APPEND);
    return true;
});

set_exception_handler(function($e) {
    $msg = 'Exception: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();
    file_put_contents(dirname(__DIR__) . '/logs/upload_debug.log', '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n", FILE_APPEND);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'message' => $msg]);
    exit;
});

register_shutdown_function(function() {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        $msg = 'FATAL: ' . $error['message'] . ' in ' . $error['file'] . ':' . $error['line'];
        file_put_contents(dirname(__DIR__) . '/logs/upload_debug.log', '[' . date('Y-m-d H:i:s') . '] ' . $msg . "\n", FILE_APPEND);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success' => false, 'message' => $msg]);
    }
});

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
$allowedExtensions = array('mp4', 'mov', 'webm', 'ogg');

// 创建日志目录
$logDir = dirname(__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 = array(
        'success' => $success,
        'message' => $message
    );
    if ($data !== null) {
        $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 = array(
            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);
    }

    // 验证MP4文件头
    if ($ext === 'mp4') {
        $handle = fopen($file['tmp_name'], 'rb');
        if ($handle) {
            $header = bin2hex(fread($handle, 16));
            fclose($handle);
            $isValidMp4 = strpos($header, '0000001866747970') === 0 || 
                         strpos($header, '0000002066747970') === 0;
            if (!$isValidMp4) {
                $errorMsg = '文件不是有效的MP4格式，请确保文件是标准的H.264+AAC编码';
                logMessage('错误: ' . $errorMsg . ' | 文件头: ' . $header);
                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 = dirname(__DIR__) . '/videos/opening/';
        $storagePath = 'videos/opening/';
    } elseif ($videoType === 'host') {
        $uploadDir = dirname(__DIR__) . '/videos/host/';
        $storagePath = 'videos/host/';
    } elseif ($videoType === 'ending') {
        $uploadDir = dirname(__DIR__) . '/videos/ending/';
        $storagePath = 'videos/ending/';
    } else {
        $uploadDir = dirname(__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 dirname(__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(array(
            $videoId,
            $videoName,
            $videoType,
            $storagePath,
            $newFileName,
            $file['size'],
            $duration,
            strtoupper($ext)
        ));

        logMessage('数据库写入成功: ' . $videoId);
        sendResponse(true, '上传成功', array(
            '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);
}
?>