<?php
/**
 * User Dashboard
 */
$pageTitle = 'Dashboard';
require_once 'includes/header.php';

$userId = $user['id'] ?? 0;

$wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :id", ['id' => $userId]);
if (!$wallet) {
    $wallet = ['balance' => 0, 'demo_balance' => 10000, 'total_won' => 0, 'total_lost' => 0, 'total_trades' => 0];
}

$isDemo = ($accountType ?? 'demo') === 'demo' ? 1 : 0;

$todayTrades = dbFetch(
    "SELECT COUNT(*) as total, 
            COALESCE(SUM(CASE WHEN result = 'won' THEN 1 ELSE 0 END), 0) as won,
            COALESCE(SUM(CASE WHEN result = 'lost' THEN 1 ELSE 0 END), 0) as lost,
            COALESCE(SUM(CASE WHEN result = 'won' THEN actual_profit ELSE 0 END), 0) as profit
     FROM trades 
     WHERE user_id = :id AND is_demo = :is_demo AND DATE(created_at) = CURDATE()",
    ['id' => $userId, 'is_demo' => $isDemo]
);
if (!$todayTrades) {
    $todayTrades = ['total' => 0, 'won' => 0, 'lost' => 0, 'profit' => 0];
}

$activeTrades = dbCount('trades', "user_id = :id AND result = 'pending' AND is_demo = :is_demo", ['id' => $userId, 'is_demo' => $isDemo]);

$recentTrades = dbFetchAll(
    "SELECT t.*, a.name as asset_name 
     FROM trades t 
     LEFT JOIN assets a ON t.asset_id = a.id 
     WHERE t.user_id = :id AND t.is_demo = :is_demo
     ORDER BY t.created_at DESC LIMIT 10",
    ['id' => $userId, 'is_demo' => $isDemo]
);

$recentTransactions = dbFetchAll(
    "SELECT * FROM transactions WHERE user_id = :id ORDER BY created_at DESC LIMIT 5",
    ['id' => $userId]
);

$totalClosedTrades = ($wallet['total_won'] ?? 0) + ($wallet['total_lost'] ?? 0);
$winRate = $totalClosedTrades > 0 ? round((($wallet['total_won'] ?? 0) / $totalClosedTrades) * 100, 1) : 0;
?>

