<?php
require_once '../includes/init.php';
require_once '../includes/auth.php';
checkUserAuth();
require_once '../includes/mail_helper.php';
require_once '../includes/db_helper.php';
require_once '../includes/database_reconnect_helper.php';
require_once '../includes/trade_ai_marker_helper.php';
require_once '../includes/domestic_futures_helper.php';
if (!function_exists('ggai_format_audit_remark_html') || !function_exists('ggai_resolve_strategy_display_name')) {
    require_once __DIR__ . '/../includes/promotion_apis_helper.php';
}

// 页面标题（用于布局模板）
$pageTitle = __t('api_manage_page_title', '我的API管理');

// 检查用户API删除权限
$user_api_delete_enabled = get_system_setting('user_api_delete_enabled') ?: 0;

function mask_api_key($key) {
    $len = strlen($key);
    if ($len <= 8) return str_repeat('*', $len);
    return substr($key,0,4) . '***' . substr($key,-4);
}

/**
 * 审核备注列展示：将「有人工单」用黄底红字高亮，其余转义为纯文本。
 */
function api_bind_format_audit_remark_display($remark) {
    if (function_exists('ggai_format_audit_remark_html')) {
        global $pdo;
        return ggai_format_audit_remark_html((string) ($remark ?? ''), (isset($pdo) && $pdo instanceof PDO) ? $pdo : null);
    }
    $remark = (string) ($remark ?? '');
    if ($remark === '') {
        return '';
    }
    return '<span style="color:#c00;font-weight:600;">' . htmlspecialchars($remark, ENT_QUOTES, 'UTF-8') . '</span>';
}

/** 审核备注列：存在「有人工单」标记时，整格悬停显示与会员首页一致的算力说明 */
function api_bind_audit_remark_cell_attrs($auditRemark) {
    if (!function_exists('trade_ai_marker_has_manual_trade_flag') || !trade_ai_marker_has_manual_trade_flag($auditRemark ?? '')) {
        return '';
    }
    $tip = __t(
        'user_api_id_tip_manual_intervention',
        '注意：有人工干预单。自己手工单盈了扣算力，亏了可能导致算力不补。'
    );
    return ' title="' . htmlspecialchars($tip, ENT_QUOTES, 'UTF-8') . '" style="cursor:help;"';
}

// ====== 新增：三大交易所推荐码处理 ======
$host = $_SERVER['HTTP_HOST'] ?? '';
$binance_referral_code = '';
$okx_referral_code = '';
// 从exchanges表动态获取默认推荐码
$default_binance_code = '';
$default_okx_code = '';
$stmt = $pdo->prepare("SELECT name, referral_code FROM exchanges WHERE name IN ('binance','okx')");
$stmt->execute();
$exchange_codes = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$default_binance_code = $exchange_codes['binance'] ?? '';
$default_okx_code = $exchange_codes['okx'] ?? '';
if ($host) {
    $host_no_www = preg_replace('/^www\./i', '', $host); // 去掉www.前缀
    $stmt = $pdo->prepare('SELECT * FROM partners WHERE domain=? LIMIT 1');
    $stmt->execute([$host_no_www]);
    $partnerInfoTmp = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($partnerInfoTmp) {
        $binance_referral_code = $partnerInfoTmp['binance_referral_code'] ?: $default_binance_code;
        $okx_referral_code = $partnerInfoTmp['okx_referral_code'] ?: $default_okx_code;
    } else {
        $binance_referral_code = $default_binance_code;
        $okx_referral_code = $default_okx_code;
    }
}
$has_partner_referral = ($binance_referral_code && $binance_referral_code !== $default_binance_code)
    || ($okx_referral_code && $okx_referral_code !== $default_okx_code);

// 交易所允许绑定 API 数量（来自 exchanges.allow_api_count）
$binance_allow_api_count = 1;
$okx_allow_api_count = 1;
$stmt = $pdo->prepare("SELECT name, allow_api_count FROM exchanges WHERE name IN ('binance','okx')");
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $name = strtolower($row['name'] ?? '');
    $cnt = max(1, intval($row['allow_api_count'] ?? 1));
    if ($name === 'binance') {
        $binance_allow_api_count = $cnt;
    } elseif ($name === 'okx') {
        $okx_allow_api_count = $cnt;
    }
}

// 获取当前用户合伙人下载地址
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT points, partner_id FROM users WHERE id=?");
$stmt->execute([$user_id]);
$user_row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_points = number_format(floatval($user_row['points']), 6, '.', '');
$partner_id = intval($user_row['partner_id'] ?? 0);
$download_url = '';
if ($partner_id) {
    $stmt2 = $pdo->prepare("SELECT download_url FROM partners WHERE id=?");
    $stmt2->execute([$partner_id]);
    $download_url = $stmt2->fetchColumn();
}
if (!$download_url) {
    $download_url = 'http://down.ggai365.com'; // 默认
}

// ====== 新增：浮动算力与实时算力统计（与首页一致） ======
$api_unrealized = [];
$api_ids = [];
$stmt = $pdo->prepare("SELECT id FROM api_accounts WHERE user_id=? AND status='active' AND is_paid_client=1");
$stmt->execute([$user_id]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $api_ids[] = $row['id'];
}
if ($api_ids) {
    foreach ($api_ids as $aid) {
        $stmt2 = $pdo->prepare("SELECT unrealized_pnl FROM power_logs WHERE api_id=? ORDER BY interval_end DESC LIMIT 1");
        $stmt2->execute([$aid]);
        $row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
        if ($row2) {
            $api_unrealized[] = floatval($row2['unrealized_pnl']);
        }
    }
}
$api_unrealized_fmt = array_map(function($v){ return (float)$v >= 0 ? '+' . number_format($v,1,'.','') : number_format($v,1,'.',''); }, $api_unrealized);
$unrealized_total = array_sum($api_unrealized);
$unrealized_formula = $api_unrealized ? implode('', $api_unrealized_fmt).'='.number_format($unrealized_total,1,'.','') : '0.0';
$power_deduct_ratio = 3;
$stmt = $pdo->query("SELECT value FROM system_settings WHERE key_name='power_deduct_ratio'");
$ratio = $stmt->fetchColumn();
if (is_numeric($ratio) && $ratio > 0) $power_deduct_ratio = floatval($ratio);
$float_power = intval(abs($unrealized_total) / $power_deduct_ratio);
$float_power_show = ($unrealized_total < 0 ? '+' : '-') . $float_power;
$points_base = intval($user_row['points'] ?? 0);
$realtime_power = $unrealized_total < 0 ? $points_base + $float_power : $points_base - $float_power;

