<?php
session_start();
include 'header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

require_once 'db/config.php';
$db = db();
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

$kyc_status = $user['kyc_status'] ?? 0;
$kyc_labels = [
    0 => __('kyc_none', '未认证'),
    1 => __('kyc_pending', '审核中'),
    2 => __('kyc_approved', '已认证'),
    3 => __('kyc_rejected', '未通过'),
];
$kyc_colors = [0 => '#888', 1 => '#f0b90b', 2 => 'var(--success-color)', 3 => 'var(--danger-color)'];
?>

<style>
    .profile-tabs { display: flex; gap: 30px; border-bottom: 1px solid var(--border-color); margin-bottom: 25px; overflow-x: auto; white-space: nowrap; }
    .profile-tab-btn { background: none; border: none; color: var(--text-muted); padding: 10px 0; font-size: 1rem; font-weight: 600; cursor: pointer; border-bottom: 2px solid transparent; }
    .profile-tab-btn.active { color: white; border-bottom-color: var(--primary-color); }
    .record-item { padding: 15px; background: rgba(255,255,255,0.02); border-radius: 12px; border: 1px solid var(--border-color); margin-bottom: 10px; }
    
    .profile-grid { display: grid; grid-template-columns: 350px 1fr; gap: 30px; }
    .balance-amount { font-size: 3rem; font-weight: bold; letter-spacing: -1px; color: white; line-height: 1.2; }
    
    @media (max-width: 992px) {
        .profile-grid { grid-template-columns: 1fr; gap: 20px; }
        .balance-amount { font-size: 2.2rem; }
        .profile-header-actions { flex-direction: column; gap: 10px !important; width: 100%; }
        .profile-header-actions a { width: 100%; justify-content: center; }
        .profile-main-card { padding: 25px !important; border-radius: 16px !important; }
    }
</style>