<style>
/* === UTILITIES === */
.d-flex{display:flex}.d-grid{display:grid}
.flex-wrap{flex-wrap:wrap}.flex-1{flex:1;min-width:0}
.align-items-center{align-items:center}
.justify-content-between{justify-content:space-between}
.justify-content-center{justify-content:center}
.text-center{text-align:center}
.gap-2{gap:8px}.gap-3{gap:12px}.gap-4{gap:16px}
.p-0{padding:0!important}.p-3{padding:12px}
.py-4{padding-top:16px;padding-bottom:16px}
.mb-2{margin-bottom:8px}.mb-3{margin-bottom:12px}.mb-4{margin-bottom:16px}
.mt-3{margin-top:12px}
.font-semibold{font-weight:600}
.font-mono{font-family:'JetBrains Mono','Fira Code',monospace}
.text-muted{color:var(--text-secondary)!important}
.text-green{color:#00d09c!important}
.text-red{color:#ff4757!important}
.text-blue{color:#3b82f6!important}
.text-yellow{color:#fbbf24!important}
.text-purple{color:#a855f7!important}

/* === WELCOME === */
.dashboard-welcome{
    background:linear-gradient(135deg,rgba(0,208,156,.08),rgba(59,130,246,.08));
    border:1px solid rgba(0,208,156,.2);border-radius:16px;padding:24px;margin-bottom:24px;
}
.welcome-content{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:16px}
.welcome-text h2{font-size:1.4rem;font-weight:700;margin-bottom:4px}
.welcome-text p{color:var(--text-secondary);margin:0;font-size:.9rem}
.quick-actions{display:flex;gap:10px;flex-wrap:wrap}

/* === STATS === */
.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}
@media(max-width:1100px){.stats-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:500px){.stats-grid{grid-template-columns:1fr}}
.stat-card{
    background:var(--bg-card);border:1px solid var(--border-color);border-radius:14px;
    padding:20px;display:flex;align-items:center;gap:16px;transition:transform .2s,border-color .2s;
}
.stat-card:hover{transform:translateY(-2px);border-color:rgba(0,208,156,.3)}
.stat-icon{
    width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;
    font-size:1.1rem;flex-shrink:0;
}
.stat-icon.green{background:rgba(0,208,156,.15);color:#00d09c}
.stat-icon.red{background:rgba(255,71,87,.15);color:#ff4757}
.stat-icon.blue{background:rgba(59,130,246,.15);color:#3b82f6}
.stat-icon.yellow{background:rgba(251,191,36,.15);color:#fbbf24}
.stat-icon.purple{background:rgba(168,85,247,.15);color:#a855f7}
.stat-info{flex:1;min-width:0}
.stat-value{font-size:1.4rem;font-weight:700;line-height:1.2}
.stat-label{font-size:.78rem;color:var(--text-secondary);margin-top:2px}

/* === CONTENT GRID === */
.content-grid{display:grid;grid-template-columns:5fr 3fr;gap:20px}
@media(max-width:900px){.content-grid{grid-template-columns:1fr}}

/* === CARDS === */
.card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:14px;overflow:hidden}
.card-header{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid var(--border-color)}
.card-title{font-size:.95rem;font-weight:600;margin:0}
.card-body{padding:20px}
.card-body.p-0{padding:0!important}

/* === BUTTONS === */
.btn{
    padding:10px 20px;border:none;border-radius:10px;font-weight:600;font-size:.85rem;
    cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;gap:8px;
    transition:all .2s;line-height:1.4;
}
.btn:hover{opacity:.9;transform:translateY(-1px)}
.btn-primary{background:linear-gradient(135deg,#00d09c,#00a87a);color:#000}
.btn-secondary{background:var(--bg-secondary);color:var(--text-primary);border:1px solid var(--border-color)}
.btn-sm{padding:6px 14px;font-size:.78rem;border-radius:8px}

/* === BADGES === */
.badge{
    display:inline-flex;align-items:center;gap:4px;
    padding:4px 10px;border-radius:6px;font-size:.72rem;font-weight:600;white-space:nowrap;
}
.badge-success{background:rgba(0,208,156,.15);color:#00d09c}
.badge-danger{background:rgba(255,71,87,.15);color:#ff4757}
.badge-warning{background:rgba(251,191,36,.15);color:#fbbf24}
.badge-secondary{background:rgba(139,146,168,.15);color:#8b92a8}

/* === TABLE === */
.table-responsive{overflow-x:auto;-webkit-overflow-scrolling:touch}
.table{width:100%;border-collapse:collapse;font-size:.85rem}
.table thead{background:var(--bg-secondary)}
.table th{padding:12px 16px;text-align:left;font-weight:600;color:var(--text-secondary);font-size:.75rem;text-transform:uppercase;letter-spacing:.5px;white-space:nowrap}
.table td{padding:14px 16px;border-bottom:1px solid var(--border-color);vertical-align:middle}
.table tbody tr:hover{background:rgba(255,255,255,.02)}
.table tbody tr:last-child td{border-bottom:none}

/* === PERFORMANCE === */
.perf-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px}
.perf-item{text-align:center;padding:12px;background:var(--bg-secondary);border-radius:10px;border:1px solid var(--border-color)}
.perf-value{font-size:1.3rem;font-weight:700;line-height:1.2}
.perf-label{font-size:.7rem;color:var(--text-secondary);margin-top:2px}
.perf-total{text-align:center;padding:16px;background:var(--bg-secondary);border-radius:12px;border:1px solid var(--border-color)}
.perf-total-value{font-size:1.8rem;font-weight:700}
.perf-total-label{font-size:.75rem;color:var(--text-secondary);margin-top:4px}

/* === ACTIVITY === */
.activity-item{display:flex;align-items:center;gap:12px;padding:14px 20px;border-bottom:1px solid var(--border-color);transition:background .2s}
.activity-item:hover{background:rgba(255,255,255,.02)}
.activity-item:last-child{border-bottom:none}
.activity-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:.85rem;flex-shrink:0}
.activity-icon.green{background:rgba(0,208,156,.15);color:#00d09c}
.activity-icon.red{background:rgba(255,71,87,.15);color:#ff4757}
.activity-info{flex:1;min-width:0}
.activity-title{font-size:.85rem;font-weight:600}
.activity-time{font-size:.7rem;color:var(--text-secondary)}
.activity-amount{font-weight:600;font-family:'JetBrains Mono','Fira Code',monospace;font-size:.85rem;white-space:nowrap}

/* === EMPTY STATE === */
.empty-state{padding:32px 20px;text-align:center;color:var(--text-secondary)}
.empty-state i{font-size:2rem;margin-bottom:8px;opacity:.4;display:block}
.empty-state p{font-size:.85rem;margin-bottom:12px}
.empty-state a{color:#00d09c;text-decoration:none;font-weight:600}

/* === MOBILE === */
@media(max-width:768px){
    .top-bar{flex-direction:column;gap:12px;align-items:stretch}
    .top-bar .page-title{font-size:1.2rem}
    .balance-box{justify-content:center;flex-wrap:wrap}
    .balance-item{padding:8px 12px;flex:1;min-width:120px;text-align:center}
    .welcome-content{flex-direction:column;text-align:center}
    .welcome-text h2{font-size:1.2rem}
    .quick-actions{justify-content:center}
}
</style>

<!-- Welcome -->
<div class="dashboard-welcome">
    <div class="welcome-content">
        <div class="welcome-text">
            <h2>Welcome back, <?= htmlspecialchars($user['first_name'] ?? 'Trader') ?>! 👋</h2>
            <p>Ready to trade? Your account is looking great today.</p>
        </div>
        <div class="quick-actions">
            <a href="trade.php" class="btn btn-primary"><i class="fas fa-chart-line"></i> Start Trading</a>
            <a href="deposit.php" class="btn btn-secondary"><i class="fas fa-plus"></i> Deposit</a>
        </div>
    </div>
</div>

<!-- Stats -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon green"><i class="fas fa-wallet"></i></div>
        <div class="stat-info">
            <div class="stat-value text-green"><?= formatCurrency(max(0, ($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0) - $pendingAmount)) ?></div>
            <div class="stat-label">Real Balance</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-gamepad"></i></div>
        <div class="stat-info">
            <div class="stat-value text-blue"><?= formatCurrency($wallet['demo_balance'] ?? 0) ?></div>
            <div class="stat-label">Demo Balance</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon yellow"><i class="fas fa-exchange-alt"></i></div>
        <div class="stat-info">
            <div class="stat-value"><?= number_format($wallet['total_trades'] ?? 0) ?></div>
            <div class="stat-label">Total Trades</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon purple"><i class="fas fa-percentage"></i></div>
        <div class="stat-info">
            <div class="stat-value"><?= $winRate ?>%</div>
            <div class="stat-label">Win Rate</div>
        </div>
    </div>
</div>

<!-- Content -->
<div class="content-grid">
    <!-- Recent Trades -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Recent Trades</h3>
            <a href="history.php" class="btn btn-sm btn-secondary">View All</a>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr><th>Asset</th><th>Direction</th><th>Amount</th><th>Result</th><th>Profit</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentTrades as $trade): ?>
                        <tr>
                            <td>
                                <div class="font-semibold"><?= htmlspecialchars($trade['symbol'] ?? $trade['asset_name'] ?? 'N/A') ?></div>
                                <div class="text-muted" style="font-size:.72rem"><?= formatDateTime($trade['created_at'], 'd M, H:i') ?></div>
                            </td>
                            <td>
                                <span class="badge badge-<?= $trade['direction'] === 'up' ? 'success' : 'danger' ?>">
                                    <i class="fas fa-arrow-<?= $trade['direction'] ?>"></i> <?= strtoupper($trade['direction']) ?>
                                </span>
                            </td>
                            <td class="font-mono"><?= formatCurrency($trade['amount']) ?></td>
                            <td>
                                <?php
                                $statusClasses = ['won' => 'success', 'lost' => 'danger', 'pending' => 'warning'];
                                $resultClass = $statusClasses[$trade['result']] ?? 'secondary';
                                ?>
                                <span class="badge badge-<?= $resultClass ?>"><?= ucfirst($trade['result']) ?></span>
                            </td>
                            <td class="font-mono <?= $trade['result'] === 'won' ? 'text-green' : ($trade['result'] === 'lost' ? 'text-red' : '') ?>">
                                <?php if ($trade['result'] === 'won'): ?>+<?= formatCurrency($trade['actual_profit']) ?>
                                <?php elseif ($trade['result'] === 'lost'): ?>-<?= formatCurrency($trade['amount']) ?>
                                <?php else: ?>--<?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($recentTrades)): ?>
                        <tr><td colspan="5"><div class="empty-state"><i class="fas fa-chart-bar"></i><p>No trades yet</p><a href="trade.php"><i class="fas fa-play"></i> Start trading now!</a></div></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Right Sidebar -->
    <div>
        <!-- Today's Performance -->
        <div class="card mb-3">
            <div class="card-header"><h3 class="card-title">Today's Performance</h3></div>
            <div class="card-body">
                <div class="perf-grid">
                    <div class="perf-item"><div class="perf-value text-green"><?= $todayTrades['won'] ?? 0 ?></div><div class="perf-label">Won</div></div>
                    <div class="perf-item"><div class="perf-value text-red"><?= $todayTrades['lost'] ?? 0 ?></div><div class="perf-label">Lost</div></div>
                    <div class="perf-item"><div class="perf-value"><?= $todayTrades['total'] ?? 0 ?></div><div class="perf-label">Total</div></div>
                </div>
                <div class="perf-total">
                    <div class="perf-total-value <?= ($todayTrades['profit'] ?? 0) >= 0 ? 'text-green' : 'text-red' ?>">
                        <?= ($todayTrades['profit'] ?? 0) >= 0 ? '+' : '' ?><?= formatCurrency($todayTrades['profit'] ?? 0) ?>
                    </div>
                    <div class="perf-total-label">Today's Profit/Loss</div>
                </div>
            </div>
        </div>
        
        <!-- Recent Activity -->
        <div class="card">
            <div class="card-header"><h3 class="card-title">Recent Activity</h3></div>
            <div class="card-body p-0">
                <?php foreach ($recentTransactions as $tx): ?>
                <div class="activity-item">
                    <div class="activity-icon <?= $tx['amount'] >= 0 ? 'green' : 'red' ?>">
                        <i class="fas fa-<?= $tx['amount'] >= 0 ? 'arrow-down' : 'arrow-up' ?>"></i>
                    </div>
                    <div class="activity-info">
                        <div class="activity-title"><?= ucfirst(str_replace('_', ' ', $tx['type'])) ?></div>
                        <div class="activity-time"><?= timeAgo($tx['created_at']) ?></div>
                    </div>
                    <div class="activity-amount <?= $tx['amount'] >= 0 ? 'text-green' : 'text-red' ?>">
                        <?= $tx['amount'] >= 0 ? '+' : '' ?><?= formatCurrency($tx['amount']) ?>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if (empty($recentTransactions)): ?>
                <div class="empty-state"><i class="fas fa-inbox"></i><p>No recent activity</p></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
