<?php
/**
 * Admin Dashboard
 */

$pageTitle = 'Dashboard';
require_once 'includes/header.php';

// Get statistics
$totalUsers = dbCount('users');
$activeUsers = dbCount('users', "status = 'active'");
$todayUsers = dbCount('users', "DATE(created_at) = CURDATE()");

$totalDeposits = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM deposits WHERE status = 'approved'")['total'];
$todayDeposits = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM deposits WHERE status = 'approved' AND DATE(created_at) = CURDATE()")['total'];

$totalWithdrawals = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals WHERE status = 'approved'")['total'];
$todayWithdrawals = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals WHERE status = 'approved' AND DATE(created_at) = CURDATE()")['total'];

$totalTrades = dbCount('trades', "is_demo = 0");
$todayTrades = dbCount('trades', "is_demo = 0 AND DATE(created_at) = CURDATE()");
$activeTrades = dbCount('trades', "result = 'pending'");

$wonTrades = dbCount('trades', "result = 'won' AND is_demo = 0");
$lostTrades = dbCount('trades', "result = 'lost' AND is_demo = 0");

$totalProfit = dbFetch("SELECT COALESCE(SUM(CASE WHEN result = 'lost' THEN amount ELSE 0 END) - SUM(CASE WHEN result = 'won' THEN actual_profit ELSE 0 END), 0) as profit FROM trades WHERE is_demo = 0")['profit'];

// Recent data
$recentDeposits = dbFetchAll(
    "SELECT d.*, u.email, u.first_name, u.last_name 
     FROM deposits d 
     LEFT JOIN users u ON d.user_id = u.id 
     ORDER BY d.created_at DESC LIMIT 5"
);

$recentWithdrawals = dbFetchAll(
    "SELECT w.*, u.email, u.first_name, u.last_name 
     FROM withdrawals w 
     LEFT JOIN users u ON w.user_id = u.id 
     ORDER BY w.created_at DESC LIMIT 5"
);

$recentTrades = dbFetchAll(
    "SELECT t.*, u.email, u.first_name 
     FROM trades t 
     LEFT JOIN users u ON t.user_id = u.id 
     WHERE t.is_demo = 0
     ORDER BY t.created_at DESC LIMIT 10"
);

$recentUsers = dbFetchAll(
    "SELECT u.*, w.balance 
     FROM users u 
     LEFT JOIN user_wallets w ON u.id = w.user_id 
     ORDER BY u.created_at DESC LIMIT 5"
);

// Last 7 days data for chart
$last7Days = dbFetchAll(
    "SELECT DATE(created_at) as date, 
            COUNT(*) as trades,
            SUM(CASE WHEN result = 'won' THEN 1 ELSE 0 END) as won,
            SUM(CASE WHEN result = 'lost' THEN 1 ELSE 0 END) as lost,
            SUM(amount) as volume
     FROM trades 
     WHERE is_demo = 0 AND created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
     GROUP BY DATE(created_at)
     ORDER BY date ASC"
);
?>

<style>
.dashboard-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
    margin-bottom: 1.5rem;
}

@media (max-width: 1200px) {
    .dashboard-grid { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 768px) {
    .dashboard-grid { grid-template-columns: 1fr; }
}

.charts-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

@media (max-width: 992px) {
    .charts-grid { grid-template-columns: 1fr; }
}

.tables-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
}

@media (max-width: 992px) {
    .tables-grid { grid-template-columns: 1fr; }
}

.stat-mini {
    font-size: 0.75rem;
    color: var(--text-muted);
    margin-top: 0.25rem;
}

.chart-container-dashboard {
    height: 300px;
}

.activity-item {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.75rem 0;
    border-bottom: 1px solid var(--border-color);
}

.activity-item:last-child {
    border-bottom: none;
}

.activity-icon {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.875rem;
}

.activity-icon.deposit { background: rgba(0, 208, 156, 0.15); color: var(--accent-green); }
.activity-icon.withdrawal { background: rgba(255, 82, 82, 0.15); color: var(--accent-red); }
.activity-icon.user { background: rgba(59, 130, 246, 0.15); color: var(--accent-blue); }
.activity-icon.trade { background: rgba(251, 191, 36, 0.15); color: var(--accent-yellow); }