<main style="padding: 20px 0; background: #0b0e11; min-height: 100vh;">
    <div class="container">
        
        <div style="margin-bottom: 20px;">
            <a href="index.php" class="back-btn" style="margin: 0;"><i class="fas fa-arrow-left"></i> <?php echo __('nav_home'); ?></a>
        </div>

        <div class="profile-grid">
            <!-- Left Panel -->
            <div class="profile-sidebar-panel">
                <div style="background: var(--card-bg); padding: 30px; border-radius: 20px; border: 1px solid var(--border-color); text-align: center;">
                    <div style="width: 80px; height: 80px; background: linear-gradient(135deg, #4facfe, #00f2fe); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px; font-size: 2rem; font-weight: bold; color: white; box-shadow: 0 10px 20px rgba(79,172,254,0.2);">
                        <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                    </div>
                    <h2 style="margin-bottom: 5px; color: white; font-size: 1.5rem;"><?php echo $user['username']; ?></h2>
                    <div style="background: rgba(255,255,255,0.05); display: inline-block; padding: 4px 12px; border-radius: 20px; color: var(--text-muted); font-size: 0.8rem; margin-bottom: 20px;">UID: <?php echo $user['uid'] ?: '618120'; ?></div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; padding-top: 20px; border-top: 1px solid var(--border-color);">
                        <div>
                            <div style="color: var(--text-muted); font-size: 0.75rem; margin-bottom: 3px;"><?php echo __('credit_score', '信用分'); ?></div>
                            <div style="font-weight: bold; font-size: 1.1rem; color: var(--success-color);"><?php echo $user['credit_score'] ?? 100; ?></div>
                        </div>
                        <div style="border-left: 1px solid var(--border-color);">
                            <div style="color: var(--text-muted); font-size: 0.75rem; margin-bottom: 3px;"><?php echo __('level', '等级'); ?></div>
                            <div style="font-weight: bold; font-size: 1.1rem; color: #f0b90b;">VIP 0</div>
                        </div>
                    </div>
                </div>

                <div style="margin-top: 20px; display: flex; flex-direction: column; gap: 12px;">
                    <div style="background: var(--card-bg); padding: 18px; border-radius: 16px; border: 1px solid var(--border-color);">
                        <a href="kyc.php" style="display: flex; align-items: center; justify-content: space-between; text-decoration: none; color: white;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div style="width: 36px; height: 36px; background: rgba(79,172,254,0.1); border-radius: 8px; display: flex; align-items: center; justify-content: center; color: var(--primary-color);">
                                    <i class="fas fa-id-card"></i>
                                </div>
                                <span style="font-weight: 500; font-size: 0.95rem;"><?php echo __('kyc_status'); ?></span>
                            </div>
                            <span style="font-size: 0.8rem; font-weight: bold; color: <?php echo $kyc_colors[$kyc_status]; ?>"><?php echo $kyc_labels[$kyc_status]; ?> <i class="fas fa-chevron-right" style="margin-left: 5px; font-size: 10px;"></i></span>
                        </a>
                    </div>

                    <div style="background: var(--card-bg); padding: 18px; border-radius: 16px; border: 1px solid var(--border-color);">
                        <a href="security.php" style="display: flex; align-items: center; justify-content: space-between; text-decoration: none; color: white;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <div style="width: 36px; height: 36px; background: rgba(14,203,129,0.1); border-radius: 8px; display: flex; align-items: center; justify-content: center; color: var(--success-color);">
                                    <i class="fas fa-shield-alt"></i>
                                </div>
                                <span style="font-weight: 500; font-size: 0.95rem;"><?php echo __('security_settings'); ?></span>
                            </div>
                            <i class="fas fa-chevron-right" style="color: var(--text-muted); font-size: 10px;"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Right Panel -->
            <div class="profile-main-card" style="background: var(--card-bg); padding: 40px; border-radius: 24px; border: 1px solid var(--border-color);">
                <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 35px; flex-wrap: wrap; gap: 20px;">
                    <div>
                        <div style="color: var(--text-muted); margin-bottom: 8px; font-size: 13px;"><?php echo __('total_balance'); ?> (USDT)</div>
                        <div class="balance-amount">
                            <?php echo number_format($user['balance'] ?? 0, 2); ?>
                        </div>
                        <div style="color: var(--text-muted); font-size: 0.9rem; margin-top: 5px;">≈ $ <?php echo number_format($user['balance'] ?? 0, 2); ?></div>
                    </div>
                    <div class="profile-header-actions" style="display: flex; gap: 12px;">
                        <a href="deposit.php" class="btn-primary" style="padding: 10px 25px; border-radius: 8px; font-weight: bold; font-size: 0.9rem;"><i class="fas fa-arrow-down" style="margin-right: 8px;"></i> <?php echo __('nav_deposit'); ?></a>
                        <a href="withdraw.php" class="btn-primary" style="background: #2b3139; padding: 10px 25px; border-radius: 8px; font-weight: bold; font-size: 0.9rem;"><i class="fas fa-arrow-up" style="margin-right: 8px;"></i> <?php echo __('nav_withdraw'); ?></a>
                    </div>
                </div>

                <div class="profile-tabs">
                    <button class="profile-tab-btn active" onclick="switchProfileTab(this, 'assets-tab')"><?php echo __('asset_details'); ?></button>
                    <button class="profile-tab-btn" onclick="switchProfileTab(this, 'records-tab')"><?php echo __('transaction_records'); ?></button>
                </div>

                <!-- Assets Tab -->
                <div id="assets-tab" class="tab-content">
                    <div style="display: flex; flex-direction: column; gap: 10px;">
                        <?php
                        $coins = [
                            ['symbol' => 'USDT', 'name' => 'Tether', 'balance' => $user['balance'] ?? 0, 'price' => 1.00],
                            ['symbol' => 'BTC', 'name' => 'Bitcoin', 'balance' => 0.0000, 'price' => 0],
                            ['symbol' => 'ETH', 'name' => 'Ethereum', 'balance' => 0.0000, 'price' => 0],
                            ['symbol' => 'SOL', 'name' => 'Solana', 'balance' => 0.0000, 'price' => 0],
                            ['symbol' => 'BNB', 'name' => 'Binance Coin', 'balance' => 0.0000, 'price' => 0],
                        ];
                        // Fetch real user assets if table exists
                        try {
                            $asset_stmt = $db->prepare("SELECT * FROM user_assets WHERE user_id = ?");
                            $asset_stmt->execute([$_SESSION['user_id']]);
                            $db_assets = $asset_stmt->fetchAll();
                            foreach ($db_assets as $da) {
                                $found = false;
                                foreach ($coins as &$c) {
                                    if ($c['symbol'] === $da['symbol']) {
                                        $c['balance'] = $da['amount'];
                                        $found = true;
                                    }
                                }
                                if (!$found) {
                                    $coins[] = ['symbol' => $da['symbol'], 'name' => '', 'balance' => $da['amount'], 'price' => 0];
                                }
                            }
                        } catch (Exception $e) {}

                        foreach ($coins as $coin):
                        ?>
                        <div style="display: flex; align-items: center; justify-content: space-between; padding: 15px; background: rgba(255,255,255,0.02); border-radius: 14px; border: 1px solid transparent;">
                            <div style="display: flex; align-items: center; gap: 12px;">
                                <img src="https://raw.githubusercontent.com/spothq/cryptocurrency-icons/master/128/color/<?php echo strtolower($coin['symbol']); ?>.png" width="32" height="32" onerror="this.src='https://cdn-icons-png.flaticon.com/512/2585/2585274.png'">
                                <div>
                                    <div style="font-weight: bold; font-size: 1rem; color: white;"><?php echo $coin['symbol']; ?></div>
                                    <div style="font-size: 0.75rem; color: var(--text-muted);"><?php echo $coin['name']; ?></div>
                                </div>
                            </div>
                            <div style="text-align: right;">
                                <div style="font-weight: bold; font-family: monospace; font-size: 1rem; color: white;"><?php echo number_format($coin['balance'], $coin['symbol'] === 'USDT' ? 2 : 6); ?></div>
                                <div style="font-size: 0.75rem; color: var(--text-muted);">USDT</div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Records Tab -->
                <div id="records-tab" class="tab-content" style="display: none;">
                    <div id="records-list">
                        <div style="text-align: center; padding: 40px; color: var(--text-muted);">加载中...</div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</main>

