<?php
// 在文件开头添加
spl_autoload_register(function ($class) {
    error_log("尝试自动加载类: " . $class);
    
    // 定义可能的路径
    $paths = [
        __DIR__ . '/includes/exchanges/',
        __DIR__ . '/includes/',
        'includes/exchanges/',
        'includes/'
    ];
    
    foreach ($paths as $path) {
        $file = $path . $class . '.php';
        error_log("尝试加载文件: " . $file);
        
        if (file_exists($file)) {
            error_log("找到文件: " . $file);
            require_once $file;
            return;
        }
    }
    
    error_log("未找到类文件: " . $class);
});

require_once 'config/config.php';
require_once 'config/database.php';
require_once 'config/functions.php';
require_once 'config/encryption.php';
require_once 'config/session.php';
require_once 'config/logger.php';
require_once 'config/auth.php';

// 需要登录才能访问
requireLogin();

$page_title = 'API配置';
$db = Database::getInstance();
$conn = $db->getConnection();
$user_id = $_SESSION['user_id'];
$session = Session::getInstance();
$logger = Logger::getInstance();

// 获取支持的交易所列表
$exchanges = $config['exchanges'];

// 获取系统设置中的白名单IP
error_log("Fetching whitelist IP from database...");
$stmt = $db->prepare("SELECT value FROM system_settings WHERE key_name = 'trade_api_whitelist'");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
error_log("Database result: " . print_r($row, true));
$whitelist_ip = $row['value'] ?? '';
error_log("Whitelist IP: " . $whitelist_ip);

