<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: /auth/login.php');
    exit;
}

include __DIR__ . '/includes/header.php';

// $user is already fetched in header.php, but we can re-fetch or use it.
if (!$user) {
    header('Location: /auth/login.php');
    exit;
}

// Get user data again to ensure we have latest fields
$stmt = db()->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user['id']]);
$userData = $stmt->fetch();

// Get balances
$stmt = db()->prepare("SELECT * FROM user_balances WHERE user_id = ?");
$stmt->execute([$user['id']]);
$userBalances = $stmt->fetchAll();
$balancesBySymbol = [];
foreach ($userBalances as $ub) {
    $balancesBySymbol[$ub['symbol']] = $ub;
}

// Calculate total balance in USDT
$totalBalanceUsdt = 0;
foreach ($userBalances as $ub) {
    $totalBalanceUsdt += ($ub['available'] + $ub['frozen']) * getCoinPrice($ub['symbol']);
}

$displayCoins = ['BTC', 'ETH', 'USDT', 'LTC', 'BNB', 'SOL', 'TRX', 'XRP'];
$balances = [];
foreach ($displayCoins as $symbol) {
    $balances[] = [
        'symbol' => $symbol,
        'available' => $balancesBySymbol[$symbol]['available'] ?? 0,
        'frozen' => $balancesBySymbol[$symbol]['frozen'] ?? 0,
    ];
}
// Add any other coins user might have that are not in displayCoins
foreach ($userBalances as $ub) {
    if (!in_array($ub['symbol'], $displayCoins)) {
        $balances[] = $ub;
    }
}

// Get coins prices (simple static list)
function getCoinPrice($symbol) {
    $prices = [
        'BTC' => 65432.10,
        'ETH' => 3542.50,
        'USDT' => 1.00,
        'BNB' => 612.30,
        'SOL' => 145.20,
        'LTC' => 85.40,
        'TRX' => 0.12,
        'XRP' => 0.62,
        'ADA' => 0.45,
        'DOGE' => 0.16,
        'DOT' => 7.20,
        'MATIC' => 0.72,
    ];
    return $prices[strtoupper($symbol)] ?? 1.00;
}

// Calculate total recharge and dynamic VIP level
$totalRecharge = getUserTotalRecharge($user['id']);
$vipLevel = getAutoVipLevel($totalRecharge);

// Fetch transactions
$stmt = db()->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
$stmt->execute([$user['id']]);
$transactions = $stmt->fetchAll();

// Fetch orders to sync if needed, or just show transactions which should cover most balance changes
// For a complete "order history", we might want a separate tab, but user asked for "recharge, withdrawal, and order records" to be synced here.

$kycStatusText = [
    0 => __('unverified'),
    1 => __(0),
    2 => __('verified'),
    3 => __(4)
];
$kycStatusColor = [
    0 => 'text-white-50',
    1 => 'text-warning',
    2 => 'text-success',
    3 => 'text-danger'
];
?>

