<?php
// require_once '../../config.php';

$user = currentUser();
if ($user['role'] !== 'admin') {
    header('Location: /admin.php');
    exit;
}

$site_name = getSiteConfig('site_name') ?? '授权系统';
?>
<div class="admin-container">
    <h2>
        <img src="https://api.iconify.design/mdi:chart-bar.svg?color=%23667eea" width="24" height="24" style="vertical-align: middle; margin-right: 8px;" alt="">
        数据统计
    </h2>
    
    <!-- 统计卡片 -->
    <div class="stats-cards">
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:account-group.svg?color=%23667eea" width="48" height="48" alt="">
            </div>
            <div class="stat-info">
                <div class="stat-value" id="total_users">-</div>
                <div class="stat-label">总用户数</div>
                <div class="stat-today" id="today_users">今日新增: -</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:cash.svg?color=%2310b981" width="48" height="48" alt="">
            </div>
            <div class="stat-info">
                <div class="stat-value" id="total_amount">-</div>
                <div class="stat-label">总充值金额</div>
                <div class="stat-today" id="today_amount">今日充值: -</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:cart.svg?color=%23f59e0b" width="48" height="48" alt="">
            </div>
            <div class="stat-info">
                <div class="stat-value" id="total_orders">-</div>
                <div class="stat-label">成功订单</div>
                <div class="stat-today">-</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">
                <img src="https://api.iconify.design/mdi:shield-lock.svg?color=%23ef4444" width="48" height="48" alt="">
            </div>
            <div class="stat-info">
                <div class="stat-value" id="total_encrypts">-</div>
                <div class="stat-label">加密次数</div>
                <div class="stat-today">-</div>
            </div>
        </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-row">
        <div class="chart-card">
            <h3>
                <img src="https://api.iconify.design/mdi:account-arrow-up.svg?color=%23667eea" width="20" height="20" style="vertical-align: middle; margin-right: 6px;" alt="">
                用户增长趋势
            </h3>
            <canvas id="userTrendChart" height="250"></canvas>
        </div>
        <div class="chart-card">
            <h3>
                <img src="https://api.iconify.design/mdi:cash-fast.svg?color=%2310b981" width="20" height="20" style="vertical-align: middle; margin-right: 6px;" alt="">
                充值趋势
            </h3>
            <canvas id="rechargeTrendChart" height="250"></canvas>
        </div>
    </div>
    
    <div class="charts-row">
        <div class="chart-card">
            <h3>
                <img src="https://api.iconify.design/mdi:shield-sync.svg?color=%23f59e0b" width="20" height="20" style="vertical-align: middle; margin-right: 6px;" alt="">
                加密使用趋势
            </h3>
            <canvas id="encryptTrendChart" height="250"></canvas>
        </div>
        <div class="chart-card">
            <h3>
                <img src="https://api.iconify.design/mdi:trophy.svg?color=%23fbbf24" width="20" height="20" style="vertical-align: middle; margin-right: 6px;" alt="">
                充值排行榜
            </h3>
            <div class="top-users-list" id="topUsersList">加载中...</div>
        </div>
    </div>
</div>

<style>
.stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}
.stat-card {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.stat-icon {
    font-size: 48px;
}
.stat-icon img {
    display: block;
}
.stat-info {
    flex: 1;
}
.stat-value {
    font-size: 28px;
    font-weight: 700;
    color: var(--primary-color);
}
.stat-label {
    font-size: 13px;
    color: var(--text-muted);
}
.stat-today {
    font-size: 12px;
    color: #10b981;
    margin-top: 5px;
}
.charts-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}
.chart-card {
    background: var(--bg-primary);
    border-radius: 16px;
    padding: 20px;
    border: 1px solid var(--border-color);
}
.chart-card h3 {
    margin-bottom: 20px;
    font-size: 16px;
}
.chart-card h3 img {
    display: inline-block;
}
.top-users-list {
    max-height: 300px;
    overflow-y: auto;
}
.top-user-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--border-color);
}
.top-user-item:last-child {
    border-bottom: none;
}
.top-user-name {
    font-weight: 500;
}
.top-user-amount {
    color: var(--primary-color);
    font-weight: 600;
}
@media (max-width: 768px) {
    .charts-row {
        grid-template-columns: 1fr;
    }
}
</style>