// 在获取用户的API配置之前添加
try {
    // 检查 exchange_apis 表中是否有 yesterday_pnl 和 today_pnl 字段
    $result = $conn->query("SHOW COLUMNS FROM exchange_apis LIKE 'yesterday_pnl'");
    if ($result === false) {
        throw new Exception("检查字段失败: " . $conn->error);
    }
    
    if ($result->num_rows === 0) {
        // 添加 yesterday_pnl 字段
        $result = $conn->query("
            ALTER TABLE exchange_apis 
            ADD COLUMN yesterday_pnl decimal(20,8) NOT NULL DEFAULT '0.00000000' AFTER status
        ");
        if ($result === false) {
            throw new Exception("添加 yesterday_pnl 字段失败: " . $conn->error);
        }
    }

    $result = $conn->query("SHOW COLUMNS FROM exchange_apis LIKE 'today_pnl'");
    if ($result === false) {
        throw new Exception("检查字段失败: " . $conn->error);
    }
    
    if ($result->num_rows === 0) {
        // 添加 today_pnl 字段
        $result = $conn->query("
            ALTER TABLE exchange_apis 
            ADD COLUMN today_pnl decimal(20,8) NOT NULL DEFAULT '0.00000000' AFTER yesterday_pnl
        ");
        if ($result === false) {
            throw new Exception("添加 today_pnl 字段失败: " . $conn->error);
        }
    }

    // 获取用户的API配置
    $stmt = $conn->prepare("
        SELECT *, 
            COALESCE(yesterday_pnl, 0) as yesterday_pnl,
            COALESCE(today_pnl, 0) as today_pnl
        FROM exchange_apis 
        WHERE user_id = ? 
        ORDER BY created_at DESC
    ");
    
    if ($stmt === false) {
        throw new Exception("准备查询语句失败: " . $conn->error);
    }

    if (!$stmt->execute([$user_id])) {
        throw new Exception("执行查询失败: " . $stmt->error);
    }

    $result = $stmt->get_result();
    if ($result === false) {
        throw new Exception("获取结果失败: " . $stmt->error);
    }

    $apis = $result->fetch_all(MYSQLI_ASSOC);

} catch (Exception $e) {
    error_log("检查或更新API表结构失败: " . $e->getMessage());
    // 如果出错，使用简单的查询
    $stmt = $conn->prepare("SELECT * FROM exchange_apis WHERE user_id = ? ORDER BY created_at DESC");
    if ($stmt === false) {
        error_log("准备备用查询失败: " . $conn->error);
        $apis = [];
    } else {
        $stmt->execute([$user_id]);
        $apis = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }
}

// 检查表是否存在
$result = $conn->query("SHOW TABLES LIKE 'exchange_balances'");
if ($result->num_rows === 0) {
    // 创建表
    $conn->query("
        CREATE TABLE IF NOT EXISTS `exchange_balances` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `api_id` int(11) NOT NULL,
            `total_equity` decimal(20,8) NOT NULL DEFAULT '0.00000000',
            `available_balance` decimal(20,8) NOT NULL DEFAULT '0.00000000',
            `frozen_balance` decimal(20,8) NOT NULL DEFAULT '0.00000000',
            `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `api_id` (`api_id`),
            CONSTRAINT `exchange_balances_ibfk_1` FOREIGN KEY (`api_id`) REFERENCES `exchange_apis` (`id`) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");
}

// 处理添加API请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        if ($_POST['action'] === 'add') {
            // 检查API数量限制
            if (count($apis) >= ($config['limits']['max_apis_per_user'] ?? 5)) {
                throw new Exception('已达到最大API配置数量限制（' . ($config['limits']['max_apis_per_user'] ?? 5) . '个）');
            }
            
            // 验证输入
            $exchange = trim($_POST['exchange']);
            $read_api_key = trim($_POST['read_api_key']);
            $read_api_secret = trim($_POST['read_api_secret']);
            $read_passphrase = trim($_POST['read_passphrase'] ?? '');
            $trade_api_key = trim($_POST['trade_api_key']);
            $trade_api_secret = trim($_POST['trade_api_secret']);
            $trade_passphrase = trim($_POST['trade_passphrase'] ?? '');
            $remark = trim($_POST['remark'] ?? '');
            
            if (!isset($exchanges[$exchange])) {
                throw new Exception('不支持的交易所');
            }
            
            if (empty($read_api_key) || empty($read_api_secret) || 
                empty($trade_api_key) || empty($trade_api_secret)) {
                throw new Exception('API密钥不能为空');
            }
            
            // 在文件开头添加调试信息
            error_log("当前目录: " . __DIR__);
            error_log("当前文件: " . __FILE__);
            error_log("包含路径: " . get_include_path());
            error_log("所有已加载的文件:");
            foreach (get_included_files() as $file) {
                error_log($file);
            }

            // 修改类加载部分
            try {
                $className = ucfirst($exchange) . 'Api';
                $classFile = __DIR__ . "/includes/exchanges/{$className}.php";
                
                error_log("尝试加载类文件: " . $classFile);
                if (!file_exists($classFile)) {
                    error_log("文件不存在，尝试其他路径...");
                    // 尝试其他可能的路径
                    $altPaths = [
                        __DIR__ . "/../includes/exchanges/{$className}.php",
                        dirname(__DIR__) . "/includes/exchanges/{$className}.php",
                        "includes/exchanges/{$className}.php"
                    ];
                    
                    foreach ($altPaths as $path) {
                        error_log("尝试路径: " . $path);
                        if (file_exists($path)) {
                            $classFile = $path;
                            error_log("找到文件: " . $classFile);
                            break;
                        }
                    }
                }
                
                if (!file_exists($classFile)) {
                    throw new Exception("API类文件不存在: " . $classFile);
                }
                
                error_log("加载文件内容预览:");
                error_log(substr(file_get_contents($classFile), 0, 500));
                
                require_once $classFile;
                
                error_log("已加载的类:");
                foreach (get_declared_classes() as $class) {
                    error_log($class);
                }
                
                if (!class_exists($className)) {
                    throw new Exception("类 {$className} 未定义");
                }
                
                // 测试API连接
                $readApi = new $className($read_api_key, $read_api_secret, $read_passphrase);
                try {
                    $result = $readApi->testConnection();
                    error_log("API测试响应: " . json_encode($result));
                    error_log("只读API连接测试成功");
                } catch (Exception $e) {
                    error_log("只读API连接测试失败: " . $e->getMessage());
                    error_log("错误堆栈: " . $e->getTraceAsString());
                    throw new Exception("只读API连接测试失败：" . $e->getMessage());
                }

                error_log("开始测试交易API连接...");
                error_log("API Key: " . substr($trade_api_key, 0, 8) . '...');
                
                // 测试交易API
                $tradeApi = new $className($trade_api_key, $trade_api_secret, $trade_passphrase);
                try {
                    $tradeApi->testConnection();
                    error_log("交易API连接测试成功");
                } catch (Exception $e) {
                    error_log("交易API连接测试失败: " . $e->getMessage());
                    throw new Exception("交易API连接测试失败：" . $e->getMessage());
                }

            } catch (Exception $e) {
                error_log("API连接测试失败: " . $e->getMessage());
                throw new Exception("API连接测试失败：" . $e->getMessage());
            }
            
            // 在保存API配置之前添加这段代码
            try {
                // 检查并添加缺失的字段
                $required_columns = [
                    'read_api_key' => 'VARCHAR(255) NOT NULL',
                    'read_api_secret' => 'VARCHAR(255) NOT NULL',
                    'trade_api_key' => 'VARCHAR(255) NOT NULL',
                    'trade_api_secret' => 'VARCHAR(255) NOT NULL',
                    'read_passphrase' => 'VARCHAR(255) DEFAULT NULL',
                    'trade_passphrase' => 'VARCHAR(255) DEFAULT NULL'
                ];
                
                error_log("开始检查并添加必需字段...");
                
                foreach ($required_columns as $column => $definition) {
                    // 检查字段是否存在
                    $check = $conn->query("SHOW COLUMNS FROM exchange_apis LIKE '$column'");
                    if ($check->num_rows === 0) {
                        error_log("添加字段: $column");
                        $alter_sql = "ALTER TABLE exchange_apis ADD COLUMN $column $definition";
                        if (!$conn->query($alter_sql)) {
                            error_log("添加字段失败: " . $conn->error);
                            throw new Exception("添加字段 $column 失败: " . $conn->error);
                        }
                    }
                }
                
                error_log("字段检查和添加完成");
                
                // 验证字段是否都已添加成功
                $missing_fields = [];
                foreach (array_keys($required_columns) as $column) {
                    $check = $conn->query("SHOW COLUMNS FROM exchange_apis LIKE '$column'");
                    if ($check->num_rows === 0) {
                        $missing_fields[] = $column;
                    }
                }
                
                if (!empty($missing_fields)) {
                    throw new Exception("无法添加必需字段: " . implode(", ", $missing_fields));
                }
                
            } catch (Exception $e) {
                error_log("检查和添加字段时出错: " . $e->getMessage());
                throw $e;
            }
            
            // 保存API配置
            error_log("开始保存API配置...");
            
            // 检查表结构
            $table_check = $conn->query("SHOW CREATE TABLE exchange_apis");
            if ($table_check) {
                $table_def = $table_check->fetch_row();
                error_log("当前表结构: " . print_r($table_def, true));
            }
            
            // 获取并显示所有字段
            $columns = $conn->query("SHOW COLUMNS FROM exchange_apis");
            error_log("表字段列表:");
            while ($col = $columns->fetch_assoc()) {
                error_log(sprintf(
                    "字段: %s, 类型: %s, 允许空: %s, 键: %s, 默认值: %s",
                    $col['Field'],
                    $col['Type'],
                    $col['Null'],
                    $col['Key'],
                    $col['Default']
                ));
            }
            
            // 检查是否缺少必需字段
            $required_fields = [
                'user_id', 'exchange', 
                'read_api_key', 'read_api_secret',
                'trade_api_key', 'trade_api_secret'
            ];
            
            $missing_fields = [];
            foreach ($required_fields as $field) {
                $check = $conn->query("SHOW COLUMNS FROM exchange_apis LIKE '$field'");
                if ($check->num_rows === 0) {
                    $missing_fields[] = $field;
                }
            }
            
            if (!empty($missing_fields)) {
                error_log("缺少的字段: " . implode(", ", $missing_fields));
                throw new Exception("数据库表缺少必需字段: " . implode(", ", $missing_fields));
            }
            
            // 修改插入SQL，包含所有必需字段
            $sql = "INSERT INTO exchange_apis (
                user_id, exchange,
                api_key, api_secret, passphrase,
                read_api_key, read_api_secret, read_passphrase,
                trade_api_key, trade_api_secret, trade_passphrase,
                remark, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')";
            
            error_log("准备执行SQL: " . $sql);
            error_log("参数值: " . json_encode([
                'user_id' => $user_id,
                'exchange' => $exchange,
                'read_api_key' => substr($read_api_key, 0, 8) . '...',
                'trade_api_key' => substr($trade_api_key, 0, 8) . '...',
                'has_passphrase' => !empty($read_passphrase) || !empty($trade_passphrase)
            ]));
            
            $stmt = $conn->prepare($sql);
            if ($stmt === false) {
                throw new Exception("准备插入语句失败: " . $conn->error);
            }
            
            // 修改参数绑定，包含所有字段
            if (!$stmt->execute([
                $user_id, $exchange,
                $read_api_key, $read_api_secret, $read_passphrase, // 用只读API填充旧字段
                $read_api_key, $read_api_secret, $read_passphrase,
                $trade_api_key, $trade_api_secret, $trade_passphrase,
                $remark
            ])) {
                throw new Exception("参数绑定失败: " . $stmt->error);
            }
            
            $stmt->close();
            
            // 记录操作日志
            $logger->info('add_api', [
                'user_id' => $user_id,
                'exchange' => $exchange
            ]);
            
            // 暂时注释掉积分功能
            // if (function_exists('addPoints')) {
            //     addPoints($user_id, $config['points']['api'], "添加{$exchange}交易所API");
            // }
            
            $_SESSION['flash'] = ['type' => 'success', 'message' => 'API配置添加成功'];
            header('Location: api_settings.php');
            exit;
            
        } elseif ($_POST['action'] === 'delete') {
            $api_id = intval($_POST['api_id']);
            
            // 验证API归属
            $stmt = $conn->prepare("SELECT exchange FROM exchange_apis WHERE id = ? AND user_id = ?");
            $stmt->execute([$api_id, $user_id]);
            $api = $stmt->get_result()->fetch_assoc();
            
            if (!$api) {
                throw new Exception('API配置不存在或无权操作');
            }
            
            // 删除API配置
            $stmt = $conn->prepare("DELETE FROM exchange_apis WHERE id = ?");
            $stmt->execute([$api_id]);
            
            // 记录操作日志
            $logger->info('delete_api', [
                'user_id' => $user_id,
                'api_id' => $api_id
            ]);
            
            $_SESSION['flash'] = ['type' => 'success', 'message' => 'API配置删除成功'];
            header('Location: api_settings.php');
            exit;
        }
        
    } catch (Exception $e) {
        error_log("添加API失败: " . $e->getMessage());
        $_SESSION['flash'] = ['type' => 'danger', 'message' => $e->getMessage()];
        header('Location: api_settings.php');
        exit;
    }
}

error_log(sprintf(
    "数据库配置: Host=%s, DB=%s, User=%s",
    DB_HOST,
    DB_NAME,
    DB_USER
));

include 'templates/header.php';
?>

<div class="container-fluid mt-4">
    <div class="row">
        <!-- 左侧导航 -->
        <div class="col-md-2">
            <?php 
            if ($session->getRole() === 'admin' && strpos($_SERVER['PHP_SELF'], '/admin/') !== false) {
                include 'templates/admin/sidebar.php';
            } else {
                include 'templates/sidebar.php';
            }
            ?>
        </div>
        
        <!-- 主内容区 -->
        <div class="col-md-10">
            <!-- API列表 -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">API配置</h5>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addApiModal">
                        添加API
                    </button>
                </div>
                <div class="card-body">
                    <?php if (empty($apis)): ?>
                    <div class="text-center py-4">
                        <p class="text-muted">暂无API配置</p>
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>交易所</th>
                                    <th>只读API Key</th>
                                    <th>只读API Secret</th>
                                    <th>交易API Key</th>
                                    <th>交易API Secret</th>
                                    <th>账户权益</th>
                                    <th>可用资金</th>
                                    <th>仓位占比</th>
                                    <th>昨日盈亏</th>
                                    <th>当日盈亏</th>
                                    <th>备注</th>
                                    <th>状态</th>
                                    <th>添加时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($apis as $api): 
                                    try {
                                        $className = ucfirst($api['exchange']) . 'Api';
                                        error_log("开始获取账户信息 - API ID: " . $api['id']);
                                        
                                        $apiInstance = new $className(
                                            $api['read_api_key'], 
                                            $api['read_api_secret'], 
                                            $api['read_passphrase'] ?? ''
                                        );
                                        
                                        // 获取账户信息
                                        error_log("调用getBalance方法...");
                                        $accountInfo = $apiInstance->getBalance();
                                        error_log("账户信息: " . json_encode($accountInfo));
                                        
                                        if (isset($accountInfo['totalEquity']) && isset($accountInfo['availableBalance'])) {
                                            // 更新数据库
                                            error_log("准备更新数据库...");
                                            error_log("总权益: " . $accountInfo['totalEquity']);
                                            error_log("可用余额: " . $accountInfo['availableBalance']);
                                            
                                            $updateStmt = $conn->prepare("
                                                UPDATE exchange_apis 
                                                SET total_equity = ?,
                                                    available_balance = ?,
                                                    last_update = NOW()
                                                WHERE id = ?
                                            ");
                                            
                                            if ($updateStmt === false) {
                                                error_log("SQL预处理失败: " . $conn->error);
                                                throw new Exception("数据库更新失败");
                                            }
                                            
                                            if (!$updateStmt->execute([
                                                $accountInfo['totalEquity'],
                                                $accountInfo['availableBalance'],
                                                $api['id']
                                            ])) {
                                                error_log("SQL执行失败: " . $updateStmt->error);
                                                throw new Exception("数据库执行失败");
                                            }
                                            
                                            $updateStmt->close();
                                            error_log("数据库更新成功");
                                            
                                            // 更新当前循环中的数据，这样显示时就能看到最新值
                                            $api['total_equity'] = $accountInfo['totalEquity'];
                                            $api['available_balance'] = $accountInfo['availableBalance'];
                                        } else {
                                            error_log("账户信息中缺少必要的字段");
                                            error_log("返回的数据结构: " . print_r($accountInfo, true));
                                        }
                                        
                                    } catch (Exception $e) {
                                        error_log("获取账户信息失败: " . $e->getMessage());
                                        error_log("错误堆栈: " . $e->getTraceAsString());
                                    }
                                ?>
                                <tr>
                                    <td>
                                        <?php if (!empty($exchanges[$api['exchange']]['logo'])): ?>
                                            <img src="<?php echo $exchanges[$api['exchange']]['logo']; ?>" 
                                                 alt="<?php echo $api['exchange']; ?>" 
                                                 height="20" class="me-2">
                                        <?php endif; ?>
                                        <?php echo $exchanges[$api['exchange']]['name'] ?? $api['exchange']; ?>
                                    </td>
                                    <td><?php echo substr($api['read_api_key'], 0, 8) . '...'; ?></td>
                                    <td><?php echo substr($api['read_api_secret'], 0, 8) . '...'; ?></td>
                                    <td><?php echo substr($api['trade_api_key'], 0, 8) . '...'; ?></td>
                                    <td><?php echo substr($api['trade_api_secret'], 0, 8) . '...'; ?></td>
                                    <td>
                                        <?php 
                                        // 获取账户余额信息（合约账户）
                                        $futures_balance = [
                                            'total_equity' => 0,
                                            'available_balance' => 0,
                                            'position_ratio' => 0
                                        ];
                                        
                                        // 获取账户余额信息（现货账户）
                                        $spot_balance = [
                                            'total_equity' => 0,
                                            'available_balance' => 0
                                        ];
                                        
                                        try {
                                            // 检查表是否存在
                                            $tableCheck = $conn->query("SHOW TABLES LIKE 'exchange_account_balances'");
                                            if ($tableCheck === false) {
                                                throw new Exception("检查表失败: " . $conn->error);
                                            }
                                            
                                            if ($tableCheck->num_rows === 0) {
                                                // 创建表
                                                $result = $conn->query("
                                                    CREATE TABLE IF NOT EXISTS `exchange_account_balances` (
                                                        `id` int(11) NOT NULL AUTO_INCREMENT,
                                                        `api_id` int(11) NOT NULL,
                                                        `account_type` enum('futures','spot') NOT NULL,
                                                        `total_equity` decimal(20,8) NOT NULL DEFAULT '0.00000000',
                                                        `available_balance` decimal(20,8) NOT NULL DEFAULT '0.00000000',
                                                        `position_ratio` decimal(10,2) NOT NULL DEFAULT '0.00',
                                                        `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                                                        PRIMARY KEY (`id`),
                                                        KEY `api_id` (`api_id`),
                                                        CONSTRAINT `exchange_account_balances_ibfk_1` FOREIGN KEY (`api_id`) REFERENCES `exchange_apis` (`id`) ON DELETE CASCADE
                                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
                                                ");
                                                
                                                if ($result === false) {
                                                    throw new Exception("创建表失败: " . $conn->error);
                                                }
                                            }

                                            // 获取合约账户余额
                                            $stmt = $conn->prepare("
                                                SELECT total_equity, available_balance, position_ratio 
                                                FROM exchange_account_balances 
                                                WHERE api_id = ? AND account_type = 'futures'
                                                ORDER BY updated_at DESC 
                                                LIMIT 1
                                            ");
                                            
                                            if ($stmt === false) {
                                                throw new Exception("准备合约账户查询语句失败: " . $conn->error);
                                            }
                                            
                                            $stmt->execute([$api['id']]);
                                            $result = $stmt->get_result();
                                            if ($result === false) {
                                                throw new Exception("获取合约账户结果失败: " . $stmt->error);
                                            }
                                            
                                            if ($row = $result->fetch_assoc()) {
                                                $futures_balance = array_merge($futures_balance, $row);
                                            }
                                            
                                            // 获取现货账户余额
                                            $stmt = $conn->prepare("
                                                SELECT total_equity, available_balance 
                                                FROM exchange_account_balances 
                                                WHERE api_id = ? AND account_type = 'spot'
                                                ORDER BY updated_at DESC 
                                                LIMIT 1
                                            ");
                                            
                                            if ($stmt === false) {
                                                throw new Exception("准备现货账户查询语句失败: " . $conn->error);
                                            }
                                            
                                            $stmt->execute([$api['id']]);
                                            $result = $stmt->get_result();
                                            if ($row = $result->fetch_assoc()) {
                                                $spot_balance = array_merge($spot_balance, $row);
                                            }
                                            
                                        } catch (Exception $e) {
                                            error_log("获取API账户余额失败: " . $e->getMessage());
                                            // 设置默认值
                                            $futures_balance = [
                                                'total_equity' => 0,
                                                'available_balance' => 0,
                                                'position_ratio' => 0
                                            ];
                                            $spot_balance = [
                                                'total_equity' => 0,
                                                'available_balance' => 0
                                            ];
                                        }
                                        ?>
                                        
                                        <!-- 显示合约账户信息 -->
                                        <div class="mb-2">
                                            <strong>合约账户：</strong>
                                            <div>总权益: <?php echo number_format($futures_balance['total_equity'], 2); ?> USDT</div>
                                            <div>可用资金: <?php echo number_format($futures_balance['available_balance'], 2); ?> USDT</div>
                                            <div>仓位占比: <?php echo number_format($futures_balance['position_ratio'], 2); ?>%</div>
                                        </div>
                                        
                                        <!-- 显示现货账户信息 -->
                                        <div>
                                            <strong>现货账户：</strong>
                                            <div>总权益: <?php echo number_format($spot_balance['total_equity'], 2); ?> USDT</div>
                                            <div>可用资金: <?php echo number_format($spot_balance['available_balance'], 2); ?> USDT</div>
                                        </div>
                                    </td>
                                    <td class="<?php echo ($api['yesterday_pnl'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                                        <?php 
                                        $yesterday_pnl = $api['yesterday_pnl'] ?? 0;
                                        echo $yesterday_pnl != 0 ? number_format($yesterday_pnl, 2) . ' USDT' : '-'; 
                                        ?>
                                    </td>
                                    <td class="<?php echo ($api['today_pnl'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                                        <?php 
                                        $today_pnl = $api['today_pnl'] ?? 0;
                                        echo $today_pnl != 0 ? number_format($today_pnl, 2) . ' USDT' : '-'; 
                                        ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($api['remark']); ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $api['status'] === 'active' ? 'success' : 'danger'; ?>">
                                            <?php echo $api['status'] === 'active' ? '正常' : '禁用'; ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('Y-m-d H:i:s', strtotime($api['created_at'])); ?></td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <a href="positions.php?api_id=<?php echo $api['id']; ?>" 
                                               class="btn btn-info">持仓明细</a>
                                            <button type="button" class="btn btn-danger" 
                                                    onclick="confirmDelete(<?php echo $api['id']; ?>)">删除</button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- 使用说明 -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">API配置说明</h5>
                </div>
                <div class="card-body">
                    <h6>权限要求</h6>
                    <ul>
                        <li>读取账户资产</li>
                        <li>读取交易记录</li>
                        <li>交易下单（如需自动交易）</li>
                    </ul>
                    
                    <h6>注意事项</h6>
                    <ul>
                        <li>请勿泄露API密钥，定期更换密钥</li>
                        <li>建议设置IP白名单</li>
                        <li>建议只开启必要的API权限</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加API模态框 -->
<div class="modal fade" id="addApiModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" action="api_settings.php">
                <input type="hidden" name="action" value="add">
                
                <div class="modal-header">
                    <h5 class="modal-title">添加API</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">选择交易所</label>
                        <select class="form-select" id="exchange" name="exchange" required>
                            <option value="">请选择交易所</option>
                            <option value="binance">Binance (币安)</option>
                            <option value="okx">OKX (欧易)</option>
                            <option value="bitget">BITGET (比特球)</option>
                            <option value="bybit">Bybit (比特比)</option>
                            <option value="gate">Gate.io</option>
                        </select>
                    </div>
                    
                    <h6 class="mb-3">只读API（用于查询账户资产和交易记录）</h6>
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i> 提示：IP地址不要限制
                    </div>
                    <div class="mb-3">
                        <label class="form-label">只读 API Key</label>
                        <input type="text" name="read_api_key" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">只读 API Secret</label>
                        <input type="password" name="read_api_secret" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">只读 Passphrase (如需要)</label>
                        <input type="password" name="read_passphrase" class="form-control">
                    </div>
                    
                    <h6 class="mb-3">交易API（用于自动交易）</h6>
                    <div class="alert alert-warning">
                        <i class="fa fa-exclamation-triangle"></i> 
                        今天的白名单IP地址为：<?php echo htmlspecialchars($whitelist_ip); ?>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">交易 API Key</label>
                        <input type="text" name="trade_api_key" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">交易 API Secret</label>
                        <input type="password" name="trade_api_secret" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">交易 Passphrase (如需要)</label>
                        <input type="password" name="trade_passphrase" class="form-control">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">备注</label>
                        <input type="text" name="remark" class="form-control">
                    </div>

                    <!-- 在API表单中添加策略选择 -->
                    <div class="mb-3">
                        <label class="form-label">选择策略</label>
                        <select name="strategy_id" class="form-select" required>
                            <option value="">请选择交易策略</option>
                            <?php
                            $strategies = $conn->query("SELECT * FROM strategies WHERE status = 'active' ORDER BY type, risk_level")->fetch_all(MYSQLI_ASSOC);
                            foreach ($strategies as $strategy):
                            ?>
                            <option value="<?php echo $strategy['id']; ?>" <?php echo isset($api) && $api['strategy_id'] == $strategy['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($strategy['name']); ?> 
                                (<?php echo $strategy['type'] === 'contract' ? '合约' : '现货'; ?> - 
                                <?php echo $strategy['risk_level'] === 'stable' ? '稳定型' : 
                                    ($strategy['risk_level'] === 'enhanced' ? '增强型' : '激进型'); ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">添加</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认表单 -->
<form id="deleteForm" method="post" action="api_settings.php" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="api_id" id="deleteApiId">
</form>

<script>
function confirmDelete(apiId) {
    if (confirm('确定要删除这个API配置吗？')) {
        document.getElementById('deleteApiId').value = apiId;
        document.getElementById('deleteForm').submit();
    }
}
</script>

<!-- 持仓详情模态框 -->
<div class="modal fade" id="positionsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">持仓详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table" id="positionsTable">
                        <thead>
                            <tr>
                                <th>交易对</th>
                                <th>方向</th>
                                <th>数量</th>
                                <th>开仓均价</th>
                                <th>当前价格</th>
                                <th>未实现盈亏</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 持仓数据将通过 AJAX 加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function viewPositions(apiId) {
    // 打开新窗口显示持仓明细
    window.open('positions.php?api_id=' + apiId, 'positions', 'width=1200,height=800,scrollbars=yes');
}

function confirmCloseAll(apiId, exchange) {
    if (confirm('确定要平掉所有持仓吗？此操作不可撤销！')) {
        fetch('api_close_all.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                api_id: apiId,
                exchange: exchange
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('所有持仓已平仓');
                location.reload();
            } else {
                alert('平仓失败: ' + data.message);
            }
        })
        .catch(error => {
            alert('平仓请求失败，请重试');
            console.error('平仓请求失败:', error);
        });
    }
}

function closePosition(symbol, apiId) {
    if (confirm(`确定要平掉 ${symbol} 的持仓吗？`)) {
        fetch('api_close_position.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                symbol: symbol,
                api_id: apiId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('持仓已平仓');
                viewPositions(apiId); // 刷新持仓列表
            } else {
                alert('平仓失败: ' + data.message);
            }
        })
        .catch(error => {
            alert('平仓请求失败，请重试');
            console.error('平仓请求失败:', error);
        });
    }
}
</script>

<?php include 'templates/footer.php'; ?> 