ob_start();
?>
<?php
$user_id = $_SESSION['user_id'];
// 查询用户算力余额
$stmt = $pdo->prepare("SELECT points FROM users WHERE id=?");
$stmt->execute([$user_id]);
$user_points = floatval($stmt->fetchColumn());
// 获取系统设置
$settings = [];
$stmt = $pdo->query("SELECT key_name, value FROM system_settings");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $settings[$row['key_name']] = $row['value'];
}
$ip_whitelist = $settings['ip_whitelist'] ?? '';
$api_manual_review = $settings['api_manual_review'] ?? '1';
// 添加下一个 API 所需算力：基数×(已绑数量+1)
$min_power_api = intval($settings['min_power_for_api_submit'] ?? 95);
$stmtApiCnt = $pdo->prepare("SELECT COUNT(*) FROM api_accounts WHERE user_id=?");
$stmtApiCnt->execute([$user_id]);
$existing_api_count = intval($stmtApiCnt->fetchColumn());
$next_api_slot = $existing_api_count + 1;
$required_power_api = $min_power_api * $next_api_slot;
// 获取交易所列表（加密货币绑 API：排除国内期货类目，避免误选）
$_df_ex_where = domestic_futures_crypto_bind_exchange_sql($pdo);
$exchanges = $pdo->query(
    "SELECT id, name, display_name, register_url FROM exchanges WHERE status = 1 AND {$_df_ex_where} ORDER BY id ASC"
)->fetchAll(PDO::FETCH_ASSOC);
// 获取策略列表，包含风险等级与默认杠杆，按id升序
$strategies = $pdo->query("SELECT id, name, name_en, risk_level, default_leverage, sort_order FROM strategies WHERE status=1 ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
// 获取当前用户API信息（只取一条，按exchange_id=1优先，可扩展多交-易-所）
$stmt = $pdo->prepare("SELECT * FROM api_accounts WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$api = $stmt->fetch(PDO::FETCH_ASSOC);
// 获取当前用户信息（用户名、昵称）
$stmt = $pdo->prepare("SELECT username, nickname FROM users WHERE id=?");
$stmt->execute([$user_id]);
$user_info = $stmt->fetch(PDO::FETCH_ASSOC);
$username = $user_info['username'] ?? '';
$nickname = $user_info['nickname'] ?? '';
// 处理表单提交
$err = $msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($api && $api['status'] === 'active') {
        if ($api['has_pending_edit']) {
            $err = '有变更待审核，暂不可再次修改。';
    } else {
            $allowed_fields = ['strategy_id','strategy_type','is_custom_params','custom_params'];
            $old = [];
            $new = [];
            foreach ($allowed_fields as $f) {
                $old[$f] = $api[$f];
                $new[$f] = $_POST[$f] ?? '';
            }
            $new['api_status'] = $_POST['api_status'] ?? 'active';
            if ($old == $new) {
                $err = '未检测到变更';
            } else {
                $stmt = $pdo->prepare("INSERT INTO api_change_logs (api_id, user_id, change_type, old_data, new_data, remark, ip_address, created_at) VALUES (?,?,?,?,?,?,?,NOW())");
                $stmt->execute([
                    $api['id'], $user_id, 'edit',
                    json_encode($old, JSON_UNESCAPED_UNICODE),
                    json_encode($new, JSON_UNESCAPED_UNICODE),
                    '', (function_exists('getUserActionIP') ? getUserActionIP($user_id) : (function_exists('getClientIP') ? getClientIP() : ($_SERVER['REMOTE_ADDR'] ?? '')))
                ]);
                $pdo->prepare("UPDATE api_accounts SET has_pending_edit=1 WHERE id=?")->execute([$api['id']]);
                $msg = '参数变更已提交，待管理员审核';
                // 刷新api数据
                $stmt = $pdo->prepare("SELECT * FROM api_accounts WHERE user_id = ? LIMIT 1");
                $stmt->execute([$user_id]);
                $api = $stmt->fetch(PDO::FETCH_ASSOC);
            }
        }
    } else {
        // 绑定API前，先查exchanges表的allow_api_count，判断当前用户该交易所已绑定API数量，超出则提示并禁止绑定。
        $exchange_id = $_POST['exchange_id'] ?? '';
        $stmt = $pdo->prepare("SELECT allow_api_count, name FROM exchanges WHERE id=?");
        $stmt->execute([$exchange_id]);
        $exchange_row = $stmt->fetch(PDO::FETCH_ASSOC);
        $allow_api_count = intval($exchange_row['allow_api_count'] ?? 1);
        $exchange_name = strtolower($exchange_row['name'] ?? '');
        $stmtUr = $pdo->prepare('SELECT role_id FROM users WHERE id=?');
        $stmtUr->execute([$user_id]);
        $user_role_id_bind = (int) $stmtUr->fetchColumn();
        if (in_array($user_role_id_bind, [9, 10, 11], true)) {
            $exidBind = (int) $exchange_id;
            if ($exidBind === 1) {
                $allow_api_count = 1;
            } elseif ($exidBind === 2) {
                $allow_api_count = 20;
            }
        }
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM api_accounts WHERE user_id=? AND exchange_id=?");
        $stmt->execute([$user_id, $exchange_id]);
        $current_api_count = intval($stmt->fetchColumn());
        if ($current_api_count >= $allow_api_count) {
            $err = "该交易所已绑定API数量超出限制，最多可绑定 $allow_api_count 个API。";
        } else {
            // 逐字段赋值
        $read_key = trim($_POST['read_key'] ?? '');
        $read_secret = trim($_POST['read_secret'] ?? '');
        $read_password = trim($_POST['read_password'] ?? '');
        $trade_key = trim($_POST['trade_key'] ?? '');
        $trade_secret = trim($_POST['trade_secret'] ?? '');
        $trade_password = trim($_POST['trade_password'] ?? '');
        $is_referral = intval($_POST['is_referral'] ?? 0);
        $referral_exchange = trim($_POST['referral_exchange'] ?? '');
        $referral_userid = trim($_POST['referral_userid'] ?? '');
        $status = 'pending';
        $updated_at = date('Y-m-d H:i:s');
        $strategy_id = $_POST['strategy_id'] ?? null;
        $is_custom_params = intval($_POST['is_custom_params'] ?? 0);
        $custom_params = $is_custom_params && !empty($_POST['custom_params_json']) ? $_POST['custom_params_json'] : null;
        $new = [
            'strategy_id' => $_POST['strategy_id'],
            'is_custom_params' => $_POST['is_custom_params'],
            'custom_params' => $_POST['custom_params_json'],
            'api_status' => $_POST['api_status'] ?? 'active'
        ];
        // 新增：交易合约字段校验
        if ($is_custom_params && !empty($_POST['custom_contracts'])) {
            $contracts = trim($_POST['custom_contracts']);
            // 1. 只能字母、数字、小写逗号分隔，2. 不能有空格和特殊字符，3. 最后一位不能是逗号
            if (!preg_match('/^[A-Za-z0-9]+(,[A-Za-z0-9]+)*$/', $contracts)) {
                $err = '交易合约格式有误，只能填写字母、数字，多个合约用英文逗号分隔，不能有空格或特殊字符，最后一位不能是逗号。';
            } else {
                // 4. 不能有USDT等后缀
                $arr = explode(',', $contracts);
                foreach ($arr as $c) {
                    if (preg_match('/USDT$/i', $c)) {
                        $err = '请勿填写带USDT等后缀的合约，只需填写前缀，如BTC、ETH等。';
                        break;
                    }
                }
            }
        }
        if (!function_exists('encrypt_api_account_row_for_write')) {
            require_once __DIR__ . '/../includes/user_api_crypto.php';
        }
        ggai_ensure_api_key_fp_columns($pdo);
        $encRow = encrypt_api_account_row_for_write([
            'read_key' => $read_key,
            'read_secret' => $read_secret,
            'read_password' => $read_password,
            'trade_key' => $trade_key,
            'trade_secret' => $trade_secret,
            'trade_password' => $trade_password,
        ]);
        $read_key_db = (string)($encRow['read_key'] ?? '');
        $read_secret_db = (string)($encRow['read_secret'] ?? '');
        $read_password_db = (string)($encRow['read_password'] ?? '');
        $trade_key_db = (string)($encRow['trade_key'] ?? '');
        $trade_secret_db = (string)($encRow['trade_secret'] ?? '');
        $trade_password_db = (string)($encRow['trade_password'] ?? '');
        $hasFpCols = ggai_api_accounts_has_fp_columns($pdo);
        $trade_key_fp_db = (string)($encRow['trade_key_fp'] ?? '');
        $read_key_fp_db = (string)($encRow['read_key_fp'] ?? '');

        if ($api) {
            // 更新
            $sql = "UPDATE api_accounts SET exchange_id=?, read_key=?, read_secret=?, read_password=?, trade_key=?, trade_secret=?, trade_password=?"
                . ($hasFpCols ? ", trade_key_fp=?, read_key_fp=?" : "")
                . ", is_referral=?, referral_exchange=?, referral_userid=?, status=?, updated_at=?, strategy_id=?, is_custom_params=?, custom_params=? WHERE id=? AND user_id=?";
            $params = [
                $exchange_id, $read_key_db, $read_secret_db, $read_password_db, $trade_key_db, $trade_secret_db, $trade_password_db,
            ];
            if ($hasFpCols) {
                $params[] = ($trade_key_fp_db !== '' ? $trade_key_fp_db : null);
                $params[] = ($read_key_fp_db !== '' ? $read_key_fp_db : null);
            }
            $params = array_merge($params, [
                $is_referral, $referral_exchange, $referral_userid, $status, $updated_at, $strategy_id, $is_custom_params, $custom_params,
                $api['id'], $user_id
            ]);
            $pdo->prepare($sql)->execute($params);
                $api_id = $api['id'];
        } else {
            // 新增（显式跳号 id，避免连号）
            $sql = $hasFpCols
                ? "INSERT INTO api_accounts (id, user_id, exchange_id, read_key, read_secret, read_password, trade_key, trade_secret, trade_password, trade_key_fp, read_key_fp, is_referral, referral_exchange, referral_userid, status, created_at, updated_at, strategy_id, is_custom_params, custom_params) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?,?,?)"
                : "INSERT INTO api_accounts (id, user_id, exchange_id, read_key, read_secret, read_password, trade_key, trade_secret, trade_password, is_referral, referral_exchange, referral_userid, status, created_at, updated_at, strategy_id, is_custom_params, custom_params) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?,?,?)";
            $api_id = 0;
            $bindInserted = false;
            for ($idTry = 0; $idTry < 5; $idTry++) {
                $allocId = function_exists('ggai_allocate_next_api_account_id')
                    ? ggai_allocate_next_api_account_id($pdo)
                    : ((int)$pdo->query('SELECT COALESCE(MAX(id),0) FROM api_accounts')->fetchColumn() + mt_rand(3, 5));
                if ($hasFpCols) {
                    $params = [
                        $allocId, $user_id, $exchange_id, $read_key_db, $read_secret_db, $read_password_db, $trade_key_db, $trade_secret_db, $trade_password_db,
                        ($trade_key_fp_db !== '' ? $trade_key_fp_db : null),
                        ($read_key_fp_db !== '' ? $read_key_fp_db : null),
                        $is_referral, $referral_exchange, $referral_userid, $status, $updated_at, $strategy_id, $is_custom_params, $custom_params
                    ];
                } else {
                    $params = [
                        $allocId, $user_id, $exchange_id, $read_key_db, $read_secret_db, $read_password_db, $trade_key_db, $trade_secret_db, $trade_password_db,
                        $is_referral, $referral_exchange, $referral_userid, $status, $updated_at, $strategy_id, $is_custom_params, $custom_params
                    ];
                }
                try {
                    $pdo->prepare($sql)->execute($params);
                    $api_id = $allocId;
                    $bindInserted = true;
                    break;
                } catch (PDOException $dupEx) {
                    $sqlState = (string)($dupEx->errorInfo[0] ?? '');
                    $isDup = ($sqlState === '23000' || stripos($dupEx->getMessage(), 'Duplicate') !== false);
                    if ($isDup && $idTry < 4) {
                        continue;
                    }
                    throw $dupEx;
                }
            }
            if (!$bindInserted) {
                $err = '分配 API ID 失败，请重试';
            }
            }
            if ($err === '') {
            // 临时关闭会员提交时的同步划转测试：交易所接口或数据库慢时会卡住最后一步。
            // 不写 transfer_tested=1，后台仍可在审核时手动发起划转测试。
            $msg = 'API信息已提交，资金权限划转测试已临时关闭，后续管理员审核时可再次测试。';
        // 刷新api数据
        $stmt = $pdo->prepare("SELECT * FROM api_accounts WHERE user_id = ? LIMIT 1");
        $stmt->execute([$user_id]);
        $api = $stmt->fetch(PDO::FETCH_ASSOC);
        // === 新增：API提交后邮件通知管理员 ===
        $admin_emails = get_system_setting('admin_email');
        if ($admin_emails) {
            $admin_emails_arr = array_filter(array_map('trim', explode(',', $admin_emails)));
            $user_info = $pdo->prepare("SELECT username, email FROM users WHERE id=?");
            $user_info->execute([$user_id]);
            $user = $user_info->fetch(PDO::FETCH_ASSOC);
            $subject = '【系统通知】有新API信息待审核';
            $body = "有用户提交了新的API信息，请及时审核：\n" .
                "用户名：" . ($user['username'] ?? $user_id) . "\n" .
                "邮箱：" . ($user['email'] ?? '') . "\n" .
                "提交时间：" . date('Y-m-d H:i:s') . "\n" .
                "请登录后台进行审核。";
            foreach ($admin_emails_arr as $mail) {
                try { send_mail($mail, $subject, $body); } catch (Exception $e) {}
            }
        }
        // === END 邮件通知 ===
        }
        }
    }
}
// 是否只读
$readonly = ($api && $api['status'] === 'active');
// 新增：审核被拒绝时显示备注
$audit_remark = ($api && $api['status'] === 'rejected' && !empty($api['audit_remark'])) ? $api['audit_remark'] : '';
// 查询当前用户所有API记录
// 重要：多机/主从延迟场景下，可能出现“数据写入落到某库/某节点，另一个库暂时读不到”的情况。
// 为避免“明明存在但用户API管理为空”，这里做两段回查：优先读库(从库)，空则回查主库。
$api_list = [];
$pdoUsed = $pdo;
$source = 'default';
if (function_exists('get_db_connection')) {
    // 1) 优先读库（主库优先，主库不可用时回落从库）
    try {
        $pdoReadTry = get_db_connection("SELECT 1"); // 读连接（主库优先）
        $stmtR = $pdoReadTry->prepare("SELECT * FROM api_accounts WHERE user_id = ? ORDER BY created_at DESC");
        $stmtR->execute([$user_id]);
        $api_list = $stmtR->fetchAll(PDO::FETCH_ASSOC);
        if (!empty($api_list)) {
            $pdoUsed = $pdoReadTry;
            $source = 'read';
        }
    } catch (Throwable $e) {
        // ignore
    }

    // 2) 读库为空，则回查主库（强一致）
    if (empty($api_list)) {
        try {
            $pdoMasterTry = get_db_connection("SELECT 1", true);
            $stmtM = $pdoMasterTry->prepare("SELECT * FROM api_accounts WHERE user_id = ? ORDER BY created_at DESC");
            $stmtM->execute([$user_id]);
            $api_list = $stmtM->fetchAll(PDO::FETCH_ASSOC);
            if (!empty($api_list)) {
                $pdoUsed = $pdoMasterTry;
                $source = 'master';
            }
        } catch (Throwable $e) {
            // ignore
        }
    }
}

// 统一后续使用同一个连接（避免一半查主库一半查从库导致数据不一致）
$pdo = $pdoUsed;
if (!empty($api_list) && empty($api) && !empty($api_list[0]) && is_array($api_list[0])) {
    $api = $api_list[0];
}

// 记录命中来源（只在发生回查且有结果时记录，避免日志过大）
if (!empty($api_list) && $source !== 'default') {
    $logFile = dirname(__DIR__) . '/logs/db_master_fallback.log';
    @file_put_contents($logFile, date('Y-m-d H:i:s') . " api-bind.php source={$source} hit user_id={$user_id} count=" . count($api_list) . "\n", FILE_APPEND);
}
// 构建策略ID到名称的映射（与会员首页 / add-api / 策略对比页一致：语言包 → name_en → translate_content）
$strategyMap = [];
$strategyDefaultLeverageMap = [];
foreach ($strategies as $s) {
    $sid = (int) ($s['id'] ?? 0);
    $strategyMap[$sid] = function_exists('ggai_resolve_strategy_display_name')
        ? ggai_resolve_strategy_display_name(
            (string) ($s['name'] ?? ''),
            isset($s['name_en']) ? (string) $s['name_en'] : null,
            $pdo,
            $sid > 0 ? $sid : null
        )
        : (string) ($s['name'] ?? '');
    $strategyDefaultLeverageMap[$sid] = $s['default_leverage'] ?? '';
}

function black_swan_level_label($val) {
    return api_black_swan_level_label($val);
}

function build_custom_params_summary($row, $strategyDefaultLeverageMap, array $strategies = []) {
    $paramsArr = [];
    if (!empty($row['custom_params'])) {
        $decoded = json_decode($row['custom_params'], true);
        if (is_array($decoded)) {
            $paramsArr = $decoded;
        }
    }

    $red = function($text) {
        return '<span style="color:#ff4d4f;">' . htmlspecialchars((string)$text) . '</span>';
    };

    $multiDirectionKeys = [
        'hedge_pair_direction_btc_eth',
        'hedge_pair_direction_xau_xag',
        'hedge_pair_direction_cl_bz',
    ];
    $formOptions = function_exists('api_hedge_pair_direction_form_options_from_api')
        ? api_hedge_pair_direction_form_options_from_api($row, $strategies)
        : ['strategy_name' => '', 'strategy_file' => '', 'strategy_sort_order' => null];
    $isMulti = function_exists('api_hedge_pair_direction_is_multi_strategy')
        && api_hedge_pair_direction_is_multi_strategy(
            (string)($formOptions['strategy_name'] ?? ''),
            (string)($formOptions['strategy_file'] ?? ''),
            $formOptions['strategy_sort_order'] ?? null
        );
    $groupBasesByKey = [];
    if ($isMulti && function_exists('api_hedge_pair_direction_group_definitions')) {
        foreach (api_hedge_pair_direction_group_definitions() as $def) {
            $groupBasesByKey[$def['custom_key']] = $def['bases'];
        }
    }

    $items = [];
    $idx = 0;
    foreach (api_manage_custom_params_core_label_map() as $key => $label) {
        // 多组只显示 B/J/Y 首仓；单组只显示「首仓方向」（多组不再用单栏 hedge_pair_direction）
        if ($isMulti) {
            if ($key === 'hedge_pair_direction') {
                continue;
            }
        } elseif (in_array($key, $multiDirectionKeys, true)) {
            continue;
        }

        // 自选运行组：非多组且无三键时不展示
        if ($key === 'multi_pair_groups') {
            $mpDisp = function_exists('api_multi_pair_groups_positions_display')
                ? api_multi_pair_groups_positions_display($paramsArr, array_merge($row, [
                    'strategy_name' => (string)($formOptions['strategy_name'] ?? ''),
                    'strategy_file' => (string)($formOptions['strategy_file'] ?? ''),
                    'strategy_sort_order' => $formOptions['strategy_sort_order'] ?? null,
                ]))
                : ['show' => false, 'text' => ''];
            if (empty($mpDisp['show'])) {
                continue;
            }
            $text = (string)($mpDisp['text'] ?? '');
            $items[] = api_manage_render_custom_param_item(
                $key,
                $label,
                $red($text),
                function_exists('api_multi_pair_groups_has_any_key') && api_multi_pair_groups_has_any_key($paramsArr),
                $idx === 0
            );
            $idx++;
            continue;
        }

        $val = $paramsArr[$key] ?? '';
        if ($key === 'hedge_pair_direction' && function_exists('api_hedge_pair_direction_display_for_api_row')) {
            $text = api_hedge_pair_direction_display_for_api_row($val, $row, $strategies);
            if (function_exists('api_manage_summary_normalize_display_text')) {
                $text = api_manage_summary_normalize_display_text($text);
            }
        } elseif (isset($groupBasesByKey[$key]) && function_exists('api_hedge_pair_direction_display_value')) {
            $text = api_hedge_pair_direction_display_value($val, $groupBasesByKey[$key]);
            if (function_exists('api_manage_summary_normalize_display_text')) {
                $text = api_manage_summary_normalize_display_text($text);
            }
        } else {
            $text = api_manage_custom_param_summary_value($key, $val);
        }
        $items[] = api_manage_render_custom_param_item(
            $key,
            $label,
            $red($text),
            api_manage_custom_param_is_modified($key, $val),
            $idx === 0
        );
        $idx++;
    }

    $coreKeys = array_keys(api_manage_custom_params_core_label_map());
    $paramMap = [
        'contracts' => __t('api_manage_summary_short_contracts', '合约'),
        'stop_loss' => __t('api_manage_summary_short_stop_loss', '止损'),
        'take_profit' => __t('api_manage_summary_short_take_profit', '止盈'),
        'auto_withdraw' => __t('api_manage_custom_param_auto_withdraw', '自动提现'),
        'withdraw_threshold' => __t('api_manage_summary_short_withdraw_threshold', '提现阈值'),
        'withdraw_percent' => __t('api_manage_summary_short_withdraw_percent', '提现比例'),
        'loss_position_speed' => __t('api_manage_summary_short_loss_speed', '亏加'),
        'profit_position_speed' => __t('api_manage_summary_short_profit_speed', '盈加'),
        'min_add_position_interval' => __t('api_manage_summary_short_add_interval', '加仓间隔'),
        'trend_degree' => __t('api_manage_summary_short_trend', '趋势'),
    ];

    if (!empty($row['is_custom_params'])) {
        foreach ($paramMap as $k => $label) {
            if (in_array($k, $coreKeys, true) || !isset($paramsArr[$k])) {
                continue;
            }
            $val = $paramsArr[$k];
            if ($val === '' || $val === null) {
                continue;
            }
            if ($k === 'auto_withdraw' && (string)$val === '0') {
                continue;
            }
            $display = function_exists('api_custom_params_format_value_for_display')
                ? api_custom_params_format_value_for_display($k, $val)
                : (string)$val;
            if (function_exists('api_manage_summary_normalize_display_text')) {
                $display = api_manage_summary_normalize_display_text($display);
            }
            $items[] = api_manage_render_custom_param_item(
                $k,
                $label,
                $red($display),
                true,
                $idx === 0
            );
            $idx++;
        }
    }

    $body = implode('', $items);
    if (empty($row['is_custom_params'])) {
        return '<span class="api-cp-summary">'
            . '<span class="api-cp-open">' . htmlspecialchars(__t('api_manage_summary_default_open', '默认('), ENT_QUOTES, 'UTF-8') . '</span>'
            . '<span class="api-cp-body">' . $body . '</span>'
            . '<span class="api-cp-close">' . htmlspecialchars(__t('api_manage_summary_default_close', ')'), ENT_QUOTES, 'UTF-8') . '</span>'
            . '</span>';
    }

    return '<span class="api-cp-summary"><span class="api-cp-body">' . $body . '</span></span>';
}
// 新增：参数变更待审核API
$stmt = $pdo->prepare("
    SELECT a.*, l.created_at as change_submitted, l.new_data, l.old_data
    FROM api_accounts a
    LEFT JOIN (
        SELECT t1.*
        FROM api_change_logs t1
        INNER JOIN (
            SELECT api_id, MAX(id) as max_id
            FROM api_change_logs
            WHERE change_type='edit'
            GROUP BY api_id
        ) t2 ON t1.api_id = t2.api_id AND t1.id = t2.max_id
    ) l ON a.id = l.api_id
    WHERE a.user_id = ? AND a.has_pending_edit = 1
    ORDER BY a.id DESC
");
$stmt->execute([$_SESSION['user_id']]);
$pending_changes = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <h2><?= __t('api_manage_page_title', '我的API管理'); ?></h2>
    <div>
        <a href="<?= htmlspecialchars(ggai_mu('/user/index.php'), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-outline-secondary mr-2">
            <i class="fas fa-home me-1"></i> <?= __t('common_back_home', '返回会员首页'); ?>
        </a>
        <a href="<?= htmlspecialchars(ggai_mu('/user/add-api.php'), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-primary mr-2"><?= __t('api_manage_btn_add_api', '添加API'); ?></a>
    </div>
</div>
<div class="api-cp-filter-bar mb-3" id="apiCpFilterBar">
    <label class="api-cp-filter-toggle mb-0" for="apiCpModifiedOnly">
        <input class="api-cp-filter-checkbox" type="checkbox" id="apiCpModifiedOnly">
        <span class="api-cp-filter-text">
            <span class="api-cp-filter-title"><?= __t('api_manage_cp_modified_only_label', '仅显示有修改的自定义参数'); ?></span>
            <span class="api-cp-filter-hint"><?= __t('api_manage_cp_modified_only_hint', '选中后除杠杆与抗黑外，未改动的参数不显示；偏好保存在本浏览器。'); ?></span>
            <span class="api-cp-filter-tip"><?= __t('api_manage_cp_default_tip', '自定义参数不会或不懂的用默认即可'); ?></span>
        </span>
    </label>
</div>
<?php
// 按状态分组；最新权益：BA/OE/HY 优先 insight（与交易所/持仓页同源）；ONE 仍用库内 equity（insight 常不含浮盈）
$active_apis = [];
$pending_apis = [];
$other_apis = [];
foreach ($api_list as $row) {
    $exIdBind = intval($row['exchange_id'] ?? 0);
    if ($exIdBind !== 7) {
        $insight_raw = $row['pair_open_insight'] ?? '';
        if (is_string($insight_raw) && $insight_raw !== '') {
            $insight_arr = json_decode($insight_raw, true);
            if (is_array($insight_arr) && isset($insight_arr['equity']) && is_numeric($insight_arr['equity'])) {
                $row['equity'] = floatval($insight_arr['equity']);
            }
        }
    }
    // 待审核变更的展示规则：
    // - active/pending：只在“参数变更待审核API”显示，避免重复
    // - overdue/inactive/rejected：仍需在“其它状态API”显示，避免欠费停机等状态被隐藏
    if ($row['has_pending_edit'] == 1 && in_array($row['status'], ['active', 'pending'], true)) {
        continue;
    }
    
    if ($row['status'] === 'active') $active_apis[] = $row;
    elseif ($row['status'] === 'pending') $pending_apis[] = $row;
    else $other_apis[] = $row;
}
$apiStrategyCellTitle = htmlspecialchars(__t(
    'api_manage_tip_strategy_cell',
    '可自由更换策略，除首次绑定时有限制外，后续更换不再严格限制每个策略的起始资金，请自行注意风险'
), ENT_QUOTES, 'UTF-8');
// 表头仅短名；旧翻译若仍带括号说明则剥掉，避免手机缓存/旧语言包显示长标题
$apiCustomParamsColLabel = __t('api_manage_col_custom_params_short', '自定义参数');
$apiCustomParamsColLabel = preg_replace('/\s*[\(（][^）\)]*[\)）]\s*/u', '', (string)$apiCustomParamsColLabel);
$apiCustomParamsColLabel = trim((string)$apiCustomParamsColLabel);
if ($apiCustomParamsColLabel === '' || preg_match('/不会|不懂|默认即可|don\'t know|defaults/iu', $apiCustomParamsColLabel)) {
    $apiCustomParamsColLabel = '自定义参数';
}
?>
<!-- 已审核通过 -->
<h4><?= __t('api_manage_section_active', '已审核通过的API'); ?></h4>
<p class="small text-warning mb-2" style="line-height:1.55;"><?= htmlspecialchars(__t(
    'api_manage_tip_withdraw_min_equity',
    '（除系统亏损导致金额低于一千的情况外，将资金提出少于1000U将会停机）'
), ENT_QUOTES, 'UTF-8'); ?></p>
<?php if (empty($active_apis)): ?>
    <div class="text-muted mb-3"><?= __t('api_manage_section_active_empty', '暂无已审核通过的API'); ?></div>
<?php else: ?>
<div class="table-responsive mb-4">
            <table class="table table-bordered table-striped mb-0">
                <thead>
                    <tr>
                        <th><?= __t('api_manage_col_exchange', '交易所'); ?></th>
                        <th><?= __t('api_manage_col_strategy', '策略名称'); ?></th>
                        <th><?= htmlspecialchars($apiCustomParamsColLabel, ENT_QUOTES, 'UTF-8'); ?></th>
                        <th><?= __t('api_manage_col_read_key', '只读API Key'); ?></th>
                        <th><?= __t('api_manage_col_trade_key', '交易API Key'); ?></th>
                        <th><?= __t('api_manage_col_equity', '最新权益'); ?></th>
                        <th><?= __t('api_manage_col_created_at', '提交时间'); ?></th>
                        <th><?= __t('api_manage_col_audit_remark', '审核备注'); ?></th>
                        <th><?= __t('api_manage_col_status', '当前状态'); ?></th>
                        <th><?= __t('api_manage_col_actions', '操作'); ?></th>
                    </tr>
                </thead>
                <tbody>
    <?php foreach ($active_apis as $row): ?>
                    <?php
                        $ex_name = '';
                        foreach ($exchanges as $ex) {
                            if ($ex['id'] == $row['exchange_id']) {
                                $ex_name = $ex['display_name'];
                                break;
                            }
                        }
                        $ex_name = str_replace(['币安','BINANCE','币安链','BA','欧易','OKX'], ['币AN','BA','币AN链','BA','OE','OE'], $ex_name);
                        $statusMap = [
                            'pending'  => __t('api_manage_status_pending', '待审核'),
                            'active'   => __t('api_manage_status_active', '正常'),
                            'inactive' => __t('api_manage_status_inactive', '禁用'),
                            'rejected' => __t('api_manage_status_rejected', '已拒绝'),
                            'overdue'  => __t('api_manage_status_overdue', '已欠费'),
                        ];
                        $custom_params_label = build_custom_params_summary($row, $strategyDefaultLeverageMap, $strategies);
        ?>
        <tr>
            <?php
            $register_url = '';
            foreach ($exchanges as $ex) {
                if ($ex['id'] == $row['exchange_id']) {
                    $register_url = $ex['register_url'] ?? '';
                    break;
                }
            }
            ?>
            <td>
                <?php if (!empty($register_url)): ?>
                <a href="<?= htmlspecialchars($register_url) ?>" target="_blank" title="<?= __t('api_manage_tip_register_link', '如果打不开或要翻QIANG可以下载APP后注册时填推荐码'); ?>" style="color:inherit;text-decoration:underline;">
                    <?= htmlspecialchars($ex_name ?: $row['exchange_id']) ?>
                </a>
                <?php else: ?>
                    <?= htmlspecialchars($ex_name ?: $row['exchange_id']) ?>
                <?php endif; ?>
            </td>
            <td><span class="strategy-cell-hint d-inline-block" style="cursor:help;" title="<?= $apiStrategyCellTitle; ?>"><?php $sid = $row['strategy_id']; ?><a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" style="color:inherit;text-decoration:underline;"><?php echo isset($strategyMap[$sid]) ? htmlspecialchars($strategyMap[$sid]) : ''; ?></a></span></td>
            <td><a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars(api_bind_custom_params_link_title(), ENT_QUOTES, 'UTF-8'); ?>" style="color:inherit;text-decoration:underline;"><?php echo $custom_params_label; ?></a></td>
            <td style="word-break:break-all;"><?php echo htmlspecialchars(mask_api_key($row['read_key'])); ?></td>
            <td style="word-break:break-all;"><?php echo htmlspecialchars(mask_api_key($row['trade_key'])); ?></td>
            <td><?php echo number_format($row['equity'], 2); ?> U</td>
            <td><?php echo htmlspecialchars($row['created_at']); ?></td>
            <td<?php echo api_bind_audit_remark_cell_attrs($row['audit_remark'] ?? ''); ?>><?php echo api_bind_format_audit_remark_display($row['audit_remark'] ?? ''); ?><?php if (!empty($row['audit_remark'])): ?><br><?php endif; ?><small style="color:#666;">（APIID：<strong style="color:#d00;"><?php echo $row['id']; ?></strong>）</small></td>
            <td>
                <?php echo $statusMap[$row['status']] ?? $row['status']; ?>
                <?php if ($row['status'] === 'overdue'): ?>
                    <div style="color:#ff4d4f;font-size:0.98em;"><?= __t('api_manage_overdue_tip', '充值后自动恢复激活，无需人工操作'); ?></div>
                <?php endif; ?>
            </td>
            <td class="api-actions-cell">
                <div class="api-actions-wrap">
                <a href="<?= htmlspecialchars(ggai_mu('/user/positions.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-sm btn-info" target="_blank" title="<?= __t('api_manage_tip_positions', '实时查看交易所的持仓明细'); ?>"><?= __t('api_manage_btn_positions', '持仓'); ?></a>
                <a href="<?= htmlspecialchars(ggai_mu('/user/power-detail.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-sm btn-warning" target="_blank" title="<?= __t('api_manage_tip_power', '查看资金曲线与算力扣减明细'); ?>"><?= __t('api_manage_btn_power', '算力'); ?></a>
                <a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-sm btn-primary" title="<?= __t('api_manage_tip_edit', '可以修改策略与杠杆等'); ?>"><?= __t('api_manage_btn_edit', '修改'); ?></a>
                <a href="<?= htmlspecialchars(ggai_mu('/user/cj.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-sm btn-info" target="_blank" title="<?= __t('api_manage_tip_trades', '实时查看交易所的成交明细，记录不在本地数据库保存'); ?>"><?= __t('api_manage_btn_trades', '成交'); ?></a>
                <button type="button" class="btn btn-sm btn-secondary js-disable-api" data-api-id="<?php echo $row['id']; ?>" title="<?= __t('api_manage_tip_disable', '禁用后约5分钟左右，策略会停止服务'); ?>"><?= __t('api_manage_btn_disable', '禁用'); ?></button>
                <?php if ($user_api_delete_enabled): ?>
                <button type="button" class="btn btn-sm btn-danger js-delete-api" data-api-id="<?php echo $row['id']; ?>" title="<?= __t('api_manage_tip_delete', '请谨慎操作，删除后不可恢复'); ?>"><?= __t('api_manage_btn_delete', '删除'); ?></button>
                <?php endif; ?>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<p class="d-md-none small text-muted mb-3 api-table-scroll-hint"><?= __t('api_manage_mobile_scroll_hint', '手机上可左右滑动表格；操作按钮固定在右侧。'); ?></p>
<?php endif; ?>
<!-- 待审核 -->
<h4 class="mt-4"><?= __t('api_manage_section_pending', '待审核的API'); ?></h4>
<?php if (empty($pending_apis)): ?>
    <div class="text-muted mb-3"><?= __t('api_manage_section_pending_empty', '暂无待审核的API'); ?></div>
<?php else: ?>
<div class="table-responsive mb-4">
<table class="table table-bordered table-striped mb-0">
    <thead>
        <tr>
            <th><?= __t('api_manage_col_exchange', '交易所'); ?></th>
            <th><?= __t('api_manage_col_strategy', '策略名称'); ?></th>
            <th><?= htmlspecialchars($apiCustomParamsColLabel, ENT_QUOTES, 'UTF-8'); ?></th>
            <th><?= __t('api_manage_col_read_key', '只读API Key'); ?></th>
            <th><?= __t('api_manage_col_trade_key', '交易API Key'); ?></th>
            <th><?= __t('api_manage_col_equity', '最新权益'); ?></th>
            <th><?= __t('api_manage_col_created_at', '提交时间'); ?></th>
            <th><?= __t('api_manage_col_audit_remark', '审核备注'); ?></th>
            <th><?= __t('api_manage_col_status', '当前状态'); ?></th>
            <th><?= __t('api_manage_col_actions', '操作'); ?></th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($pending_apis as $row): ?>
        <?php
            $ex_name = '';
            foreach ($exchanges as $ex) {
                if ($ex['id'] == $row['exchange_id']) {
                    $ex_name = $ex['display_name'];
                                break;
                            }
                        }
            $ex_name = str_replace(['币安','BINANCE','币安链','BA','欧易','OKX'], ['币AN','BA','币AN链','BA','OE','OE'], $ex_name);
            $statusMap = [
                'pending'  => __t('api_manage_status_pending', '待审核'),
                'active'   => __t('api_manage_status_active', '正常'),
                'inactive' => __t('api_manage_status_inactive', '禁用'),
                'rejected' => __t('api_manage_status_rejected', '已拒绝'),
                'overdue'  => __t('api_manage_status_overdue', '已欠费'),
            ];
                        $custom_params_label = build_custom_params_summary($row, $strategyDefaultLeverageMap, $strategies);
                    ?>
                    <tr>
                        <?php
                        $register_url = '';
                        foreach ($exchanges as $ex) {
                            if ($ex['id'] == $row['exchange_id']) {
                                $register_url = $ex['register_url'] ?? '';
                                break;
                            }
                        }
                        ?>
                        <td>
                            <?php if (!empty($register_url)): ?>
                            <a href="<?= htmlspecialchars($register_url) ?>" target="_blank" title="<?= __t('api_manage_tip_register_link', '如果打不开或要翻QIANG可以下载APP后注册时填推荐码'); ?>" style="color:inherit;text-decoration:underline;">
                                <?= htmlspecialchars($ex_name ?: $row['exchange_id']) ?>
                            </a>
                            <?php else: ?>
                                <?= htmlspecialchars($ex_name ?: $row['exchange_id']) ?>
                            <?php endif; ?>
                        </td>
            <td><span class="strategy-cell-hint d-inline-block" style="cursor:help;" title="<?= $apiStrategyCellTitle; ?>"><?php $sid = $row['strategy_id']; ?><a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" style="color:inherit;text-decoration:underline;"><?php echo isset($strategyMap[$sid]) ? htmlspecialchars($strategyMap[$sid]) : ''; ?></a></span></td>
                        <td><a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars(api_bind_custom_params_link_title(), ENT_QUOTES, 'UTF-8'); ?>" style="color:inherit;text-decoration:underline;"><?php echo $custom_params_label; ?></a></td>
                        <td style="word-break:break-all;"><?php echo htmlspecialchars(mask_api_key($row['read_key'])); ?></td>
                        <td style="word-break:break-all;"><?php echo htmlspecialchars(mask_api_key($row['trade_key'])); ?></td>
            <td><?php echo number_format($row['equity'], 2); ?> U</td>
                        <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                        <td<?php echo api_bind_audit_remark_cell_attrs($row['audit_remark'] ?? ''); ?>><?php echo api_bind_format_audit_remark_display($row['audit_remark'] ?? ''); ?><?php if (!empty($row['audit_remark'])): ?><br><?php endif; ?><small style="color:#666;">（APIID：<strong style="color:#d00;"><?php echo $row['id']; ?></strong>）</small></td>
                        <td>
                <?php echo $statusMap[$row['status']] ?? $row['status']; ?>
                <?php if ($row['status'] === 'overdue'): ?>
                    <div style="color:#ff4d4f;font-size:0.98em;"><?= __t('api_manage_overdue_tip', '充值后自动恢复激活，无需人工操作'); ?></div>
                <?php endif; ?>
                        </td>
                        <td class="api-actions-cell">
                <div class="api-actions-wrap">
                <a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-sm btn-warning font-weight-bold" style="color:#212529;" title="<?= htmlspecialchars(__t('api_manage_tip_reactivate_edit', '可以修改策略与杠杆等，修改后重新激活'), ENT_QUOTES, 'UTF-8'); ?>"><?= __t('api_manage_btn_reactivate', '修改后重新激活'); ?></a>
                </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
                            <?php endif; ?>
<!-- 其它状态 -->
<h4 class="mt-4"><?= __t('api_manage_section_other', '其它状态API'); ?></h4>
<?php if (empty($other_apis)): ?>
    <div class="text-muted mb-3"><?= __t('api_manage_section_other_empty', '暂无其它状态API'); ?></div>
<?php else: ?>
<div class="table-responsive mb-4">
<table class="table table-bordered table-striped mb-0">
    <thead>
        <tr>
            <th><?= __t('api_manage_col_exchange', '交易所'); ?></th>
            <th><?= __t('api_manage_col_strategy', '策略名称'); ?></th>
            <th><?= htmlspecialchars($apiCustomParamsColLabel, ENT_QUOTES, 'UTF-8'); ?></th>
            <th><?= __t('api_manage_col_read_key', '只读API Key'); ?></th>
            <th><?= __t('api_manage_col_trade_key', '交易API Key'); ?></th>
            <th><?= __t('api_manage_col_equity', '最新权益'); ?></th>
            <th><?= __t('api_manage_col_created_at', '提交时间'); ?></th>
            <th><?= __t('api_manage_col_audit_remark', '审核备注'); ?></th>
            <th><?= __t('api_manage_col_status', '当前状态'); ?></th>
            <th><?= __t('api_manage_col_actions', '操作'); ?></th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($other_apis as $row): ?>
        <?php
            $ex_name = '';
            foreach ($exchanges as $ex) {
                if ($ex['id'] == $row['exchange_id']) {
                    $ex_name = $ex['display_name'];
                    break;
                }
            }
            $ex_name = str_replace(['币安','BINANCE','币安链','BA','欧易','OKX'], ['币AN','BA','币AN链','BA','OE','OE'], $ex_name);
            $statusMap = [
                'pending'  => __t('api_manage_status_pending', '待审核'),
                'active'   => __t('api_manage_status_active', '正常'),
                'inactive' => __t('api_manage_status_inactive', '禁用'),
                'rejected' => __t('api_manage_status_rejected', '已拒绝'),
                'overdue'  => __t('api_manage_status_overdue', '已欠费'),
            ];
                        $custom_params_label = build_custom_params_summary($row, $strategyDefaultLeverageMap, $strategies);
        ?>
        <tr>
            <?php
            $register_url = '';
            foreach ($exchanges as $ex) {
                if ($ex['id'] == $row['exchange_id']) {
                    $register_url = $ex['register_url'] ?? '';
                    break;
                }
            }
            ?>
            <td>
                <?php if (!empty($register_url)): ?>
                <a href="<?= htmlspecialchars($register_url) ?>" target="_blank" title="<?= htmlspecialchars(__t('api_manage_tip_register_link', '如果打不开或要翻QIANG可以下载APP后注册时填推荐码'), ENT_QUOTES, 'UTF-8'); ?>" style="color:inherit;text-decoration:underline;">
                    <?= htmlspecialchars($ex_name ?: $row['exchange_id']) ?>
                </a>
                <?php else: ?>
                    <?= htmlspecialchars($ex_name ?: $row['exchange_id']) ?>
                <?php endif; ?>
            </td>
            <td><span class="strategy-cell-hint d-inline-block" style="cursor:help;" title="<?= $apiStrategyCellTitle; ?>"><?php $sid = $row['strategy_id']; ?><a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" style="color:inherit;text-decoration:underline;"><?php echo isset($strategyMap[$sid]) ? htmlspecialchars($strategyMap[$sid]) : ''; ?></a></span></td>
            <td><a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars(api_bind_custom_params_link_title(), ENT_QUOTES, 'UTF-8'); ?>" style="color:inherit;text-decoration:underline;"><?php echo $custom_params_label; ?></a></td>
            <td style="word-break:break-all;"><?php echo htmlspecialchars(mask_api_key($row['read_key'])); ?></td>
            <td style="word-break:break-all;"><?php echo htmlspecialchars(mask_api_key($row['trade_key'])); ?></td>
            <td><?php echo number_format($row['equity'], 2); ?> U</td>
            <td><?php echo htmlspecialchars($row['created_at']); ?></td>
            <td<?php echo api_bind_audit_remark_cell_attrs($row['audit_remark'] ?? ''); ?>><?php echo api_bind_format_audit_remark_display($row['audit_remark'] ?? ''); ?><?php if (!empty($row['audit_remark'])): ?><br><?php endif; ?><small style="color:#666;">（APIID：<strong style="color:#d00;"><?php echo $row['id']; ?></strong>）</small></td>
            <td>
                <?php echo $statusMap[$row['status']] ?? $row['status']; ?>
                <?php if ($row['status'] === 'overdue'): ?>
                    <div style="color:#ff4d4f;font-size:0.98em;"><?= __t('api_manage_overdue_tip', '充值后自动恢复激活，无需人工操作'); ?></div>
                <?php endif; ?>
            </td>
            <td class="api-actions-cell">
                <div class="api-actions-wrap">
                <a href="<?= htmlspecialchars(ggai_mu('/user/edit-api.php?api_id=' . (int)$row['id']), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-sm btn-warning font-weight-bold" style="color:#212529;" title="<?= htmlspecialchars(__t('api_manage_tip_reactivate_edit', '可以修改策略与杠杆等，修改后重新激活'), ENT_QUOTES, 'UTF-8'); ?>"><?= __t('api_manage_btn_reactivate', '修改后重新激活'); ?></a>
                <?php if ($user_api_delete_enabled): ?>
                <button type="button" class="btn btn-sm btn-danger js-delete-api" data-api-id="<?php echo $row['id']; ?>" title="<?= __t('api_manage_tip_delete', '请谨慎操作，删除后不可恢复'); ?>"><?= __t('api_manage_btn_delete', '删除'); ?></button>
                <?php endif; ?>
                </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
</div>
<?php endif; ?>
<!-- 新增：参数变更待审核API -->
<h4 class="mt-4"><?= __t('api_manage_section_pending_changes', '参数变更待审核API'); ?></h4>
<?php if (empty($pending_changes)): ?>
    <div class="text-muted"><?= __t('api_manage_section_pending_changes_empty', '暂无参数变更待审核的API。'); ?></div>
<?php else: ?>
    <table class="table table-bordered table-sm align-middle">
        <thead><tr>
            <th>ID</th><th>交易所</th><th>策略</th><th>变更提交时间</th><th>变更内容</th><th>状态</th>
        </tr></thead>
        <tbody>
        <?php foreach($pending_changes as $row): ?>
        <tr>
            <td><?php echo $row['id']; ?></td>
            <td><?php echo htmlspecialchars($row['exchange_id']); ?></td>
            <td><?php echo htmlspecialchars($row['strategy_id']); ?></td>
            <td><?php echo htmlspecialchars($row['change_submitted']); ?></td>
            <td>
                <?php
                // 美化变更内容（多语言）
                $data = json_decode($row['new_data'], true);
                $old_data = isset($row['old_data']) ? json_decode($row['old_data'], true) : null;
                $desc = [];
                // 状态变更
                if (isset($data['api_status'])) {
                    $old_status = isset($old_data['api_status']) ? $old_data['api_status'] : ($row['status'] ?? 'active');
                    $statusMap = [
                        'active'   => __t('api_manage_change_status_active', '正常'),
                        'inactive' => __t('api_manage_change_status_inactive', '禁用')
                    ];
                    if (!isset($old_data['api_status']) || $old_data['api_status'] !== $data['api_status']) {
                        $oldLabel = $statusMap[$old_status] ?? $old_status;
                        $newLabel = $statusMap[$data['api_status']] ?? $data['api_status'];
                        $desc[] = str_replace(
                            ['{old}','{new}'],
                            [$oldLabel, $newLabel],
                            __t('api_manage_change_status_text', 'API状态：{old}→{new}')
                        );
                    }
                } else {
                    // 如果没有api_status字段，但API当前状态是inactive，说明是要重新激活
                    if ($row['status'] === 'inactive') {
                        $desc[] = __t('api_manage_change_status_reactivate_text', 'API状态：禁用→正常（重新激活）');
                    }
                }
                // 其它参数 - 只显示真正变更的参数
                if (isset($data['custom_params']) && trim($data['custom_params']) !== '') {
                    $newParamsArr = json_decode($data['custom_params'], true);
                    $oldParamsArr = isset($old_data['custom_params']) ? json_decode($old_data['custom_params'], true) : [];
                    
                    if ($newParamsArr && is_array($newParamsArr)) {
                        $paramMap = [
                            'contracts' => __t('api_manage_custom_param_contracts', '交易合约'),
                            'multi_pair_group_btc_eth' => __t('api_manage_custom_param_multi_pair_group_btc_eth', '多组·币'),
                            'multi_pair_group_xau_xag' => __t('api_manage_custom_param_multi_pair_group_xau_xag', '多组·金'),
                            'multi_pair_group_cl_bz' => __t('api_manage_custom_param_multi_pair_group_cl_bz', '多组·油'),
                            'multi_pair_group_sp500_xyz100' => __t('api_manage_custom_param_multi_pair_group_sp500_xyz100', '多组·股指'),
                            'multi_pair_group_eur_gbp' => __t('api_manage_custom_param_multi_pair_group_eur_gbp', '多组·汇'),
                            'leverage' => __t('api_manage_custom_param_leverage', '杠杆倍数'),
                            'stop_loss' => __t('api_manage_custom_param_stop_loss', '止损比例'),
                            'hedge_dual_stop_loss' => __t('api_manage_custom_param_hedge_dual_stop_loss', '双合约盈亏累加止损'),
                            'hedge_remain_stop_loss' => __t('api_manage_custom_param_hedge_remain_stop_loss', '已平一腿余腿止损'),
                            'take_profit' => __t('api_manage_custom_param_take_profit', '止盈比例'),
                            'account_position_limit' => __t('api_manage_custom_param_account_position_limit', '总仓位限制'),
                            'net_position_limit' => __t('api_manage_custom_param_net_position_limit', '净头寸限制'),
                            'first_leg_amount_rate' => __t('api_manage_custom_param_first_leg_amount_rate', '首仓单边起始仓位'),
                            'hedge_pair_direction' => __t('api_manage_custom_param_hedge_pair_direction', '首仓方向'),
                            'hedge_pair_direction_btc_eth' => 'B组 BTC/ETH 首仓方向',
                            'hedge_pair_direction_xau_xag' => 'J组 XAU/XAG 首仓方向',
                            'hedge_pair_direction_cl_bz' => 'Y组 CL/BZ 首仓方向',
                            'hedge_pair_direction_sp500_xyz100' => 'I组 SP500/XYZ100 首仓方向',
                            'hedge_pair_direction_eur_gbp' => 'F组 EUR/GBP 首仓方向',
                            'open_threshold_scale' => __t('api_manage_custom_param_open_threshold_scale', '开仓阈值缩放系数'),
                            'tp_scale' => __t('api_manage_custom_param_tp_scale', '止盈缩放系数'),
                            'interval_scale' => __t('api_manage_custom_param_interval_scale', '分钟间隔缩放系数'),
                            'add_threshold_scale' => __t('api_manage_custom_param_add_threshold_scale', '加仓阈值缩放系数'),
                            'auto_withdraw' => __t('api_manage_custom_param_auto_withdraw', '自动提现'),
                            'withdraw_threshold' => __t('api_manage_custom_param_withdraw_threshold', '提现阈值'),
                            'withdraw_percent' => __t('api_manage_custom_param_withdraw_percent', '提现百分比'),
                            'loss_position_speed' => __t('api_manage_custom_param_loss_position_speed', '亏损加仓速度'),
                            'profit_position_speed' => __t('api_manage_custom_param_profit_position_speed', '加仓速度'),
                            'single_contract_max_position' => __t('api_manage_custom_param_single_contract_max_position', '单品种最大仓位'),
                            'min_add_position_interval' => __t('api_manage_custom_param_min_add_position_interval', '最小加仓间隔'),
                            'trend_degree' => __t('api_manage_custom_param_trend_degree', '趋势强度')
                        ];
                        
                        $changedDesc = [];
                        foreach ($paramMap as $k => $v) {
                            $oldValue = isset($oldParamsArr[$k]) ? $oldParamsArr[$k] : '';
                            $newValue = isset($newParamsArr[$k]) ? $newParamsArr[$k] : '';
                            
                            // 只显示真正发生变更的参数
                            if ($oldValue !== $newValue) {
                                $oldShow = $oldValue;
                                $newShow = $newValue;
                                if ($k === 'black_swan_level') {
                                    $oldShow = api_black_swan_level_label($oldValue);
                                    $newShow = api_black_swan_level_label($newValue);
                                } elseif ($k === 'leverage') {
                                    $oldShow = function_exists('api_custom_params_format_value_for_display')
                                        ? api_custom_params_format_value_for_display($k, $oldValue)
                                        : $oldValue;
                                    $newShow = function_exists('api_custom_params_format_value_for_display')
                                        ? api_custom_params_format_value_for_display($k, $newValue)
                                        : $newValue;
                                } elseif (in_array($k, ['hedge_dual_stop_loss', 'hedge_remain_stop_loss'], true)) {
                                    $oldShow = api_hedge_stop_loss_display_label($oldValue);
                                    $newShow = api_hedge_stop_loss_display_label($newValue);
                                } elseif (api_position_limit_custom_is_param_key($k)) {
                                    $oldShow = api_position_limit_custom_display_value($oldValue);
                                    $newShow = api_position_limit_custom_display_value($newValue);
                                } elseif (function_exists('api_custom_params_format_value_for_display')) {
                                    $oldShow = api_custom_params_format_value_for_display($k, $oldValue);
                                    $newShow = api_custom_params_format_value_for_display($k, $newValue);
                                }
                                $changedDesc[] = $v . '：' . htmlspecialchars($oldShow) . '→' . htmlspecialchars($newShow);
                            }
                        }
                        
                        if (!empty($changedDesc)) {
                            $shortDesc = array_slice($changedDesc, 0, 3);
                            $desc[] = implode('，', $shortDesc);
                        }
                        
                        // 显示所有变更内容（包括状态变更和参数变更）
                        if (!empty($desc)) {
                            if (count($desc) > 1) {
                                echo implode('，', $desc);
                                if (count($changedDesc) > 3) {
                                    echo ' <a href="#" onclick="this.nextElementSibling.style.display=\'inline\';this.style.display=\'none\';return false;" style="color:#00eaff;">' . __t('api_manage_change_expand', '展开') . '</a>';
                                    echo '<span style="display:none;">，' . implode('，', array_slice($changedDesc, 3)) . '</span>';
                                }
                            } else {
                                echo implode('，', $desc);
                            }
                        } else {
                            echo __t('api_manage_change_no_changes', '无变更');
                        }
                    } else {
                        echo implode('，', $desc) ?: __t('api_manage_change_none', '无');
                    }
                } else {
                    echo implode('，', $desc) ?: __t('api_manage_change_none', '无');
                }
                ?>
            </td>
            <td>
                <?php
                if (isset($data['api_status']) && $data['api_status'] === 'inactive') {
                    echo '<span style="color:red;font-weight:bold;">禁用</span>';
                } else {
                    echo '<span class="badge bg-warning text-dark">待审核</span>';
                }
                ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
<!-- 修正版：参数变更被拒绝API（以变更日志审核状态为准） -->
<h4 class="mt-4"><?= __t('api_manage_section_rejected_changes', '参数变更被拒绝API'); ?></h4>
<?php
try {
    $stmt = $pdo->prepare("SELECT l.*, a.exchange_id, a.strategy_id, a.status as api_status, a.id as api_id, a.updated_at as api_updated_at
        FROM api_change_logs l
        LEFT JOIN api_accounts a ON l.api_id = a.id
        WHERE l.user_id = ? AND l.change_type = 'edit' AND l.review_status = 'rejected'
        ORDER BY l.id DESC LIMIT 20");
    $stmt->execute([$_SESSION['user_id']]);
    $rejected_logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
    echo '<div style=\'color:red\'>SQL/查询异常: '.htmlspecialchars($e->getMessage()).'</div>';
}
?>
<?php if (empty($rejected_logs)): ?>
    <div class="text-muted"><?= __t('api_manage_section_rejected_changes_empty', '暂无被拒绝的API。'); ?></div>
<?php else: ?>
    <table class="table table-bordered table-sm align-middle">
        <thead><tr>
            <th>API编号</th><th><?= __t('api_manage_col_exchange', '交易所'); ?></th><th><?= __t('api_manage_col_strategy', '策略'); ?></th><th><?= __t('api_manage_change_col_changes', '变更内容'); ?></th><th><?= __t('api_manage_change_col_created_at', '提交时间'); ?></th><th><?= __t('api_manage_change_col_remark', '审核备注'); ?></th><th><?= __t('api_manage_change_col_reviewed_at', '审核时间'); ?></th>
        </tr></thead>
        <tbody>
        <?php foreach($rejected_logs as $row): ?>
            <tr>
                <td><?php echo htmlspecialchars($row['api_id']); ?></td>
                <td><?php echo htmlspecialchars($row['exchange_id']); ?></td>
                <td><?php echo htmlspecialchars($row['strategy_id']); ?></td>
                <td>
                <?php
                // 美化变更内容（多语言）
                $data = json_decode($row['new_data'], true);
                $desc = [];
                if (isset($data['api_status'])) {
                    $statusMap = [
                        'active'   => __t('api_manage_change_status_active', '正常'),
                        'inactive' => __t('api_manage_change_status_inactive', '禁用')
                    ];
                    $statusLabel = $statusMap[$data['api_status']] ?? $data['api_status'];
                    $desc[] = str_replace(
                        ['{old}','{new}'],
                        ['', $statusLabel],
                        __t('api_manage_change_status_text', 'API状态：{old}→{new}')
                    );
                }
                if (isset($data['custom_params']) && trim($data['custom_params']) !== '') {
                    $paramsArr = json_decode($data['custom_params'], true);
                    if ($paramsArr && is_array($paramsArr)) {
                        $paramMap = [
                            'contracts' => __t('api_manage_custom_param_contracts', '交易合约'),
                            'multi_pair_group_btc_eth' => __t('api_manage_custom_param_multi_pair_group_btc_eth', '多组·币'),
                            'multi_pair_group_xau_xag' => __t('api_manage_custom_param_multi_pair_group_xau_xag', '多组·金'),
                            'multi_pair_group_cl_bz' => __t('api_manage_custom_param_multi_pair_group_cl_bz', '多组·油'),
                            'multi_pair_group_sp500_xyz100' => __t('api_manage_custom_param_multi_pair_group_sp500_xyz100', '多组·股指'),
                            'multi_pair_group_eur_gbp' => __t('api_manage_custom_param_multi_pair_group_eur_gbp', '多组·汇'),
                            'leverage' => __t('api_manage_custom_param_leverage', '杠杆倍数'),
                            'black_swan_level' => '抗黑天鹅等级',
                            'stop_loss' => __t('api_manage_custom_param_stop_loss', '止损比例'),
                            'hedge_dual_stop_loss' => __t('api_manage_custom_param_hedge_dual_stop_loss', '双合约盈亏累加止损'),
                            'hedge_remain_stop_loss' => __t('api_manage_custom_param_hedge_remain_stop_loss', '已平一腿余腿止损'),
                            'take_profit' => __t('api_manage_custom_param_take_profit', '止盈比例'),
                            'account_position_limit' => __t('api_manage_custom_param_account_position_limit', '总仓位限制'),
                            'net_position_limit' => __t('api_manage_custom_param_net_position_limit', '净头寸限制'),
                            'first_leg_amount_rate' => __t('api_manage_custom_param_first_leg_amount_rate', '首仓单边起始仓位'),
                            'hedge_pair_direction' => __t('api_manage_custom_param_hedge_pair_direction', '首仓方向'),
                            'hedge_pair_direction_btc_eth' => 'B组 BTC/ETH 首仓方向',
                            'hedge_pair_direction_xau_xag' => 'J组 XAU/XAG 首仓方向',
                            'hedge_pair_direction_cl_bz' => 'Y组 CL/BZ 首仓方向',
                            'hedge_pair_direction_sp500_xyz100' => 'I组 SP500/XYZ100 首仓方向',
                            'hedge_pair_direction_eur_gbp' => 'F组 EUR/GBP 首仓方向',
                            'open_threshold_scale' => __t('api_manage_custom_param_open_threshold_scale', '开仓阈值缩放系数'),
                            'tp_scale' => __t('api_manage_custom_param_tp_scale', '止盈缩放系数'),
                            'interval_scale' => __t('api_manage_custom_param_interval_scale', '分钟间隔缩放系数'),
                            'add_threshold_scale' => __t('api_manage_custom_param_add_threshold_scale', '加仓阈值缩放系数'),
                            'auto_withdraw' => __t('api_manage_custom_param_auto_withdraw', '自动提现'),
                            'withdraw_threshold' => __t('api_manage_custom_param_withdraw_threshold', '提现阈值'),
                            'withdraw_percent' => __t('api_manage_custom_param_withdraw_percent', '提现百分比'),
                            'loss_position_speed' => __t('api_manage_custom_param_loss_position_speed', '亏损加仓速度'),
                            'profit_position_speed' => __t('api_manage_custom_param_profit_position_speed', '加仓速度'),
                            'single_contract_max_position' => __t('api_manage_custom_param_single_contract_max_position', '单品种最大仓位'),
                            'min_add_position_interval' => __t('api_manage_custom_param_min_add_position_interval', '最小加仓间隔'),
                            'trend_degree' => __t('api_manage_custom_param_trend_degree', '趋势强度')
                        ];
                        $i = 0;
                        foreach ($paramMap as $k => $v) {
                            if (isset($paramsArr[$k]) && $paramsArr[$k] !== '') {
                                $showVal = $paramsArr[$k];
                                if ($k === 'black_swan_level') {
                                    $bsMap = [
                                        '8' => '一级(8)', '12' => '一级(12)',
                                        '18' => '二级(18)', '22' => '二级(22)',
                                        '28' => '三级(28)', '32' => '三级(32)',
                                        '38' => '四级(38)', '42' => '四级(42)',
                                        '48' => '五级(48)', '52' => '五级(52)',
                                        '58' => '六级(58)', '62' => '六级(62)',
                                    ];
                                    $showVal = $bsMap[(string)$paramsArr[$k]] ?? $paramsArr[$k];
                                } elseif (in_array($k, ['hedge_dual_stop_loss', 'hedge_remain_stop_loss'], true)) {
                                    $showVal = api_hedge_stop_loss_display_label($paramsArr[$k]);
                                } elseif (api_position_limit_custom_is_param_key($k)) {
                                    $showVal = api_position_limit_custom_display_value($paramsArr[$k]);
                                } elseif (function_exists('api_custom_params_format_value_for_display')) {
                                    $showVal = api_custom_params_format_value_for_display($k, $paramsArr[$k]);
                                }
                                $desc[] = $v.'：'.$showVal;
                                $i++;
                                if ($i >= 3) break;
                            }
                        }
                        if (count($paramsArr) > 3) {
                            $desc[] = '<a href="#" onclick="this.nextElementSibling.style.display=\'block\';this.style.display=\'none\';return false;">' . __t('api_manage_change_expand', '展开') . '</a><span style="display:none;">';
                            foreach ($paramMap as $k => $v) {
                                if (isset($paramsArr[$k]) && $paramsArr[$k] !== '') {
                                    $expandedVal = function_exists('api_custom_params_format_value_for_display')
                                        ? api_custom_params_format_value_for_display($k, $paramsArr[$k])
                                        : $paramsArr[$k];
                                    $desc[] = $v.'：'.$expandedVal;
                                }
                            }
                            $desc[] = '</span>';
                        }
                    }
                }
                echo implode('，', $desc) ?: __t('api_manage_change_none', '无');
                ?>
                </td>
                <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                <td><?php echo htmlspecialchars($row['remark']); ?></td>
                <td><?php echo htmlspecialchars($row['api_updated_at']); ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    <div class="mt-3">
        <a href="<?= htmlspecialchars(ggai_mu('/user/api-change-history.php'), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-outline-info"><?= __t('api_manage_change_history_btn', 'API参数变更历史'); ?></a>
    </div>
<?php endif; ?>
<style>
.api-cp-filter-bar {
    background: linear-gradient(135deg, #fff8e6 0%, #ffecb3 100%);
    border: 2px solid #ffb300;
    border-radius: 12px;
    padding: 14px 18px;
    box-shadow: 0 3px 12px rgba(255, 152, 0, 0.22);
}
.api-cp-filter-bar.is-active {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    border-color: #1976d2;
    box-shadow: 0 3px 12px rgba(25, 118, 210, 0.25);
}
.api-cp-filter-toggle {
    display: flex;
    align-items: flex-start;
    gap: 14px;
    cursor: pointer;
    user-select: none;
    width: 100%;
}
.api-cp-filter-checkbox {
    width: 22px;
    height: 22px;
    min-width: 22px;
    margin-top: 4px;
    cursor: pointer;
    accent-color: #ff9800;
    transform: scale(1.15);
}
.api-cp-filter-bar.is-active .api-cp-filter-checkbox {
    accent-color: #1976d2;
}
.api-cp-filter-text {
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.api-cp-filter-title {
    font-size: 1.12em;
    font-weight: 800;
    color: #e65100;
    line-height: 1.35;
}
.api-cp-filter-bar.is-active .api-cp-filter-title {
    color: #0d47a1;
}
.api-cp-filter-hint {
    font-size: 0.92em;
    color: #5d4037;
    line-height: 1.45;
}
.api-cp-filter-tip {
    display: block;
    margin-top: 6px;
    font-size: 0.95em;
    font-weight: 700;
    color: #c62828;
    line-height: 1.4;
}
.api-cp-filter-bar.is-active .api-cp-filter-hint {
    color: #1565c0;
}
.api-cp-filter-bar.is-active .api-cp-filter-tip {
    color: #b71c1c;
}
/* 跟随会员区深色底，避免白底导致字看不清 */
body, .main-wrapper, .content-area {
    background: transparent !important;
    color: #e8f4ff !important;
}
.api-card {
    background: rgba(12, 18, 36, 0.92) !important;
    color: #e8f4ff !important;
    border: 1px solid rgba(0, 234, 255, 0.18);
}
.table {
    background: transparent !important;
    color: #e8f4ff !important;
}
.table th, .table td {
    color: #e8f4ff !important;
}
/* 深色隔行底色：奇数略深、偶数略亮，字保持高对比 */
.table.table-striped > tbody > tr:nth-of-type(odd) > td,
.table.table-striped > tbody > tr:nth-of-type(odd) > th {
    background: rgba(8, 14, 28, 0.92) !important;
}
.table.table-striped > tbody > tr:nth-of-type(even) > td,
.table.table-striped > tbody > tr:nth-of-type(even) > th {
    background: rgba(0, 90, 140, 0.28) !important;
}
.table.table-striped > tbody > tr:hover > td,
.table.table-striped > tbody > tr:hover > th {
    background: rgba(0, 180, 220, 0.22) !important;
}
h2, h4, .card-header, .table thead th {
    color: #7df9ff !important;
    font-weight: bold !important;
    background: rgba(0, 60, 120, 0.35) !important;
    opacity: 1 !important;
    text-shadow: none !important;
}
.table thead th {
    border-bottom: 2px solid rgba(0, 234, 255, 0.2) !important;
}
.card-header {
    font-size: 1.15em !important;
    letter-spacing: 0.5px;
}
.api-card {
    background: rgba(12, 18, 36, 0.92);
    border-radius: 12px;
    box-shadow: 0 2px 16px rgba(0, 0, 0, 0.35);
    padding: 32px 28px 24px 28px;
    margin: 32px auto 0 auto;
    max-width: 900px;
    border: 1px solid rgba(0, 234, 255, 0.18);
}
.api-title {
    font-size: 1.6rem;
    font-weight: 600;
    color: #7df9ff;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.api-title i {
    color: #00eaff;
    font-size: 1.3em;
}
.api-desc {
    color: #9ec9d8;
    font-size: 1.05rem;
    margin-bottom: 22px;
}
.api-card .form-label {
    font-weight: 500;
    color: #b2f7ff;
}
.api-card input.form-control,
.api-card select.form-control,
.api-card textarea.form-control {
    border-radius: 6px;
    border: 1px solid #dbe2ea;
    box-shadow: none;
    transition: border-color 0.2s;
}
.api-card input.form-control:focus,
.api-card select.form-control:focus,
.api-card textarea.form-control:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0,123,255,0.08);
}
.api-card .btn-primary {
    background: linear-gradient(90deg,#007bff 0,#0056d2 100%);
    border: none;
    border-radius: 6px;
    font-weight: 600;
    padding: 8px 32px;
    font-size: 1.1rem;
    box-shadow: 0 2px 8px rgba(0,123,255,0.08);
    transition: background 0.2s;
}
.api-card .btn-primary:hover {
    background: linear-gradient(90deg,#0056d2 0,#007bff 100%);
}
.api-card .alert {
    border-radius: 6px;
    font-size: 1.02rem;
}
.api-card h5 {
    font-size: 1.1rem;
    color: #007bff;
    margin-bottom: 10px;
    font-weight: 600;
}
.api-card .row + .row {
    margin-top: 10px;
}
.api-card .form-text {
    color: #8a99b3;
}
.api-card .readonly {
    background: #f8f9fa;
    color: #888;
}
.api-actions-wrap {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    align-items: center;
}
/* 自定义参数：每一项独立一行，收窄列宽 */
.api-cp-summary,
.api-cp-body {
    display: block;
    white-space: normal;
    word-break: break-word;
    line-height: 1.45;
}
.api-cp-item {
    display: block;
    white-space: normal !important;
    word-break: break-word;
    margin: 0 0 2px 0;
    line-height: 1.4;
}
.api-cp-item.api-cp-item-hidden {
    display: none !important;
}
.api-cp-item .api-cp-comma {
    display: none !important;
}
.api-cp-open,
.api-cp-close {
    display: none;
}
@media (max-width: 768px) {
    .main-wrapper,
    .content-area.container {
        max-width: 100% !important;
        width: 100% !important;
        padding-left: 0 !important;
        padding-right: 0 !important;
        margin-left: 0 !important;
        margin-right: 0 !important;
    }
    .api-card {
        padding: 14px 8px 12px 8px;
        max-width: 100% !important;
        width: 100% !important;
        margin: 12px 0 0 0;
        box-sizing: border-box;
    }
    .table-responsive {
        display: block;
        width: 100%;
        max-width: 100%;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch;
        overscroll-behavior-x: contain;
        border: 1px solid #e3e8ee;
        border-radius: 8px;
    }
    .table-responsive > .table {
        width: max-content;
        min-width: 100%;
        margin-bottom: 0;
        overflow: visible !important;
    }
    .table-responsive .table thead th {
        white-space: nowrap;
    }
    .table-responsive .table td:nth-child(3),
    .table-responsive .table th:nth-child(3) {
        max-width: 46vw;
        min-width: 120px;
        white-space: normal !important;
        word-break: break-word;
    }
    .table-responsive .table th:nth-child(4),
    .table-responsive .table td:nth-child(4),
    .table-responsive .table th:nth-child(5),
    .table-responsive .table td:nth-child(5),
    .table-responsive .table th:nth-child(7),
    .table-responsive .table td:nth-child(7) {
        display: none;
    }
    .table-responsive .table th:last-child,
    .table-responsive .table td:last-child,
    .table-responsive .table .api-actions-cell {
        position: sticky;
        right: 0;
        z-index: 3;
        box-shadow: -6px 0 10px rgba(0, 0, 0, 0.08);
        min-width: 92px;
        max-width: 118px;
        white-space: normal !important;
        vertical-align: middle;
    }
    .table-responsive .table thead th:last-child {
        z-index: 4;
        background: rgba(0, 60, 120, 0.55) !important;
    }
    .table-responsive .table.table-striped > tbody > tr:nth-of-type(odd) > td.api-actions-cell,
    .table-responsive .table.table-striped > tbody > tr:nth-of-type(odd) > td:last-child {
        background: rgba(8, 14, 28, 0.98) !important;
    }
    .table-responsive .table.table-striped > tbody > tr:nth-of-type(even) > td.api-actions-cell,
    .table-responsive .table.table-striped > tbody > tr:nth-of-type(even) > td:last-child {
        background: rgba(0, 70, 110, 0.95) !important;
    }
    .api-actions-wrap {
        flex-direction: column;
        align-items: stretch;
        gap: 6px;
    }
    .api-actions-wrap .btn {
        width: 100%;
        margin: 0 !important;
        white-space: nowrap;
    }
    .api-table-scroll-hint {
        margin-top: 6px;
        padding: 0 4px;
    }
}
</style>
<div class="main-wrapper">
    <div class="content-area container">
        <div class="api-card">
            <div class="mb-3">
                <b><?= __t('api_manage_basic_power_label', '基础算力：'); ?></b>
                <span class="text-<?php echo $user_points < $required_power_api ? 'danger' : 'success'; ?>" style="font-size:1.2em;font-weight:bold;">
                    <?php echo $points_base; ?>
                </span>
                <span style="margin-left:18px;color:#555;font-size:1em;">
                    <?= __t('ctp_user_username', '用户名：'); ?><?php echo htmlspecialchars($username); ?>
                    <?php if ($nickname): ?>（<?= __t('ctp_user_nickname', '昵称：'); ?><?php echo htmlspecialchars($nickname); ?>）<?php endif; ?>
                </span>
                <?php if ($user_points < $required_power_api): ?>
                    <span class="text-danger ml-2" style="font-weight:bold;"><?php
                        echo htmlspecialchars(str_replace(
                            ['{n}', '{min}', '{unit}'],
                            [(string)$next_api_slot, (string)$required_power_api, (string)$min_power_api],
                            __t('api_manage_power_insufficient', '基础算力不足（按基础算力检测，非实时算力；绑定第{n}个API需≥{min}U，即{unit}×{n}），无法提交API绑定！')
                        ));
                    ?></span>
                <?php endif; ?>
            </div>
            <div class="mb-3" style="font-size:1.08em;">
                <span style="color:#00eaff;font-weight:bold;"><?= __t('api_manage_float_power_label', '浮动算力：'); ?></span><?php echo $float_power_show; ?>
                <span style="margin-left:2em;color:#3fa7ff;font-weight:bold;"><?= __t('api_manage_realtime_power_label', '实时算力余额：'); ?></span><?php echo $realtime_power; ?>
            </div>
            <div class="mb-3" style="background:#f8fafd;border-radius:10px;border:1px solid #e3e8ee;padding:16px 18px 10px 18px;">
                <div style="font-weight:600;font-size:1.1em;margin-bottom:8px;color:#007bff;"><i class="fas fa-university"></i> <?= __t('api_manage_exchange_promo_title', '交-易-所及官方推荐码'); ?>（
                    <?= __t('api_manage_exchange_promo_subtitle', '直接下载APP在注册时填写免翻-QIANG'); ?><?php if (!$has_partner_referral): ?>（<a href="<?= htmlspecialchars(rtrim($download_url, '/') . '/down/sf.apk') ?>" target="_blank"><?= __t('api_manage_exchange_promo_verifier', '点击可下载身份验证器'); ?></a>）<?php endif; ?>
                ）</div>
                <div class="row">
                    <div class="col-md-6 col-12 mb-2">
                        <span style="font-weight:700;color:#fff;background:#007bff;padding:2px 10px;border-radius:6px;box-shadow:0 2px 8px #007bff44;letter-spacing:1px;" title="<?= __t('user_btn_binance_api_title', '全球最大的币-交-所，现货交易量最大'); ?>"><?= __t('user_exchange_binance_label', '币AN'); ?></span>
                        <a href="<?= htmlspecialchars(rtrim($download_url, '/') . '/down/ba.apk') ?>" target="_blank" class="badge badge-success" style="margin-left:8px;" title="<?= __t('user_exchange_binance_app_title', '币AN的安卓版本的APP下载地址'); ?>"><?= __t('user_exchange_binance_app', '下载APP'); ?></a>
                        <a href="https://down.ggai365.com/down/ba.apk" target="_blank" class="badge badge-warning" style="margin-left:8px;" title="<?= __t('user_exchange_binance_apk2_title', '币AN的备用下载地址'); ?>"><?= __t('user_exchange_binance_apk2', 'APK下载2'); ?></a>
                        <a href="<?= htmlspecialchars(rtrim($download_url, '/') . '/video_download.php?file=BACZ.mp4') ?>" target="_blank" class="badge badge-success" style="margin-left:8px;color:#fff;font-weight:bold;"><?= __t('user_exchange_binance_deposit', '币AN充值教程'); ?></a>
                        <a href="<?= htmlspecialchars(rtrim($download_url, '/') . '/video_download.php?file=BAHELP.mp4') ?>" target="_blank" class="badge badge-danger" style="margin-left:8px;color:#fff;font-weight:bold;" title="<?= __t('user_btn_binance_api_title', '全球最大的币-交-所，现货交易量最大'); ?>"><?= __t('user_exchange_binance_api', '币AN-API教程'); ?></a>
                        <span class="badge badge-light" style="background:#eef3fa;color:#007bff;font-size:0.98em;margin-left:8px;"><?= __t('user_exchange_promo_code', '推荐码：'); ?><?= htmlspecialchars($binance_referral_code ?: '1049279721') ?> <button type="button" class="btn btn-sm btn-outline-secondary" style="padding:2px 6px;font-size:0.8em;margin-left:4px;" onclick="copyToClipboard('<?= htmlspecialchars($binance_referral_code ?: '1049279721') ?>')" title="<?= __t('user_exchange_copy_promo_title', '复制推荐码'); ?>"><i class="fas fa-copy"></i></button><span style="margin-left:6px;color:#28a745;font-weight:600;"><?= htmlspecialchars(str_replace('{count}', (string)$binance_allow_api_count, __t('user_exchange_allow_bind_count', '可绑{count}个'))) ?></span></span>
                    </div>
                    <div class="col-md-6 col-12 mb-2">
                        <span style="font-weight:700;color:#fff;background:#007bff;padding:2px 10px;border-radius:6px;box-shadow:0 2px 8px #007bff44;letter-spacing:1px;" title="<?= __t('user_btn_okx_api_title', '全球第2大币-交-所，对于程序化交易最友好'); ?>"><?= __t('user_exchange_okx_label', 'OE'); ?></span>
                        <a href="<?= htmlspecialchars(rtrim($download_url, '/') . '/down/oe.apk') ?>" target="_blank" class="badge badge-success" style="margin-left:8px;" title="<?= __t('user_exchange_okx_app_title', 'OE的安卓版本的APP下载地址'); ?>"><?= __t('user_exchange_okx_app', '下载APP'); ?></a>
                        <a href="https://down.ggai365.com/down/oe.apk" target="_blank" class="badge badge-warning" style="margin-left:8px;" title="<?= __t('user_exchange_okx_apk2_title', 'OE的备用下载地址'); ?>"><?= __t('user_exchange_okx_apk2', 'APK下载2'); ?></a>
                        <a href="<?= htmlspecialchars(rtrim($download_url, '/') . '/video_download.php?file=OECZ.mp4') ?>" target="_blank" class="badge badge-success" style="margin-left:8px;color:#fff;font-weight:bold;"><?= __t('user_exchange_okx_deposit', '欧E充值教程'); ?></a>
                        <a href="<?= htmlspecialchars(rtrim($download_url, '/') . '/video_download.php?file=OEHELP.mp4') ?>" target="_blank" class="badge badge-danger" style="margin-left:8px;color:#fff;font-weight:bold;" title="<?= __t('user_btn_okx_api_title', '全球第2大币-交-所，对于程序化交易最友好'); ?>"><?= __t('user_exchange_okx_api', '欧E-API教程'); ?></a>
                        <span class="badge badge-light" style="background:#eef3fa;color:#007bff;font-size:0.98em;margin-left:8px;"><?= __t('user_exchange_promo_code', '推荐码：'); ?><?= htmlspecialchars($okx_referral_code ?: '31653225') ?> <button type="button" class="btn btn-sm btn-outline-secondary" style="padding:2px 6px;font-size:0.8em;margin-left:4px;" onclick="copyToClipboard('<?= htmlspecialchars($okx_referral_code ?: '31653225') ?>')" title="<?= __t('user_exchange_copy_promo_title', '复制推荐码'); ?>"><i class="fas fa-copy"></i></button><span style="margin-left:6px;color:#28a745;font-weight:600;"><?= htmlspecialchars(str_replace('{count}', (string)$okx_allow_api_count, __t('user_exchange_allow_bind_count', '可绑{count}个'))) ?></span></span>
                    </div>
                </div>
            </div>
            <div class="api-title" style="cursor:pointer;" onclick="window.location.href='<?= htmlspecialchars(ggai_mu('/user/add-api.php'), ENT_QUOTES, 'UTF-8') ?>'">
                <i class="fas fa-key"></i> <span style="text-decoration:underline;">API</span>
            </div>
            <div class="api-desc" style="color:#007bff;font-weight:bold;"><?= __t('api_manage_desc_main', '请填写您在交-易-所创建的API信息，审核通过后将用于自动化资产统计与交易。API信息一经审核通过不能修改，但允许修改相关参数。'); ?></div>
            <div class="api-desc" style="color:#dc3545;font-weight:bold;"><?php
                echo str_replace(
                    ['{unit}', '{unit2}', '{unit3}', '{n}', '{required}'],
                    [(string)$min_power_api, (string)($min_power_api * 2), (string)($min_power_api * 3), (string)$next_api_slot, (string)$required_power_api],
                    __t('api_manage_desc_tip1', '重要提示：在建立API之前，确保您已开通合约交易权限与双向交易权限；合约账户资金请保持与所选策略相适应的合理规模，否则易出现权限或资金不足。同时确保你的基础算力满足「{unit}U×API序号」（按基础算力检测，非实时算力）：绑定第1个需≥{unit}U，第2个需≥{unit2}U，第3个需≥{unit3}U，以此类推（当前为第{n}个，需≥{required}U）。还有很重要的一点，系统有全自动提现划转功能，开通API时要开通提现划转功能，这样当盈利达到一定程度后，可以自动将合约账户的资金自动转到现货账户。')
                );
            ?></div>
            <div class="api-desc" style="color:#dc3545;font-weight:bold;"><?= __t('api_manage_desc_tip2', '使用本站的工具软件，可以自定相关参数，无需写代码就可以全自动化运行，但注意需要开通2个API。交易API权限与「交易币种/品种」请尽量全部勾选（强烈建议全选），方便本站日后扩展新品种，否则旧API可能因缺权限无法交易新品种；不要选合约白名单。开通API时必须填写下面的IP白名单，否则无法正常运行'); ?></div>
            <div class="api-desc" style="color:#dc3545;font-weight:bold;"><?= __t('api_manage_desc_tip3', '只读API则很简单，只要开通只读这一项即可，开通后可以随时通过本站查询持仓，也可以自行随时平仓'); ?></div>
            <div class="api-desc" style="color:#dc3545;font-weight:bold;"><?= __t('api_manage_desc_tip4', '只有您选择的是默认的稳健型时，且账户资金在1500U以下，首月如果发生亏损，且排除不可抗力等黑天鹅事件外，系统公共池会按比例给予补贴，但不是保本。但如果自定义了参数或自行有平仓行为或是金额超过1500U后或是超过1个月后，系统将不再给予补贴。'); ?></div>
            <div class="api-desc" style="color:#dc3545;font-weight:bold;"><?= __t('api_manage_desc_tip5', '审核通过的API，如果亏损，系统的算力会自动增加，如果是盈利，会自动扣减，请注意算力余额足够，否则有行情易错过，如果账户开户时填了以上官方推荐人ID的，经确认后，手续费会直接在帐号中打4至8折不等，每笔不同'); ?></div>
            <?php if ($err): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($err); ?></div>
            <?php elseif ($msg): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($msg); ?></div>
                <?php if ($api): ?>
                <?php
                    // 获取交易所中文名并脱敏
                    $ex_name = '';
                    foreach ($exchanges as $ex) {
                        if ($ex['id'] == $api['exchange_id']) {
                            $ex_name = $ex['display_name'];
                            break;
                        }
                    }
                    // 脱敏处理
                    $ex_name = str_replace(['币安','BINANCE','币安链','BA','欧易','OKX'], ['币AN','BA','币AN链','BA','OE','OE'], $ex_name);
                ?>
                <div class="card mt-4">
                    <div class="card-header"><b>API订单信息</b></div>
                    <div class="card-body">
                        <div class="row mb-2">
                            <div class="col-md-6">
                                <b>交易所：</b><?php echo htmlspecialchars($ex_name ?: $api['exchange_id']); ?>
                            </div>
                            <div class="col-md-6">
                                <b>审核状态：</b>
                                <?php
                                    $statusMap = [
                                        'pending' => '待审核',
                                        'active' => '正常',
                                        'inactive' => '禁用',
                                        'rejected' => '已拒绝',
                                        'overdue' => '已欠费',
                                    ];
                                    echo $statusMap[$api['status']] ?? $api['status'];
                                ?>
                            </div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-6">
                                <b>只读API Key：</b><?php echo htmlspecialchars($api['read_key']); ?>
                            </div>
                            <div class="col-md-6">
                                <b>交易API Key：</b><?php echo htmlspecialchars($api['trade_key']); ?>
                            </div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-6">
                                <b>最新权益：</b><?php echo number_format($api['equity'], 2); ?> U
                            </div>
                            <div class="col-md-6">
                                <b>提交时间：</b><?php echo htmlspecialchars($api['created_at']); ?>
                            </div>
                        </div>
                        <?php if (!empty($api['audit_remark'])): ?>
                        <div class="row mb-2">
                            <div class="col-12">
                                <b>审核备注：</b><span class="text-danger"><?php echo htmlspecialchars($api['audit_remark']); ?></span>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            <?php endif; ?>
            <?php if ($audit_remark): ?>
                <div class="alert alert-warning">审核未通过：<?php echo htmlspecialchars($audit_remark); ?></div>
            <?php endif; ?>
                    </div>
                    </div>
                </div>

<script>
document.addEventListener('click', function(e){
    var t = e.target;
    if (t.classList && t.classList.contains('js-disable-api')) {
        var apiId = t.getAttribute('data-api-id');
        if (!apiId) return;
        if (!confirm('<?= __t('common_confirm_disable_api', '确定要禁用该API吗？禁用后将暂停使用。'); ?>')) return;
        t.disabled = true;
        fetch('/user/ajax/disable_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
            body: 'api_id=' + encodeURIComponent(apiId)
        }).then(function(r){ return r.json(); }).then(function(res){
            alert(res.message || (res.success ? '<?= __t('common_op_success', '操作成功'); ?>' : '<?= __t('common_op_failed', '操作失败'); ?>'));
            if (res.success) { location.reload(); }
        }).catch(function(){
            alert('<?= __t('common_request_failed', '请求失败，请稍后重试'); ?>');
        }).finally(function(){ t.disabled = false; });
    }
    if (t.classList && t.classList.contains('js-delete-api')) {
        var apiId2 = t.getAttribute('data-api-id');
        if (!apiId2) return;
        if (!confirm('<?= __t('common_confirm_delete_api', '确定要删除该API吗？此操作不可恢复！'); ?>')) return;
        t.disabled = true;
        fetch('/user/ajax/delete_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
            body: 'api_id=' + encodeURIComponent(apiId2)
        }).then(function(r){ return r.json(); }).then(function(res){
            alert(res.message || (res.success ? '<?= __t('common_delete_success', '删除成功'); ?>' : '<?= __t('common_delete_failed', '删除失败'); ?>'));
            if (res.success) { location.reload(); }
        }).catch(function(){
            alert('<?= __t('common_request_failed', '请求失败，请稍后重试'); ?>');
        }).finally(function(){ t.disabled = false; });
    }
});

// 复制到剪贴板函数
function copyToClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
        // 使用现代 Clipboard API
        navigator.clipboard.writeText(text).then(function() {
            showCopySuccess();
        }).catch(function(err) {
            console.error('复制失败:', err);
            fallbackCopyTextToClipboard(text);
        });
    } else {
        // 降级到传统方法
        fallbackCopyTextToClipboard(text);
    }
}

// 降级复制方法
function fallbackCopyTextToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.value = text;
    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    textArea.style.opacity = "0";
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        var successful = document.execCommand('copy');
        if (successful) {
            showCopySuccess();
        } else {
            showCopyError();
        }
    } catch (err) {
        console.error('降级复制失败:', err);
        showCopyError();
    }
    
    document.body.removeChild(textArea);
}

