<?php
require_once '../functions.php';
requireAdminAuth();

$admin = getCurrentAdmin();
$db = getDB();

// Stats
$totalUsers = getUserCount();
$totalBalance = getTotalBalance();
$totalTransactions = getTransactionCount();
$pendingTickets = getPendingTickets();
$pendingKYC = $db->query("SELECT COUNT(*) as count FROM kyc_documents WHERE status = 'pending'")->fetch_assoc()['count'];

// Recent transactions
$recentTx = $db->query("SELECT t.*, u.first_name, u.last_name FROM transactions t JOIN users u ON t.user_id = u.id ORDER BY t.created_at DESC LIMIT 8");

// Recent users
$recentUsers = $db->query("SELECT * FROM users ORDER BY created_at DESC LIMIT 6");

// Chart data
$txByMonth = $db->query("SELECT DATE_FORMAT(created_at, '%b') as month, COUNT(*) as count, SUM(CASE WHEN transaction_type = 'credit' THEN amount ELSE 0 END) as credits, SUM(CASE WHEN transaction_type = 'debit' THEN amount ELSE 0 END) as debits FROM transactions WHERE created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH) GROUP BY MONTH(created_at) ORDER BY created_at");

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <?php include 'includes/admin-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/admin-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <!-- Stats Grid -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-card-header">
                        <span class="stat-card-title">Total Users</span>
                        <div class="stat-card-icon primary">👥</div>
                    </div>
                    <div class="stat-card-value"><?php echo number_format($totalUsers); ?></div>
                    <div class="stat-card-change positive">+<?php echo $db->query("SELECT COUNT(*) as count FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetch_assoc()['count']; ?> this week</div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-card-header">
                        <span class="stat-card-title">Total Balance</span>
                        <div class="stat-card-icon success">💰</div>
                    </div>
                    <div class="stat-card-value"><?php echo formatCurrency($totalBalance); ?></div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-card-header">
                        <span class="stat-card-title">Transactions</span>
                        <div class="stat-card-icon warning">📊</div>
                    </div>
                    <div class="stat-card-value"><?php echo number_format($totalTransactions); ?></div>
                    <div class="stat-card-change positive">+<?php echo $db->query("SELECT COUNT(*) as count FROM transactions WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetch_assoc()['count']; ?> this week</div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-card-header">
                        <span class="stat-card-title">Pending Tickets</span>
                        <div class="stat-card-icon danger">🎫</div>
                    </div>
                    <div class="stat-card-value"><?php echo number_format($pendingTickets); ?></div>
                    <?php if ($pendingTickets > 0): ?>
                        <a href="tickets.php?status=open" style="font-size: 12px; color: var(--primary); font-weight: 600;">View tickets →</a>
                    <?php endif; ?>
                </div>
                
                <div class="stat-card">
                    <div class="stat-card-header">
                        <span class="stat-card-title">Pending KYC</span>
                        <div class="stat-card-icon info">📝</div>
                    </div>
                    <div class="stat-card-value"><?php echo number_format($pendingKYC); ?></div>
                    <?php if ($pendingKYC > 0): ?>
                        <a href="kyc.php?status=pending" style="font-size: 12px; color: var(--primary); font-weight: 600;">Review →</a>
                    <?php endif; ?>
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 24px; margin-bottom: 24px;">
                <!-- Transaction Chart -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">Transaction Overview (Last 6 Months)</span>
                    </div>
                    <div class="card-body">
                        <canvas id="txChart" height="100"></canvas>
                    </div>
                </div>
                
                <!-- Quick Actions -->
                <div class="card">
                    <div class="card-header">
                        <span class="card-title">Quick Actions</span>
                    </div>
                    <div class="card-body" style="display: grid; gap: 10px;">
                        <a href="users.php?action=new" class="btn btn-primary" style="justify-content: flex-start;">
                            <span>➕</span> Add New User
                        </a>
                        <a href="transactions.php" class="btn btn-secondary" style="justify-content: flex-start;">
                            <span>📋</span> View All Transactions
                        </a>
                        <a href="tickets.php" class="btn btn-secondary" style="justify-content: flex-start;">
                            <span>🎫</span> Manage Tickets
                        </a>
                        <a href="crypto-wallets.php" class="btn btn-secondary" style="justify-content: flex-start;">
                            <span>₿</span> Manage Wallets
                        </a>
                        <a href="settings.php" class="btn btn-secondary" style="justify-content: flex-start;">
                            <span>⚙️</span> Global Settings
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Recent Transactions -->
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-header">
                    <span class="card-title">Recent Transactions</span>
                    <a href="transactions.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>User</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($recentTx->num_rows > 0): ?>
                                    <?php while ($tx = $recentTx->fetch_assoc()): ?>
                                        <tr>
                                            <td><?php echo e($tx['first_name'] . ' ' . $tx['last_name']); ?></td>
                                            <td>
                                                <span class="status-badge <?php echo $tx['transaction_type'] === 'credit' ? 'success' : ($tx['transaction_type'] === 'debit' ? 'danger' : 'info'); ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($tx['transaction_type'])); ?>
                                                </span>
                                            </td>
                                            <td><?php echo e($tx['description'] ?? '-'); ?></td>
                                            <td style="font-weight: 700;"><?php echo formatCurrency($tx['amount']); ?></td>
                                            <td><span class="status-badge <?php echo e($tx['status']); ?>"><?php echo ucfirst(e($tx['status'])); ?></span></td>
                                            <td style="font-size: 12px;"><?php echo formatDateShort($tx['created_at']); ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="6" class="text-center" style="padding: 40px; color: var(--gray);">No transactions found</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Recent Users -->
            <div class="card">
                <div class="card-header">
                    <span class="card-title">Recent Users</span>
                    <a href="users.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Account</th>
                                    <th>Balance</th>
                                    <th>KYC</th>
                                    <th>Status</th>
                                    <th>Joined</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($recentUsers->num_rows > 0): ?>
                                    <?php while ($u = $recentUsers->fetch_assoc()): ?>
                                        <tr>
                                            <td><?php echo e($u['first_name'] . ' ' . $u['last_name']); ?></td>
                                            <td><?php echo e($u['email']); ?></td>
                                            <td><code style="font-size: 11px;"><?php echo e($u['account_number']); ?></code></td>
                                            <td style="font-weight: 700;"><?php echo formatCurrency($u['available_balance']); ?></td>
                                            <td><span class="kyc-status <?php echo e($u['kyc_status']); ?>"><?php echo ucfirst(e($u['kyc_status'])); ?></span></td>
                                            <td>
                                                <span class="status-badge <?php echo $u['account_status'] === 'active' ? 'success' : ($u['account_status'] === 'suspended' ? 'danger' : 'warning'); ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($u['account_status'])); ?>
                                                </span>
                                            </td>
                                            <td style="font-size: 12px;"><?php echo formatDateShort($u['created_at']); ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="7" class="text-center" style="padding: 40px; color: var(--gray);">No users found</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../assets/js/main.js"></script>
    <script>
        // Transaction Chart
        const ctx = document.getElementById('txChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: [<?php 
                    $labels = [];
                    $credits = [];
                    $debits = [];
                    $txByMonth->data_seek(0);
                    while ($row = $txByMonth->fetch_assoc()) {
                        $labels[] = "'" . $row['month'] . "'";
                        $credits[] = $row['credits'] ?? 0;
                        $debits[] = $row['debits'] ?? 0;
                    }
                    echo implode(',', $labels);
                ?>],
                datasets: [{
                    label: 'Credits',
                    data: [<?php echo implode(',', $credits); ?>],
                    backgroundColor: '#10B981',
                    borderRadius: 4
                }, {
                    label: 'Debits',
                    data: [<?php echo implode(',', $debits); ?>],
                    backgroundColor: '#DC2626',
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0,0,0,0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    </script>
</body>
</html>