<script>
    function switchProfileTab(btn, tabId) {
        document.querySelectorAll('.profile-tab-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        document.querySelectorAll('.tab-content').forEach(c => c.style.display = 'none');
        document.getElementById(tabId).style.display = 'block';
        if (tabId === 'records-tab') {
            loadTransactionRecords();
        }
    }

    async function loadTransactionRecords() {
        const container = document.getElementById('records-list');
        try {
            const [spotResp, futuresResp] = await Promise.all([
                fetch('api/get_orders.php?type=spot&status=history'),
                fetch('api/get_orders.php?type=futures&status=history')
            ]);
            const spotRes = await spotResp.json();
            const futuresRes = await futuresResp.json();

            let allRecords = [];
            if (spotRes.success) {
                spotRes.data.forEach(r => { r.trade_type = '现货'; allRecords.push(r); });
            }
            if (futuresRes.success) {
                futuresRes.data.forEach(r => { r.trade_type = '合约'; allRecords.push(r); });
            }

            allRecords.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));

            if (allRecords.length === 0) {
                container.innerHTML = '<div style="text-align: center; padding: 40px; color: var(--text-muted);">暂无交易记录</div>';
                return;
            }

            let html = '';
            allRecords.forEach(r => {
                const isProfit = parseFloat(r.profit) > 0;
                const profitText = r.profit ? (isProfit ? '+' : '') + parseFloat(r.profit).toFixed(2) : '0.00';
                const profitColor = isProfit ? 'var(--success-color)' : (parseFloat(r.profit) < 0 ? 'var(--danger-color)' : 'var(--text-muted)');
                
                html += `
                    <div class="record-item">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                            <span style="font-weight: bold; color: white;">${r.symbol} <span style="font-size: 10px; background: rgba(255,255,255,0.1); padding: 1px 4px; border-radius: 4px; margin-left: 5px;">${r.trade_type}</span></span>
                            <span style="color: var(--text-muted); font-size: 11px;">${r.created_at}</span>
                        </div>
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div style="font-size: 12px;">
                                <span style="color: ${r.side === 'buy' ? 'var(--success-color)' : 'var(--danger-color)'}">${r.side === 'buy' ? '买入' : '卖出'}</span>
                                <span style="color: var(--text-muted); margin-left: 8px;">价格: ${parseFloat(r.price).toLocaleString()}</span>
                                <span style="color: var(--text-muted); margin-left: 8px;">数量: ${parseFloat(r.amount).toFixed(4)}</span>
                            </div>
                            <div style="text-align: right;">
                                <div style="font-size: 10px; color: var(--text-muted);">盈亏</div>
                                <div style="font-weight: bold; color: ${profitColor}; font-size: 12px;">${profitText} USDT</div>
                            </div>
                        </div>
                    </div>
                `;
            });
            container.innerHTML = html;
        } catch (e) {
            container.innerHTML = '<div style="text-align: center; padding: 40px; color: var(--danger-color);">加载失败</div>';
        }
    }
</script>

<?php include 'footer.php'; ?>