.activity-info { flex: 1; min-width: 0; }
.activity-title { font-weight: 500; font-size: 0.875rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; display: block; }
.activity-time { font-size: 0.75rem; color: var(--text-muted); }
.activity-amount { font-weight: 600; font-family: var(--font-mono); }
.table-responsive .table th, 
.table-responsive .table td { white-space: nowrap; }
</style>

<!-- Stats Cards -->
<div class="dashboard-grid">
    <div class="stat-card">
        <div class="stat-icon blue">
            <i class="fas fa-users"></i>
        </div>
        <div class="stat-value"><?= number_format($totalUsers) ?></div>
        <div class="stat-label">Total Users</div>
        <div class="stat-mini">
            <span class="text-green">+<?= $todayUsers ?></span> today
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon green">
            <i class="fas fa-arrow-down"></i>
        </div>
        <div class="stat-value"><?= formatCurrency($totalDeposits) ?></div>
        <div class="stat-label">Total Deposits</div>
        <div class="stat-mini">
            <span class="text-green">+<?= formatCurrency($todayDeposits) ?></span> today
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon red">
            <i class="fas fa-arrow-up"></i>
        </div>
        <div class="stat-value"><?= formatCurrency($totalWithdrawals) ?></div>
        <div class="stat-label">Total Withdrawals</div>
        <div class="stat-mini">
            <span class="text-red">-<?= formatCurrency($todayWithdrawals) ?></span> today
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon <?= $totalProfit >= 0 ? 'green' : 'red' ?>">
            <i class="fas fa-chart-line"></i>
        </div>
        <div class="stat-value <?= $totalProfit >= 0 ? 'text-green' : 'text-red' ?>">
            <?= formatCurrency(abs($totalProfit)) ?>
        </div>
        <div class="stat-label">Platform <?= $totalProfit >= 0 ? 'Profit' : 'Loss' ?></div>
        <div class="stat-mini">
            <?= $wonTrades ?> won / <?= $lostTrades ?> lost trades
        </div>
    </div>
</div>

<!-- Second Row Stats -->
<div class="dashboard-grid">
    <div class="stat-card">
        <div class="stat-icon yellow">
            <i class="fas fa-exchange-alt"></i>
        </div>
        <div class="stat-value"><?= number_format($totalTrades) ?></div>
        <div class="stat-label">Total Trades</div>
        <div class="stat-mini">
            <span class="text-green">+<?= $todayTrades ?></span> today
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon purple">
            <i class="fas fa-clock"></i>
        </div>
        <div class="stat-value"><?= number_format($activeTrades) ?></div>
        <div class="stat-label">Active Trades</div>
        <div class="stat-mini">Currently running</div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon green">
            <i class="fas fa-hourglass-half"></i>
        </div>
        <div class="stat-value"><?= $pendingDeposits ?></div>
        <div class="stat-label">Pending Deposits</div>
        <div class="stat-mini">
            <a href="deposits.php?status=pending" class="text-green">View all →</a>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon red">
            <i class="fas fa-hourglass-half"></i>
        </div>
        <div class="stat-value"><?= $pendingWithdrawals ?></div>
        <div class="stat-label">Pending Withdrawals</div>
        <div class="stat-mini">
            <a href="withdrawals.php?status=pending" class="text-red">View all →</a>
        </div>
    </div>
</div>

<!-- Charts and Activity -->
<div class="charts-grid">
    <!-- Trading Volume Chart -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Trading Volume (Last 7 Days)</h3>
        </div>
        <div class="card-body">
            <div class="chart-container-dashboard">
                <canvas id="volumeChart"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Recent Activity -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Recent Activity</h3>
        </div>
        <div class="card-body" style="max-height: 350px; overflow-y: auto;">
            <?php foreach ($recentDeposits as $deposit): ?>
            <div class="activity-item">
                <div class="activity-icon deposit">
                    <i class="fas fa-arrow-down"></i>
                </div>
                <div class="activity-info">
                    <div class="activity-title">
                        <?= htmlspecialchars($deposit['first_name'] ?? $deposit['email']) ?> deposited
                    </div>
                    <div class="activity-time"><?= timeAgo($deposit['created_at']) ?></div>
                </div>
                <div class="activity-amount text-green">
                    +<?= formatCurrency($deposit['amount']) ?>
                </div>
            </div>
            <?php endforeach; ?>
            
            <?php foreach ($recentWithdrawals as $withdrawal): ?>
            <div class="activity-item">
                <div class="activity-icon withdrawal">
                    <i class="fas fa-arrow-up"></i>
                </div>
                <div class="activity-info">
                    <div class="activity-title">
                        <?= htmlspecialchars($withdrawal['first_name'] ?? $withdrawal['email']) ?> requested withdrawal
                    </div>
                    <div class="activity-time"><?= timeAgo($withdrawal['created_at']) ?></div>
                </div>
                <div class="activity-amount text-red">
                    -<?= formatCurrency($withdrawal['amount']) ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Tables -->
