<?php
require_once 'config/config.php';
require_once 'config/database.php';
require_once 'config/functions.php';
require_once 'config/encryption.php';
require_once 'config/session.php';
require_once 'config/logger.php';
require_once 'config/auth.php';

// 需要登录才能访问
requireLogin();

$page_title = '账户充值';
$db = Database::getInstance();
$session = Session::getInstance();
$user_id = $session->getUserId();

// 获取钱包地址
$addresses = [
    'usdt_trc20' => '',
    'usdt_erc20' => ''
];

try {
    $stmt = $db->prepare("SELECT setting_key, setting_value FROM system_settings WHERE setting_key IN ('usdt_trc20_address', 'usdt_erc20_address')");
    if ($stmt && $stmt->execute()) {
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            if ($row['setting_key'] === 'usdt_trc20_address') {
                $addresses['usdt_trc20'] = $row['setting_value'];
            } elseif ($row['setting_key'] === 'usdt_erc20_address') {
                $addresses['usdt_erc20'] = $row['setting_value'];
            }
        }
    }
} catch (Exception $e) {
    error_log("获取钱包地址失败: " . $e->getMessage());
}

// 获取充值记录
try {
    // 撤回/拒绝的 failed 记录只给后台审计和防重复使用，前台不展示
    $stmt = $db->prepare("SELECT * FROM recharge_orders WHERE user_id = ? AND status <> 'failed' ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
    $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
} catch (Exception $e) {
    error_log("获取充值记录失败: " . $e->getMessage());
    $records = [];  // 如果出错，使用空数组
}

include 'templates/header.php';
?>

<style>
/* 移动端导航栏按钮样式 */
@media (max-width: 768px) {
    .mobile-menu-btn {
        position: fixed !important;
        top: 20px !important;
        left: 20px !important;
        z-index: 10001 !important;
        background: rgba(0, 234, 255, 0.2) !important;
        border: 3px solid #00eaff !important;
        border-radius: 50% !important;
        width: 70px !important;
        height: 70px !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
        font-size: 28px !important;
        color: #00eaff !important;
        box-shadow: 0 8px 25px rgba(0, 234, 255, 0.4) !important;
        backdrop-filter: blur(15px) !important;
        transition: all 0.3s ease !important;
        cursor: pointer !important;
        user-select: none !important;
        touch-action: none !important;
    }
    
    .mobile-menu-btn:hover {
        background: rgba(0, 234, 255, 0.3) !important;
        transform: scale(1.05) !important;
        box-shadow: 0 12px 30px rgba(0, 234, 255, 0.6) !important;
    }
    
    .mobile-menu-btn:active {
        transform: scale(0.95) !important;
    }
    
    /* 拖拽状态样式 */
    .mobile-menu-btn.dragging {
        transform: scale(1.1) !important;
        box-shadow: 0 15px 35px rgba(0, 234, 255, 0.8) !important;
        background: rgba(0, 234, 255, 0.4) !important;
        cursor: grabbing !important;
    }
    
    /* 移动端内容区域调整 */
    .container-fluid {
        padding-top: 100px !important;
    }
    
    /* 移动端表格优化 */
    .table-responsive {
        font-size: 0.8em;
    }
    
    .table th, .table td {
        padding: 0.3rem;
    }
    
    /* 移动端备用导航栏显示 */
    .mobile-backup-nav {
        display: block !important;
    }
    
    /* 移动端备用导航栏样式 */
    .mobile-backup-nav .navbar {
        background: linear-gradient(45deg, #007bff, #0056b3) !important;
        box-shadow: 0 2px 10px rgba(0, 123, 255, 0.3) !important;
    }
    
    .mobile-backup-nav .navbar-brand {
        font-weight: bold !important;
        color: #fff !important;
    }
    
    .mobile-backup-nav .nav-link {
        color: rgba(255, 255, 255, 0.9) !important;
        padding: 0.5rem 1rem !important;
        border-radius: 5px !important;
        margin: 0.2rem 0 !important;
        transition: all 0.3s ease !important;
    }
    
    .mobile-backup-nav .nav-link:hover {
        background: rgba(255, 255, 255, 0.1) !important;
        color: #fff !important;
        transform: translateX(5px) !important;
    }
    
    .mobile-backup-nav .navbar-toggler {
        border-color: rgba(255, 255, 255, 0.3) !important;
    }
    
    .mobile-backup-nav .navbar-toggler-icon {
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.8%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") !important;
    }
}
</style>

<div class="container-fluid">
    <!-- 移动端备用导航栏 -->
    <div class="mobile-backup-nav" style="display: none;">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-3">
                        <div class="container-fluid">
                            <a class="navbar-brand" href="index.php">
                                <i class="fas fa-home"></i> 返回首页
                            </a>
                            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mobileNav">
                                <span class="navbar-toggler-icon"></span>
                            </button>
                            <div class="collapse navbar-collapse" id="mobileNav">
                                <ul class="navbar-nav me-auto">
                                    <li class="nav-item">
                                        <a class="nav-link" href="index.php">
                                            <i class="fas fa-home"></i> 首页
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="positions.php">
                                            <i class="fas fa-chart-line"></i> 持仓
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="profits.php">
                                            <i class="fas fa-coins"></i> 收益
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="profile.php">
                                            <i class="fas fa-user"></i> 个人中心
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a class="nav-link" href="logout.php">
                                            <i class="fas fa-sign-out-alt"></i> 退出
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <!-- 左侧导航 -->
        <div class="col-md-2">
            <?php include 'templates/sidebar.php'; ?>
        </div>
        
        <!-- 主内容区 -->
        <div class="col-md-10">
            <h2 class="mb-4">账户充值</h2>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">USDT-TRC20充值</h5>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($addresses['usdt_trc20'])): ?>
                            <div class="mb-3">
                                <label class="form-label">TRC20钱包地址</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" 
                                           value="<?php echo htmlspecialchars($addresses['usdt_trc20']); ?>" 
                                           readonly>
                                    <button class="btn btn-outline-secondary" type="button" 
                                            onclick="copyToClipboard(this, '<?php echo htmlspecialchars($addresses['usdt_trc20']); ?>')">
                                        复制
                                    </button>
                                </div>
                            </div>
                            <div class="alert alert-info">
                                <i class="fa fa-info-circle"></i> 请使用USDT-TRC20转账到以上地址
                            </div>
                            <?php else: ?>
                            <div class="alert alert-warning">
                                <i class="fa fa-exclamation-triangle"></i> TRC20充值地址未设置，请联系客服
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">USDT-ERC20充值</h5>
                        </div>
                        <div class="card-body">
                            <?php if (!empty($addresses['usdt_erc20'])): ?>
                            <div class="mb-3">
                                <label class="form-label">ERC20钱包地址</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" 
                                           value="<?php echo htmlspecialchars($addresses['usdt_erc20']); ?>" 
                                           readonly>
                                    <button class="btn btn-outline-secondary" type="button" 
                                            onclick="copyToClipboard(this, '<?php echo htmlspecialchars($addresses['usdt_erc20']); ?>')">
                                        复制
                                    </button>
                                </div>
                            </div>
                            <div class="alert alert-info">
                                <i class="fa fa-info-circle"></i> 请使用USDT-ERC20转账到以上地址
                            </div>
                            <?php else: ?>
                            <div class="alert alert-warning">
                                <i class="fa fa-exclamation-triangle"></i> ERC20充值地址未设置，请联系客服
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">提交充值</h5>
                        </div>
                        <div class="card-body">
                            <form method="post" action="recharge_submit.php" id="rechargeForm">
                                <div class="mb-3">
                                    <label class="form-label">选择充值金额</label>
                                    <div class="row g-3">
                                        <?php
                                        $amounts = [50, 100, 200, 500, 1000, 5000, 10000, 50000, 100000];
                                        foreach ($amounts as $amt): 
                                        ?>
                                        <div class="col-md-4">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" 
                                                       name="amount_option" value="<?php echo $amt; ?>" 
                                                       id="amount_<?php echo $amt; ?>">
                                                <label class="form-check-label" for="amount_<?php echo $amt; ?>">
                                                    <?php echo number_format($amt); ?> USDT
                                                </label>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                        <div class="col-md-4">
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" 
                                                       name="amount_option" value="custom" 
                                                       id="amount_custom">
                                                <label class="form-check-label" for="amount_custom">
                                                    自定义金额
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mb-3" id="customAmountDiv" style="display: none;">
                                    <label class="form-label">自定义金额</label>
                                    <div class="input-group">
                                        <input type="number" id="customAmount" class="form-control" 
                                               min="<?php echo $config['recharge']['min_amount']; ?>" 
                                               max="<?php echo $config['recharge']['max_amount']; ?>" 
                                               step="0.01">
                                        <span class="input-group-text">USDT</span>
                                    </div>
                                </div>
                                
                                <!-- 添加隐藏的金额字段 -->
                                <input type="hidden" name="amount" id="finalAmount">
                                <input type="hidden" name="actual_amount" id="actualAmount">
                                
                                <div class="alert alert-info" id="amountNotice" style="display: none;">
                                    <i class="fa fa-info-circle"></i> 
                                    <span id="amountMessage"></span>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">充值网络</label>
                                    <select name="type" class="form-select" required>
                                        <option value="TRC20">USDT-TRC20</option>
                                        <option value="ERC20">USDT-ERC20</option>
                                    </select>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">交易哈希</label>
                                    <input type="text" name="tx_hash" class="form-control" required>
                                    <div class="form-text">请输入转账成功后的交易哈希（TXID）</div>
                                </div>
                                
                                <button type="submit" class="btn btn-primary" id="submitBtn" disabled>提交充值</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="card-title mb-0">充值说明</h5>
                </div>
                <div class="card-body">
                    <ul class="mb-0">
                        <li>最小充值金额：<?php echo $config['recharge']['min_amount']; ?> USDT</li>
                        <li>TRC20网络手续费：<?php echo $config['recharge']['fee']['TRC20']; ?> USDT</li>
                        <li>ERC20网络手续费：<?php echo $config['recharge']['fee']['ERC20']; ?> USDT</li>
                        <li>请务必使用正确的网络进行转账，否则可能导致资金丢失</li>
                        <li>充值到账时间：TRC20约5-15分钟，ERC20约10-30分钟</li>
                        <li>如有问题请联系客服</li>
                    </ul>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title mb-0">充值记录</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($records)): ?>
                    <div class="text-center py-3">
                        <p class="text-muted">暂无充值记录</p>
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>意向金额</th>
                                    <th>实际金额</th>
                                    <th>充值方式</th>
                                    <th>状态</th>
                                    <th>时间</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($records as $record): ?>
                                <tr>
                                    <td><?php echo number_format($record['amount'], 2); ?> USDT</td>
                                    <td><?php echo number_format($record['actual_amount'], 2); ?> USDT</td>
                                    <td><?php echo $record['type']; ?></td>
                                    <td>
                                        <span class="badge bg-<?php 
                                            echo $record['status'] === 'completed' ? 'success' : 
                                                ($record['status'] === 'rejected' ? 'danger' : 'warning'); 
                                        ?>">
                                            <?php 
                                            echo $record['status'] === 'completed' ? '已完成' : 
                                                ($record['status'] === 'rejected' ? '已拒绝' : '处理中'); 
                                            ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('Y-m-d H:i:s', strtotime($record['created_at'])); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let deduction = 0;

function generateDeduction() {
    // 生成0-0.2之间的随机数，保留2位小数
    return Math.round(Math.random() * 20) / 100;
}

function updateAmount(value) {
    const customAmountInput = document.getElementById('customAmount');
    const amountNotice = document.getElementById('amountNotice');
    const amountMessage = document.getElementById('amountMessage');
    const submitBtn = document.getElementById('submitBtn');
    const finalAmount = document.getElementById('finalAmount');
    const actualAmount = document.getElementById('actualAmount');
    
    let amount;
    
    // 如果是自定义金额，使用输入框的值
    if (value === 'custom') {
        if (!customAmountInput.value) {
            amountNotice.style.display = 'none';
            submitBtn.disabled = true;
            return;
        }
        amount = parseFloat(customAmountInput.value);
    } else {
        // 直接使用预设金额
        amount = parseFloat(value);
    }
    
    // 验证金额
    if (isNaN(amount) || amount < <?php echo $config['recharge']['min_amount']; ?> || 
        amount > <?php echo $config['recharge']['max_amount']; ?>) {
        amountNotice.style.display = 'none';
        submitBtn.disabled = true;
        return;
    }
    
    // 生成新的扣除金额
    deduction = generateDeduction();
    const actualAmt = parseFloat((amount - deduction).toFixed(2)); // 确保精确到2位小数
    
    // 更新显示，修改提示文本
    amountMessage.textContent = `意向转账 ${amount.toFixed(2)} USDT，请实际按此金额转账 ${actualAmt.toFixed(2)} USDT（系统扣除 ${deduction.toFixed(2)} USDT）`;
    amountNotice.style.display = 'block';
    submitBtn.disabled = false;
    
    // 更新表单值
    finalAmount.value = amount.toFixed(2);
    actualAmount.value = actualAmt.toFixed(2);
}

function enableCustomAmount() {
    const customAmountDiv = document.getElementById('customAmountDiv');
    const customAmount = document.getElementById('customAmount');
    const amountNotice = document.getElementById('amountNotice');
    const submitBtn = document.getElementById('submitBtn');
    
    customAmountDiv.style.display = 'block';
    customAmount.required = true;
    customAmount.value = ''; // 清空输入框
    customAmount.focus();
    
    // 清除提示和禁用提交按钮
    amountNotice.style.display = 'none';
    submitBtn.disabled = true;
}

// 监听所有单选按钮的变化
document.querySelectorAll('input[name="amount_option"]').forEach(radio => {
    radio.addEventListener('change', function() {
        if (this.value === 'custom') {
            enableCustomAmount();
        } else {
            updateAmount(this.value);
        }
    });
});

// 表单提交前验证
document.getElementById('rechargeForm').onsubmit = function(e) {
    const finalAmount = document.getElementById('finalAmount');
    const actualAmount = document.getElementById('actualAmount');
    
    if (!finalAmount.value || !actualAmount.value) {
        e.preventDefault();
        alert('请选择或输入充值金额');
        return false;
    }
    
    // 验证扣除金额是否在有效范围内
    const amount = parseFloat(finalAmount.value);
    const actualAmt = parseFloat(actualAmount.value);
    const deduction = amount - actualAmt;
    
    if (deduction < 0 || deduction > 0.2 || isNaN(deduction)) {
        e.preventDefault();
        alert('充值金额计算错误，请重新选择金额');
        return false;
    }
    
    // 确认提交
    if (!confirm(`确认提交充值申请？\n意向金额：${amount.toFixed(2)} USDT\n实际金额：${actualAmt.toFixed(2)} USDT`)) {
        e.preventDefault();
        return false;
    }
    
    return true;
};

function copyToClipboard(button, text) {
    navigator.clipboard.writeText(text).then(function() {
        const originalText = button.innerHTML;
        button.innerHTML = '已复制';
        button.disabled = true;
        setTimeout(function() {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 2000);
    }).catch(function(err) {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
    });
}
</script>

<!-- 移动端导航栏按钮 -->
<div class="mobile-menu-btn" id="mobileMenuBtn" style="display: none;">
    <i class="fas fa-bars"></i>
</div>

<script>
// 移动端导航栏按钮功能
document.addEventListener('DOMContentLoaded', function() {
    const mobileBtn = document.getElementById('mobileMenuBtn');
    const backupNav = document.querySelector('.mobile-backup-nav');
    const isMobile = window.innerWidth <= 768;
    
    if (isMobile) {
        // 显示备用导航栏
        if (backupNav) {
            backupNav.style.display = 'block';
        }
        
        // 显示悬浮按钮（如果存在）
        if (mobileBtn) {
            mobileBtn.style.display = 'flex';
        }
        
        // 点击事件 - 打开侧边栏
        mobileBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // 尝试找到侧边栏切换按钮
            const sidebarToggle = document.querySelector('#sidebarToggle, button#sidebarToggle, .sidebar #sidebarToggle');
            if (sidebarToggle) {
                sidebarToggle.click();
            } else {
                // 如果没有找到侧边栏，显示提示
                alert('导航菜单功能暂不可用，请使用页面顶部的导航链接');
            }
        });
        
        // 触摸事件支持
        mobileBtn.addEventListener('touchend', function(e) {
            e.preventDefault();
            e.stopPropagation();
            mobileBtn.click();
        }, {passive: false});
        
        // 拖拽功能
        let isDragMode = false;
        let dragStartX = 0;
        let dragStartY = 0;
        
        mobileBtn.addEventListener('mousedown', function(e) {
            isDragMode = true;
            dragStartX = e.clientX;
            dragStartY = e.clientY;
            mobileBtn.classList.add('dragging');
        });
        
        mobileBtn.addEventListener('touchstart', function(e) {
            isDragMode = true;
            dragStartX = e.touches[0].clientX;
            dragStartY = e.touches[0].clientY;
            mobileBtn.classList.add('dragging');
        }, {passive: false});
        
        document.addEventListener('mousemove', function(e) {
            if (isDragMode) {
                const deltaX = e.clientX - dragStartX;
                const deltaY = e.clientY - dragStartY;
                mobileBtn.style.left = (20 + deltaX) + 'px';
                mobileBtn.style.top = (20 + deltaY) + 'px';
            }
        });
        
        document.addEventListener('touchmove', function(e) {
            if (isDragMode) {
                e.preventDefault();
                const deltaX = e.touches[0].clientX - dragStartX;
                const deltaY = e.touches[0].clientY - dragStartY;
                mobileBtn.style.left = (20 + deltaX) + 'px';
                mobileBtn.style.top = (20 + deltaY) + 'px';
            }
        }, {passive: false});
        
        document.addEventListener('mouseup', function(e) {
            if (isDragMode) {
                mobileBtn.classList.remove('dragging');
                // 保存位置到本地存储
                localStorage.setItem('mobileMenuBtnPosition', JSON.stringify({
                    left: mobileBtn.style.left,
                    top: mobileBtn.style.top
                }));
            }
            isDragMode = false;
        });
        
        document.addEventListener('touchend', function(e) {
            if (isDragMode) {
                mobileBtn.classList.remove('dragging');
                localStorage.setItem('mobileMenuBtnPosition', JSON.stringify({
                    left: mobileBtn.style.left,
                    top: mobileBtn.style.top
                }));
            }
            isDragMode = false;
        });
        
        // 恢复保存的位置
        function restorePosition() {
            const savedPosition = localStorage.getItem('mobileMenuBtnPosition');
            if (savedPosition) {
                try {
                    const position = JSON.parse(savedPosition);
                    mobileBtn.style.left = position.left;
                    mobileBtn.style.top = position.top;
                } catch (e) {
                    console.log('恢复位置失败');
                }
            }
        }
        
        // 页面加载时恢复位置
        restorePosition();
    }
    
    // 窗口大小改变时重新检测
    window.addEventListener('resize', function() {
        const newIsMobile = window.innerWidth <= 768;
        if (newIsMobile !== isMobile) {
            location.reload(); // 重新加载页面以应用正确的样式
        }
    });
});
</script>

<?php include 'templates/footer.php'; ?> 