<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');

require_once 'config.php';

// 解析URL参数
$action = isset($_GET['action']) ? $_GET['action'] : null;
$serverUUID = isset($_GET['serverUUID']) ? $_GET['serverUUID'] : null;
$nodeUUID = isset($_GET['nodeUUID']) ? $_GET['nodeUUID'] : null;

// 校验参数
if (!$serverUUID || !$nodeUUID) {
    echo json_encode([
        'status' => CONFIG_API_BAD_REQUEST,
        'message' => '缺少必要的参数: serverUUID 或 nodeUUID'
    ]);
    exit;
}

// 根据不同的操作执行不同的API请求
switch ($action) {
    case 'getInstanceInfo':
        $response = getInstanceInfo($serverUUID, $nodeUUID);
        break;
    case 'startInstance':
        $response = startInstance($serverUUID, $nodeUUID);
        break;
    case 'stopInstance':
        $response = stopInstance($serverUUID, $nodeUUID);
        break;
    case 'getConsole':
        $response = getConsole($serverUUID, $nodeUUID);
        break;
    case 'sendConsoleCommand':
        $command = isset($_GET['command']) ? $_GET['command'] : null;
        $response = sendConsoleCommand($serverUUID, $nodeUUID, $command);
        break;
    case 'getConsoleOutput':
        $response = getConsoleOutput($serverUUID, $nodeUUID);
        break;
    case 'getFiles':
        $response = getFiles($serverUUID, $nodeUUID);
        break;
    case 'viewFile':
        $path = isset($_GET['path']) ? $_GET['path'] : null;
        $response = viewFile($serverUUID, $nodeUUID, $path);
        break;
    case 'downloadFile':
        $path = isset($_GET['path']) ? $_GET['path'] : null;
        downloadFile($serverUUID, $nodeUUID, $path);
        exit;
    case 'uploadFile':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode([
                'status' => CONFIG_API_BAD_REQUEST,
                'message' => '无效的请求方法'
            ]);
            exit;
        }
        $file = $_FILES['file'] ?? null;
        $path = isset($_POST['path']) ? $_POST['path'] : '/';
        $response = uploadFile($serverUUID, $nodeUUID, $file, $path);
        break;
    case 'saveEditFile':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode([
                'status' => CONFIG_API_BAD_REQUEST,
                'message' => '无效的请求方法'
            ]);
            exit;
        }
        $content = isset($_POST['content']) ? $_POST['content'] : null;
        $path = isset($_POST['path']) ? $_POST['path'] : null;
        $response = saveEditFile($serverUUID, $nodeUUID, $content, $path);
        break;
    case 'deleteFile':
        $path = isset($_GET['path']) ? $_GET['path'] : null;
        $response = deleteFile($serverUUID, $nodeUUID, $path);
        break;
    default:
        echo json_encode([
            'status' => CONFIG_API_BAD_REQUEST,
            'message' => '无效的操作'
        ]);
        exit;
}

// 输出响应
echo json_encode($response);

// 获取实例信息
function getInstanceInfo($serverUUID, $nodeUUID) {
    $url = CONFIG_MCSM_API_URL . "/api/service/remote_services_system?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'GET');
}

// 启动实例
function startInstance($serverUUID, $nodeUUID) {
    $url = CONFIG_MCSM_API_URL . "/api/service/start_server?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'GET');
}

// 停止实例
function stopInstance($serverUUID, $nodeUUID) {
    $url = CONFIG_MCSM_API_URL . "/api/service/stop_server?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'GET');
}

// 获取控制台
function getConsole($serverUUID, $nodeUUID) {
    $url = CONFIG_MCSM_API_URL . "/api/service/console?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'GET');
}

// 发送控制台命令
function sendConsoleCommand($serverUUID, $nodeUUID, $command) {
    if (!$command) {
        return [
            'status' => CONFIG_API_BAD_REQUEST,
            'message' => '命令不能为空'
        ];
    }
    
    $url = CONFIG_MCSM_API_URL . "/api/service/console?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'POST', json_encode(['command' => $command]));
}

// 获取控制台输出
function getConsoleOutput($serverUUID, $nodeUUID) {
    $url = CONFIG_MCSM_API_URL . "/api/service/console?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'GET');
}

// 获取文件列表
function getFiles($serverUUID, $nodeUUID) {
    $url = CONFIG_MCSM_API_URL . "/api/service/files?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'GET');
}

// 查看文件内容
function viewFile($serverUUID, $nodeUUID, $path) {
    if (!$path) {
        return [
            'status' => CONFIG_API_BAD_REQUEST,
            'message' => '文件路径不能为空'
        ];
    }
    
    $url = CONFIG_MCSM_API_URL . "/api/service/file_content?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'POST', json_encode(['path' => $path]));
}