<div class="tables-grid">
    <!-- Recent Trades -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Recent Trades</h3>
            <a href="trades.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>User</th>
                            <th>Asset</th>
                            <th>Amount</th>
                            <th>Result</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentTrades as $trade): ?>
                        <tr>
                            <td><?= htmlspecialchars($trade['first_name'] ?? $trade['email']) ?></td>
                            <td>
                                <span class="badge badge-<?= $trade['direction'] === 'up' ? 'success' : 'danger' ?>">
                                    <i class="fas fa-arrow-<?= $trade['direction'] ?>"></i>
                                </span>
                                <?= $trade['symbol'] ?>
                            </td>
                            <td><?= formatCurrency($trade['amount']) ?></td>
                            <td>
                                <?php
                                $statusClasses = ['won' => 'success', 'lost' => 'danger', 'pending' => 'warning'];
                                $badgeClass = $statusClasses[$trade['result']] ?? 'secondary';
                                ?>
                                <span class="badge badge-<?= $badgeClass ?>">
                                    <?= ucfirst($trade['result']) ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($recentTrades)): ?>
                        <tr>
                            <td colspan="4" class="text-center text-muted">No trades yet</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Recent Users -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">Recent Users</h3>
            <a href="users.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>User</th>
                            <th>Balance</th>
                            <th>Status</th>
                            <th>Joined</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentUsers as $user): ?>
                        <tr>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <div class="user-avatar" style="width: 32px; height: 32px; font-size: 0.75rem;">
                                        <?= strtoupper(substr($user['first_name'] ?? $user['email'], 0, 1)) ?>
                                    </div>
                                    <div>
                                        <div class="font-semibold"><?= htmlspecialchars($user['first_name'] ?? 'N/A') ?></div>
                                        <div class="text-muted" style="font-size: 0.75rem;"><?= htmlspecialchars($user['email']) ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="font-mono"><?= formatCurrency($user['balance'] ?? 0) ?></td>
                            <td>
                                <?php
                                $statusClasses = ['active' => 'success', 'blocked' => 'danger'];
                                $statusClass = $statusClasses[$user['status']] ?? 'secondary';
                                ?>
                                <span class="badge badge-<?= $statusClass ?>">
                                    <?= ucfirst($user['status']) ?>
                                </span>
                            </td>
                            <td class="text-muted"><?= timeAgo($user['created_at']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($recentUsers)): ?>
                        <tr>
                            <td colspan="4" class="text-center text-muted">No users yet</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Volume Chart
const chartData = <?= json_encode($last7Days) ?>;

const labels = chartData.map(d => {
    const date = new Date(d.date);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
});

const ctx = document.getElementById('volumeChart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: [
            {
                label: 'Won',
                data: chartData.map(d => d.won || 0),
                backgroundColor: 'rgba(0, 208, 156, 0.8)',
                borderRadius: 4
            },
            {
                label: 'Lost',
                data: chartData.map(d => d.lost || 0),
                backgroundColor: 'rgba(255, 82, 82, 0.8)',
                borderRadius: 4
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    color: '#9ca3af',
                    usePointStyle: true,
                    padding: 20
                }
            }
        },
        scales: {
            x: {
                stacked: true,
                grid: { display: false },
                ticks: { color: '#9ca3af' }
            },
            y: {
                stacked: true,
                grid: { color: 'rgba(255,255,255,0.05)' },
                ticks: { color: '#9ca3af' }
            }
        }
    }
});
</script>

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