<div class="container py-4">
    <div class="row g-4">
        <!-- Sidebar -->
        <div class="col-lg-3">
            <div class="card bg-surface border-secondary rounded-4 overflow-hidden h-100 shadow-lg">
                <div class="card-body p-0">
                    <!-- User Header -->
                    <div class="p-4 text-center border-bottom border-secondary bg-black bg-opacity-30">
                        <div class="avatar-wrapper mb-3 mx-auto">
                            <div class="rounded-circle bg-primary bg-gradient d-flex align-items-center justify-content-center text-white shadow" style="width: 80px; height: 80px; font-size: 32px;">
                                <?= strtoupper(substr($userData['username'], 0, 1)) ?>
                            </div>
                        </div>
                        <h5 class="fw-bold text-white mb-0"><?= htmlspecialchars($userData['username']) ?></h5>
                    </div>
                    
                    <!-- Menu List -->
                    <div class="list-group list-group-flush">
                        <div class="list-group-item py-3 d-flex justify-content-between align-items-center">
                            <span class="text-white-50 small"><i class="bi bi-person-badge me-2 text-primary"></i><?= __('uid') ?></span>
                            <span class="text-white fw-bold small"><?= $userData['uid'] ?></span>
                        </div>
                        <div class="list-group-item py-3 d-flex justify-content-between align-items-center">
                            <span class="text-white-50 small"><i class="bi bi-shield-check me-2 text-info"></i><?= __('credit_score') ?></span>
                            <span class="text-info fw-bold small"><?= $userData['credit_score'] ?></span>
                        </div>
                        <div class="list-group-item py-3 d-flex justify-content-between align-items-center">
                            <span class="text-white-50 small"><i class="bi bi-gem me-2 text-warning"></i><?= __('vip_level') ?></span>
                            <span class="badge bg-warning text-dark fw-bold"><?= __('level') ?> <?= $vipLevel ?></span>
                        </div>
                        <?php if ($vipLevel < 5): 
                            $nextLevel = $vipLevel + 1;
                            $thresholds = [1 => 10000, 2 => 50000, 3 => 100000, 4 => 180000, 5 => 250000];
                            $needed = $thresholds[$nextLevel] - $totalRecharge;
                            if ($needed > 0):
                        ?>
                        <div class="list-group-item py-2 bg-black bg-opacity-20 border-0">
                            <div class="small text-white-50 mb-1" style="font-size: 10px;">
                                <?= str_replace(['%amount%', '%level%'], [number_format($needed, 2), $nextLevel], __('recharge_to_upgrade')) ?>
                            </div>
                            <div class="progress rounded-pill shadow-sm" style="height: 4px; background: rgba(255,255,255,0.1);">
                                <div class="progress-bar bg-warning progress-bar-striped progress-bar-animated" style="width: <?= min(100, ($totalRecharge / $thresholds[$nextLevel]) * 100) ?>%"></div>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php else: ?>
                        <div class="list-group-item py-2 bg-black bg-opacity-20 border-0">
                            <div class="small text-success" style="font-size: 10px;">
                                <i class="bi bi-check2-circle me-1"></i><?= __('highest_level') ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <a href="/kyc.php" class="list-group-item list-group-item-action py-3 d-flex justify-content-between align-items-center">
                            <span class="text-white-50 small"><i class="bi bi-person-vcard me-2 text-success"></i><?= __('kyc') ?></span>
                            <span class="small <?= $kycStatusColor[$userData['kyc_status'] ?? 0] ?>">
                                <?= $kycStatusText[$userData['kyc_status'] ?? 0] ?> <i class="bi bi-chevron-right ms-1"></i>
                            </span>
                        </a>
                        
                        <a href="/security.php" class="list-group-item list-group-item-action py-3 d-flex justify-content-between align-items-center">
                            <span class="text-white-50 small"><i class="bi bi-lock me-2 text-danger"></i><?= __('security') ?></span>
                            <span class="text-white-50 small"><i class="bi bi-chevron-right"></i></span>
                        </a>

                        <a href="/certificate.php" class="list-group-item list-group-item-action py-3 d-flex justify-content-between align-items-center">
                            <span class="text-white-50 small"><i class="bi bi-patch-check me-2 text-primary"></i><?= __('reg_certificate') ?></span>
                            <span class="text-white-50 small"><i class="bi bi-chevron-right"></i></span>
                        </a>
                        
                        <a href="/auth/logout.php" class="list-group-item list-group-item-action py-3 d-flex justify-content-between align-items-center text-danger border-0">
                            <span class="small"><i class="bi bi-box-arrow-right me-2"></i><?= __('logout') ?></span>
                            <span class="small"><i class="bi bi-chevron-right"></i></span>
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-lg-9">
            <!-- Asset Summary -->
            <div class="card bg-surface border-secondary rounded-4 mb-4 shadow-lg overflow-hidden">
                <div class="card-body p-0">
                    <div class="p-4 border-bottom border-secondary bg-black bg-opacity-20">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <span class="text-white-50 small"><?= __('balance') ?>:</span>
                            <span class="text-white-50 small">(<?= __('USDT') ?>)</span>
                        </div>
                        <h2 class="text-white fw-bold mb-0">≈ <?= number_format($totalBalanceUsdt, 2) ?></h2>
                    </div>
                    <div class="p-3 d-flex gap-2">
                        <a href="/recharge.php" class="btn btn-primary flex-fill rounded-3 py-2 shadow-primary">
                            <i class="bi bi-plus-circle me-2"></i><?= __('deposit') ?>
                        </a>
                        <a href="/withdraw.php" class="btn btn-outline-light flex-fill rounded-3 py-2">
                            <i class="bi bi-arrow-up-circle me-2"></i><?= __('withdraw') ?>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Asset Table -->
            <div class="card bg-surface border-secondary rounded-4 overflow-hidden shadow-lg">
                <div class="d-none d-md-block">
                    <div class="table-responsive">
                        <table class="table table-dark table-hover mb-0 align-middle">
                            <thead class="bg-black bg-opacity-50 text-white small border-secondary">
                                <tr>
                                    <th class="ps-4 py-3 border-secondary" style="width: 25%;"><?= __('coin') ?></th>
                                    <th class="py-3 border-secondary" style="width: 20%;"><?= __('available_balance') ?></th>
                                    <th class="py-3 border-secondary" style="width: 20%;"><?= __('frozen') ?></th>
                                    <th class="py-3 border-secondary" style="width: 20%;"><?= __('converted_to') ?></th>
                                    <th class="text-end pe-4 py-3 border-secondary" style="width: 15%;"><?= __('operation') ?></th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                    <div class="asset-list-container" style="height: 210px; overflow-y: auto;">
                        <table class="table table-dark table-hover mb-0 align-middle">
                            <tbody class="border-0">
                                <?php foreach ($balances as $b): ?>
                                <tr class="border-secondary">
                                    <td class="ps-4 py-3" style="width: 25%;">
                                        <div class="d-flex align-items-center gap-3">
                                            <img src="<?= getCoinIcon($b['symbol']) ?>" width="24" height="24" class="rounded-circle" alt="<?= $b['symbol'] ?>" onerror="handleIconError(this, '<?= $b['symbol'] ?>')">
                                            <span class="fw-bold text-white small"><?= $lang === 'zh' ? __($b['symbol']) : $b['symbol'] ?></span>
                                        </div>
                                    </td>
                                    <td class="py-3" style="width: 20%;">
                                        <span class="text-white small fw-bold"><?= number_format($b['available'], 4) ?></span>
                                    </td>
                                    <td class="py-3" style="width: 20%;">
                                        <span class="text-white-50 small"><?= number_format($b['frozen'], 4) ?></span>
                                    </td>
                                    <td class="py-3" style="width: 20%;">
                                        <span class="text-white-50 small">≈ <?= number_format(($b['available'] + $b['frozen']) * getCoinPrice($b['symbol']), 2) ?></span>
                                    </td>
                                    <td class="text-end pe-4 py-3" style="width: 15%;">
                                        <a href="/trade.php?symbol=<?= $b['symbol'] ?>" class="text-primary text-decoration-none small"><?= __('trade') ?></a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <!-- Mobile Asset List -->
                <div class="d-md-none p-3">
                    <?php foreach ($balances as $b): if($b['available'] == 0 && $b['frozen'] == 0 && !in_array($b['symbol'], ['BTC', 'ETH', 'USDT'])) continue; ?>
                    <div class="d-flex align-items-center justify-content-between p-3 mb-2 rounded-4 bg-black bg-opacity-20 border border-secondary border-opacity-50">
                        <div class="d-flex align-items-center gap-3">
                            <img src="<?= getCoinIcon($b['symbol']) ?>" width="32" height="32" class="rounded-circle" alt="<?= $b['symbol'] ?>" onerror="handleIconError(this, '<?= $b['symbol'] ?>')">
                            <div>
                                <div class="fw-bold text-white"><?= $lang === 'zh' ? __($b['symbol']) : $b['symbol'] ?></div>
                                <div class="text-white-50 x-small"><?= __('available_balance') ?>: <?= number_format($b['available'], 4) ?></div>
                            </div>
                        </div>
                        <div class="text-end">
                            <div class="text-white fw-bold small">≈ <?= number_format(($b['available'] + $b['frozen']) * getCoinPrice($b['symbol']), 2) ?> USDT</div>
                            <a href="/trade.php?symbol=<?= $b['symbol'] ?>" class="text-primary x-small"><?= __('trade') ?> <i class="bi bi-chevron-right"></i></a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Asset Records -->
            <div class="mt-5 text-center mb-3">
                <h5 class="text-white fw-bold"><?= __('asset_records') ?></h5>
            </div>
            <div class="card bg-surface border-secondary rounded-4 overflow-hidden shadow-lg">
                <div class="d-none d-md-block">
                    <div class="table-responsive">
                        <table class="table table-dark table-hover mb-0 align-middle small">
                            <thead class="bg-black bg-opacity-20 text-white-50 border-secondary">
                                <tr>
                                    <th class="ps-4 py-3 border-secondary" style="width: 25%;"><?= __('type') ?></th>
                                    <th class="py-3 border-secondary" style="width: 30%;"><?= __('amount') ?></th>
                                    <th class="py-3 border-secondary" style="width: 20%;"><?= __('status') ?></th>
                                    <th class="text-end pe-4 py-3 border-secondary" style="width: 25%;"><?= __('time') ?></th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                    <div class="transaction-list-container" style="height: 240px; overflow-y: auto;">
                        <table class="table table-dark table-hover mb-0 align-middle small">
                            <tbody class="border-0">
                                <?php if (empty($transactions)): ?>
                                <tr>
                                    <td colspan="4" class="text-center py-5 text-white-50">
                                        <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                                        <?= __('no_records_found') ?>
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($transactions as $t): 
                                    $typeColor = 'text-primary';
                                    $typeName = __($t['type']);
                                    if (strpos($t['type'], 'win') !== false || $t['type'] === 'deposit' || $t['type'] === 'binary_win' || $t['type'] === 'recharge' || $t['type'] === 'mining_profit') $typeColor = 'text-success';
                                    elseif (strpos($t['type'], 'loss') !== false || $t['type'] === 'withdraw' || $t['type'] === 'withdrawal' || $t['type'] === 'binary_loss') $typeColor = 'text-danger';
                                    $prefix = (strpos($t['type'], 'win') !== false || $t['type'] === 'deposit' || $t['type'] === 'recharge' || $t['type'] === 'contract_settle' || $t['type'] === 'mining_profit') ? '+' : ((strpos($t['type'], 'loss') !== false || $t['type'] === 'withdraw' || $t['type'] === 'withdrawal' || $t['type'] === 'contract_margin') ? '-' : '');
                                    $statusText = ($t['status'] == 'completed' || $t['status'] == 3) ? __(3) : ($t['status'] == 4 ? __(4) : __(0));
                                    $statusClass = ($t['status'] == 'completed' || $t['status'] == 2 || $t['status'] == 3) ? 'text-success' : ($t['status'] == 4 ? 'text-danger' : 'text-warning');
                                ?>
                                <tr class="border-secondary">
                                    <td class="ps-4 py-3" style="width: 25%;"><span class="<?= $typeColor ?> fw-bold"><?= $typeName ?></span></td>
                                    <td class="py-3" style="width: 30%;"><span class="text-white fw-bold"><?= $prefix . number_format($t['amount'], 4) ?></span> <span class="text-white-50 small"><?= $lang === 'zh' ? __($t['symbol']) : $t['symbol'] ?></span></td>
                                    <td class="py-3" style="width: 20%;"><span class="<?= $statusClass ?> small"><?= $statusText ?></span></td>
                                    <td class="text-end pe-4 py-3" style="width: 25%;"><span class="text-white-50 x-small"><?= date('Y-m-d H:i', strtotime($t['created_at'])) ?></span></td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <!-- Mobile Transaction List -->
                <div class="d-md-none p-3 mobile-transaction-list" style="max-height: 400px; overflow-y: auto;">
                    <?php if (empty($transactions)): ?>
                        <div class="text-center py-4 text-white-50 small"><?= __('no_records_found') ?></div>
                    <?php else: ?>
                    <?php 
                    $count = 0;
                    foreach ($transactions as $t): 
                        $count++;
                        $typeName = __($t['type']);
                        $typeColor = (strpos($t['type'], 'win') !== false || $t['type'] === 'deposit' || $t['type'] === 'recharge' || $t['type'] === 'mining_profit') ? 'text-success' : ((strpos($t['type'], 'loss') !== false || $t['type'] === 'withdraw' || $t['type'] === 'withdrawal') ? 'text-danger' : 'text-primary');
                        $statusText = ($t['status'] == 'completed' || $t['status'] == 3) ? __(3) : ($t['status'] == 4 ? __(4) : __(0));
                        $statusClass = ($t['status'] == 'completed' || $t['status'] == 3) ? 'text-success' : ($t['status'] == 4 ? 'text-danger' : 'text-warning');
                    ?>
                    <div class="p-3 mb-2 rounded-4 bg-black bg-opacity-20 border border-secondary border-opacity-50">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <span class="<?= $typeColor ?> fw-bold small"><?= $typeName ?></span>
                            <span class="text-white-50 x-small"><?= date('m-d H:i', strtotime($t['created_at'])) ?></span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="text-white fw-bold"><?= number_format($t['amount'], 4) ?> <span class="text-white-50 small"><?= $lang === 'zh' ? __($t['symbol']) : $t['symbol'] ?></span></div>
                            <span class="<?= $statusClass ?> x-small fw-bold"><?= $statusText ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .x-small { font-size: 11px; }
    .mobile-transaction-list::-webkit-scrollbar { display: none; }
    .mobile-transaction-list { -ms-overflow-style: none; scrollbar-width: none; }
    @media (max-width: 991px) {
        .col-lg-3 { margin-bottom: 1rem; }
    }
</style>
<?php include __DIR__ . '/includes/footer.php'; ?>