// 显示复制成功提示
function showCopySuccess() {
    // 创建临时提示元素
    var toast = document.createElement('div');
    toast.innerHTML = '<i class="fas fa-check"></i> <?= __t('user_referral_copied', '推荐码已复制到剪贴板'); ?>';
    toast.style.cssText = 'position:fixed;top:20px;right:20px;background:#28a745;color:white;padding:10px 15px;border-radius:5px;z-index:9999;font-size:14px;box-shadow:0 2px 10px rgba(0,0,0,0.3);';
    document.body.appendChild(toast);
    
    // 2秒后移除提示
    setTimeout(function() {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 2000);
}

// 显示复制失败提示
function showCopyError() {
    var toast = document.createElement('div');
    toast.innerHTML = '<i class="fas fa-exclamation-triangle"></i> <?= __t('common_copy_failed', '复制失败，请手动复制'); ?>';
    toast.style.cssText = 'position:fixed;top:20px;right:20px;background:#dc3545;color:white;padding:10px 15px;border-radius:5px;z-index:9999;font-size:14px;box-shadow:0 2px 10px rgba(0,0,0,0.3);';
    document.body.appendChild(toast);
    
    setTimeout(function() {
        if (toast.parentNode) {
            toast.parentNode.removeChild(toast);
        }
    }, 3000);
}

(function() {
    var storageKey = 'api_manage_cp_modified_only';
    var checkbox = document.getElementById('apiCpModifiedOnly');
    if (!checkbox) {
        return;
    }

    function readPreference() {
        return localStorage.getItem(storageKey) === '1';
    }

    function writePreference(enabled) {
        localStorage.setItem(storageKey, enabled ? '1' : '0');
    }

    function refreshCommas(summary) {
        var firstVisible = true;
        summary.querySelectorAll('.api-cp-item').forEach(function(item) {
            if (item.classList.contains('api-cp-item-hidden')) {
                return;
            }
            var comma = item.querySelector('.api-cp-comma');
            if (!comma) {
                return;
            }
            comma.style.display = firstVisible ? 'none' : '';
            firstVisible = false;
        });
    }

    function applyCustomParamFilter() {
        var modifiedOnly = checkbox.checked;
        var bar = document.getElementById('apiCpFilterBar');
        if (bar) {
            bar.classList.toggle('is-active', modifiedOnly);
        }
        document.querySelectorAll('.api-cp-summary').forEach(function(summary) {
            summary.querySelectorAll('.api-cp-item').forEach(function(item) {
                var alwaysVisible = item.getAttribute('data-cp-always') === '1';
                var modified = item.getAttribute('data-cp-modified') === '1';
                var show = !modifiedOnly || alwaysVisible || modified;
                item.classList.toggle('api-cp-item-hidden', !show);
            });
            refreshCommas(summary);
        });
    }

    checkbox.checked = readPreference();
    checkbox.addEventListener('change', function() {
        writePreference(checkbox.checked);
        applyCustomParamFilter();
    });
    applyCustomParamFilter();
})();
</script>

<?php
$pageContent = ob_get_clean();
require_once 'includes/layout.php'; 