<?php
require_once 'config.php';
require_once 'classes/Security.php';
require_once 'classes/Wallet.php';
require_once 'classes/Trading.php';

Security::requireAuth();

$pageTitle = 'Dashboard - CryptoExchange Pro';

$wallet = new Wallet();
$trading = new Trading();

// Get user wallets and trading stats
$userWallets = $wallet->getUserWallets($_SESSION['user_id']);
$userTrades = $trading->getUserTrades($_SESSION['user_id']);
$recentTransactions = $wallet->getTransactionHistory($_SESSION['user_id'], 10);

// Calculate total portfolio value
$totalValue = 0;
foreach ($userWallets as $w) {
    $totalValue += ($w['balance'] * $w['current_price']);
}

include 'includes/header.php';
?>

<main class="container my-4">
    <!-- Welcome Section -->
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="display-5 fw-bold text-primary">
                <i class="fas fa-tachometer-alt me-3"></i>Welcome back, <?php echo $_SESSION['username']; ?>!
            </h1>
            <p class="lead text-muted">Manage your cryptocurrency portfolio and trades</p>
        </div>
    </div>

   <!-- Stats Cards -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card bg-primary text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title mb-0">Total Portfolio</h6>
                        <h4 class="mb-0">$<?php echo number_format($totalValue, 2); ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-wallet fa-2x opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card bg-success text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title mb-0">Active Trades</h6>
                        <h4 class="mb-0"><?php echo count(array_filter($userTrades, function($t) { return !in_array($t['status'], ['completed', 'cancelled']); })); ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-exchange-alt fa-2x opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card bg-info text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title mb-0">Completed Trades</h6>
                        <h4 class="mb-0"><?php echo count(array_filter($userTrades, function($t) { return $t['status'] == 'completed'; })); ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-check-circle fa-2x opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="card bg-warning text-white shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="card-title mb-0">Wallets</h6>
                        <h4 class="mb-0"><?php echo count($userWallets); ?></h4>
                    </div>
                    <div class="align-self-center">
                        <i class="fas fa-coins fa-2x opacity-75"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Portfolio Overview -->
    <div class="col-lg-8 mb-4">
        <div class="card shadow">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="fas fa-chart-pie me-2"></i>Portfolio Overview</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($userWallets)): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Asset</th>
                                <th>Balance</th>
                                <th>Locked</th>
                                <th>Current Price</th>
                                <th>Value</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($userWallets as $wallet): ?>
                            <tr>
                                <td>
                                    <strong><?php echo $wallet['symbol']; ?></strong>
                                    <small class="text-muted d-block"><?php echo $wallet['name']; ?></small>
                                </td>
                                <td><?php echo number_format($wallet['balance'], 8); ?></td>
                                <td class="text-warning"><?php echo number_format($wallet['locked_balance'], 8); ?></td>
                                <td id="price-<?php echo $wallet['symbol']; ?>">$<?php echo number_format($wallet['current_price'], 8); ?></td>
                                <td class="fw-bold">$<?php echo number_format($wallet['balance'] * $wallet['current_price'], 2); ?></td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <a href="trading.php?crypto=<?php echo $wallet['crypto_id']; ?>" class="btn btn-outline-primary btn-sm">
                                            <i class="fas fa-exchange-alt"></i> Trade
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-4">
                    <i class="fas fa-wallet fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">No cryptocurrencies in your portfolio yet</h5>
                    <a href="trading.php" class="btn btn-primary">Start Trading</a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Recent Activity -->
    <div class="col-lg-4 mb-4">
        <div class="card shadow">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="fas fa-history me-2"></i>Recent Activity</h5>
            </div>
            <div class="card-body">
                <?php if (!empty($recentTransactions)): ?>
                <div class="timeline">
                    <?php foreach ($recentTransactions as $transaction): ?>
                    <div class="timeline-item mb-3">
                        <div class="d-flex">
                            <div class="flex-shrink-0">
                                <?php
                                $iconClass = 'fas fa-arrow-up text-success';
                                $bgClass = 'bg-success';
                                if ($transaction['transaction_type'] == 'withdrawal' || $transaction['transaction_type'] == 'trade_sell') {
                                    $iconClass = 'fas fa-arrow-down text-danger';
                                    $bgClass = 'bg-danger';
                                } elseif ($transaction['transaction_type'] == 'fee') {
                                    $iconClass = 'fas fa-percent text-warning';
                                    $bgClass = 'bg-warning';
                                }
                                ?>
                                <div class="timeline-icon rounded-circle <?php echo $bgClass; ?> text-white p-2">
                                    <i class="<?php echo $iconClass; ?>"></i>
                                </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <div class="d-flex justify-content-between">
                                    <h6 class="mb-0"><?php echo ucfirst(str_replace('_', ' ', $transaction['transaction_type'])); ?></h6>
                                    <small class="text-muted"><?php echo date('M j, H:i', strtotime($transaction['created_at'])); ?></small>
                                </div>
                                <p class="mb-1">
                                    <?php echo number_format(abs($transaction['amount']), 8); ?> <?php echo $transaction['symbol']; ?>
                                </p>
                                <?php if ($transaction['notes']): ?>
                                <small class="text-muted"><?php echo $transaction['notes']; ?></small>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="text-center mt-3">
                    <a href="transactions.php" class="btn btn-outline-primary btn-sm">View All Transactions</a>
                </div>
                <?php else: ?>
                <div class="text-center py-4">
                    <i class="fas fa-history fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No recent activity</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Active Trades -->
<?php 
$activeTrades = array_filter($userTrades, function($t) { 
    return !in_array($t['status'], ['completed', 'cancelled']); 
});
?>

<?php if (!empty($activeTrades)): ?>
<div class="row">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header bg-light">
                <h5 class="mb-0"><i class="fas fa-clock me-2"></i>Active Trades</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Trade ID</th>
                                <th>Type</th>
                                <th>Asset</th>
                                <th>Amount</th>
                                <th>Price</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($activeTrades as $trade): ?>
                            <tr>
                                <td><strong>#<?php echo $trade['id']; ?></strong></td>
                                <td>
                                    <span class="badge <?php echo $trade['seller_id'] == $_SESSION['user_id'] ? 'bg-danger' : 'bg-success'; ?>">
                                        <?php echo $trade['seller_id'] == $_SESSION['user_id'] ? 'SELL' : 'BUY'; ?>
                                    </span>
                                </td>
                                <td><?php echo $trade['symbol']; ?></td>
                                <td><?php echo number_format($trade['amount'], 8); ?></td>
                                <td>$<?php echo number_format($trade['price_per_unit'], 2); ?></td>
                                <td>
                                    <?php
                                    $statusClass = [
                                        'open' => 'bg-primary',
                                        'matched' => 'bg-info',
                                        'in_escrow' => 'bg-warning',
                                        'payment_pending' => 'bg-danger',
                                        'disputed' => 'bg-secondary'
                                    ];
                                    ?>
                                    <span class="badge <?php echo $statusClass[$trade['status']] ?? 'bg-secondary'; ?>">
                                        <?php echo strtoupper(str_replace('_', ' ', $trade['status'])); ?>
                                    </span>
                                </td>
                                <td><?php echo date('M j, H:i', strtotime($trade['created_at'])); ?></td>
                                <td>
                                    <a href="trade-details.php?id=<?php echo $trade['id']; ?>" class="btn btn-outline-primary btn-sm">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>