<script src="../assets/js/chart.umd.min.js"></script>
<script>
// 加载统计数据
async function loadStats() {
    try {
        const response = await fetch('/api/admin_stats.php?type=dashboard');
        const data = await response.json();
        if (data.success) {
            document.getElementById('total_users').innerText = data.data.total_users;
            document.getElementById('total_orders').innerText = data.data.total_orders;
            document.getElementById('total_amount').innerText = '¥' + data.data.total_amount;
            document.getElementById('total_encrypts').innerText = data.data.total_encrypts;
            document.getElementById('today_users').innerHTML = '今日新增: ' + data.data.today_users;
            document.getElementById('today_amount').innerHTML = '今日充值: ¥' + data.data.today_amount;
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 加载用户趋势
async function loadUserTrend() {
    try {
        const response = await fetch('/api/admin_stats.php?type=user_trend&days=30');
        const data = await response.json();
        if (data.success) {
            const labels = data.data.map(item => item.date);
            const counts = data.data.map(item => item.count);
            
            new Chart(document.getElementById('userTrendChart'), {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '累计用户数',
                        data: counts,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102,126,234,0.1)',
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { position: 'top' }
                    }
                }
            });
        }
    } catch (error) {
        console.error('加载用户趋势失败:', error);
    }
}

// 加载充值趋势
async function loadRechargeTrend() {
    try {
        const response = await fetch('/api/admin_stats.php?type=recharge_trend&days=30');
        const data = await response.json();
        if (data.success) {
            const labels = data.data.map(item => item.date);
            const amounts = data.data.map(item => parseFloat(item.amount));
            
            new Chart(document.getElementById('rechargeTrendChart'), {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '充值金额 (¥)',
                        data: amounts,
                        backgroundColor: '#10b981',
                        borderRadius: 8
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { position: 'top' }
                    }
                }
            });
        }
    } catch (error) {
        console.error('加载充值趋势失败:', error);
    }
}

// 加载加密趋势
async function loadEncryptTrend() {
    try {
        const response = await fetch('/api/admin_stats.php?type=encrypt_trend&days=30');
        const data = await response.json();
        if (data.success) {
            const labels = data.data.map(item => item.date);
            const counts = data.data.map(item => item.count);
            
            new Chart(document.getElementById('encryptTrendChart'), {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: '加密次数',
                        data: counts,
                        borderColor: '#f59e0b',
                        backgroundColor: 'rgba(245,158,11,0.1)',
                        fill: true,
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: true,
                    plugins: {
                        legend: { position: 'top' }
                    }
                }
            });
        }
    } catch (error) {
        console.error('加载加密趋势失败:', error);
    }
}

// 加载充值排行榜
async function loadTopUsers() {
    try {
        const response = await fetch('/api/admin_stats.php?type=top_users');
        const data = await response.json();
        if (data.success && data.data.length > 0) {
            let html = '';
            data.data.forEach((user, index) => {
                html += `
                    <div class="top-user-item">
                        <div>
                            <span style="display: inline-block; width: 30px;">${index + 1}</span>
                            <span class="top-user-name">${escapeHtml(user.username)}</span>
                            <span style="font-size: 12px; color: var(--text-muted);">(${escapeHtml(user.email)})</span>
                        </div>
                        <div class="top-user-amount">¥${parseFloat(user.total).toFixed(2)}</div>
                    </div>
                `;
            });
            document.getElementById('topUsersList').innerHTML = html;
        } else {
            document.getElementById('topUsersList').innerHTML = '<div style="text-align: center; padding: 40px; color: var(--text-muted);">暂无数据</div>';
        }
    } catch (error) {
        console.error('加载排行榜失败:', error);
        document.getElementById('topUsersList').innerHTML = '<div style="text-align: center; padding: 40px; color: var(--text-muted);">加载失败</div>';
    }
}

function escapeHtml(text) {
    if (!text) return '';
    return text.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}

// 页面加载
loadStats();
loadUserTrend();
loadRechargeTrend();
loadEncryptTrend();
loadTopUsers();
</script>