// 下载文件
function downloadFile($serverUUID, $nodeUUID, $path) {
    if (!$path) {
        echo json_encode([
            'status' => CONFIG_API_BAD_REQUEST,
            'message' => '文件路径不能为空'
        ]);
        exit;
    }
    
    $url = CONFIG_MCSM_API_URL . "/api/service/file_download?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    try {
        // 发送请求到MCSManager API
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['path' => $path]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',
            'X-Requested-With: XMLHttpRequest'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, CONFIG_API_TIMEOUT);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // 检查API响应状态码
        if ($httpCode !== CONFIG_API_SUCCESS) {
            echo json_encode([
                'status' => $httpCode,
                'message' => 'API请求失败'
            ]);
            exit;
        }
        
        // 解析响应
        $data = json_decode($response, true);
        
        if ($data['status'] !== CONFIG_API_SUCCESS) {
            echo json_encode([
                'status' => $data['status'],
                'message' => $data['message'] ?? '未知错误'
            ]);
            exit;
        }
        
        // 设置下载响应头
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Content-Length: ' . strlen($data['data']));
        
        // 输出文件内容
        echo $data['data'];
    } catch (Exception $e) {
        echo json_encode([
            'status' => CONFIG_API_INTERNAL_ERROR,
            'message' => '下载文件失败: ' . $e->getMessage()
        ]);
    }
}

// 上传文件
function uploadFile($serverUUID, $nodeUUID, $file, $path) {
    if (!$file || !is_uploaded_file($file['tmp_name'])) {
        return [
            'status' => CONFIG_API_BAD_REQUEST,
            'message' => '未上传有效的文件'
        ];
    }
    
    $url = CONFIG_MCSM_API_URL . "/api/service/file_upload?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    try {
        // 打开文件
        $fileData = file_get_contents($file['tmp_name']);
        
        // 发送请求到MCSManager API
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'path' => $path,
            'file' => base64_encode($fileData)
        ]);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
            'X-Requested-With: XMLHttpRequest'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, CONFIG_API_TIMEOUT);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // 检查API响应状态码
        if ($httpCode !== CONFIG_API_SUCCESS) {
            return [
                'status' => $httpCode,
                'message' => 'API请求失败'
            ];
        }
        
        // 解析响应
        $data = json_decode($response, true);
        
        if ($data['status'] !== CONFIG_API_SUCCESS) {
            return [
                'status' => $data['status'],
                'message' => $data['message'] ?? '未知错误'
            ];
        }
        
        return [
            'status' => CONFIG_API_SUCCESS,
            'message' => '文件上传成功'
        ];
    } catch (Exception $e) {
        return [
            'status' => CONFIG_API_INTERNAL_ERROR,
            'message' => '上传文件失败: ' . $e->getMessage()
        ];
    }
}

// 保存编辑的文件
function saveEditFile($serverUUID, $nodeUUID, $content, $path) {
    if (!$content || !$path) {
        return [
            'status' => CONFIG_API_BAD_REQUEST,
            'message' => '内容或路径不能为空'
        ];
    }
    
    $url = CONFIG_MCSM_API_URL . "/api/service/file_content?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'PUT', json_encode(['path' => $path, 'content' => $content]));
}

// 删除文件
function deleteFile($serverUUID, $nodeUUID, $path) {
    if (!$path) {
        return [
            'status' => CONFIG_API_BAD_REQUEST,
            'message' => '文件路径不能为空'
        ];
    }
    
    $url = CONFIG_MCSM_API_URL . "/api/service/file_delete?nodeUUID=" . urlencode($nodeUUID) . "&serverUUID=" . urlencode($serverUUID);
    
    return sendRequest($url, 'DELETE', json_encode(['path' => $path]));
}

// 发送API请求
function sendRequest($url, $method = 'GET', $data = null) {
    try {
        // 发送请求到MCSManager API
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        // 设置请求方法
        switch ($method) {
            case 'POST':
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case 'PUT':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
            case 'DELETE':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                break;
        }
        
        // 设置请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8',
            'X-Requested-With: XMLHttpRequest'
        ]);
        
        // 设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, CONFIG_API_TIMEOUT);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // 检查API响应状态码
        if ($httpCode !== CONFIG_API_SUCCESS) {
            return [
                'status' => $httpCode,
                'message' => 'API请求失败'
            ];
        }
        
        // 解析响应
        $data = json_decode($response, true);
        
        if ($data['status'] !== CONFIG_API_SUCCESS) {
            return [
                'status' => $data['status'],
                'message' => $data['message'] ?? '未知错误'
            ];
        }
        
        return [
            'status' => CONFIG_API_SUCCESS,
            'data' => $data['data'] ?? []
        ];
    } catch (Exception $e) {
        return [
            'status' => CONFIG_API_INTERNAL_ERROR,
            'message' => '请求失败: ' . $e->getMessage()
        ];
    }
}