<?php
/**
 * 流量监控
**/
include("../includes/common.php");
$title='流量监控';
include './head.php';

if($islogin==1){
}else exit("<script language='javascript'>window.location.href='./login.php';</script>");

// 获取时间范围
$days = isset($_GET['days']) ? intval($_GET['days']) : 7;
$days = max(1, min(30, $days));

// 获取统计数据
$date_start = date('Y-m-d', strtotime("-{$days} days"));

// 每日流量统计
$daily_stats = [];
for($i=$days-1; $i>=0; $i--){
    $date = date('Y-m-d', strtotime("-{$i} days"));
    $upload = $DB->getColumn("SELECT SUM(size) FROM pre_file WHERE addtime LIKE '{$date}%'");
    $download = $DB->getColumn("SELECT SUM(traffic_size) FROM pre_traffic_log WHERE access_type='download' AND created_at LIKE '{$date}%'");
    $daily_stats[] = [
        'date' => $date,
        'upload' => $upload ?: 0,
        'download' => $download ?: 0
    ];
}

// 今日统计
$today = date('Y-m-d');
$today_upload = $DB->getColumn("SELECT SUM(size) FROM pre_file WHERE addtime LIKE '{$today}%'");
$today_download = $DB->getColumn("SELECT SUM(traffic_size) FROM pre_traffic_log WHERE access_type='download' AND created_at LIKE '{$today}%'");

// 总统计
$total_upload = $DB->getColumn("SELECT SUM(size) FROM pre_file");
$total_download = $DB->getColumn("SELECT SUM(traffic_size) FROM pre_traffic_log WHERE access_type='download'");
$total_files = $DB->getColumn("SELECT COUNT(*) FROM pre_file");
$total_users = $DB->getColumn("SELECT COUNT(*) FROM pre_user");

// 格式化文件大小
function formatBytes($bytes){
    $bytes = intval($bytes);
    if($bytes >= 1073741824) return round($bytes / 1073741824, 2) . ' GB';
    if($bytes >= 1048576) return round($bytes / 1048576, 2) . ' MB';
    if($bytes >= 1024) return round($bytes / 1024, 2) . ' KB';
    if($bytes > 0) return $bytes . ' B';
    return '0 B';
}

// 获取下载排行
$download_top = $DB->query("SELECT f.name, f.hash, f.size, COUNT(d.id) as download_count, SUM(d.traffic_size) as total_size 
    FROM pre_file f 
    LEFT JOIN pre_traffic_log d ON f.hash=d.file_hash AND d.access_type='download' AND d.created_at>='{$date_start}'
    GROUP BY f.hash, f.name, f.size
    HAVING download_count > 0
    ORDER BY download_count DESC 
    LIMIT 10");
if($download_top === false) $download_top = [];

// 获取用户排行
$user_top = $DB->query("SELECT u.uid, u.username, u.nickname, COUNT(f.id) as file_count, SUM(f.size) as total_size 
    FROM pre_user u 
    LEFT JOIN pre_file f ON u.uid=f.uid AND f.addtime>='{$date_start} 00:00:00'
    GROUP BY u.uid, u.username, u.nickname
    HAVING file_count > 0
    ORDER BY file_count DESC 
    LIMIT 10");
if($user_top === false) $user_top = [];
?>
<div class="container">
    <!-- 页面标题 -->
    <div class="page-header-section">
        <div class="page-title">
            <div class="page-title-icon"><i class="fa fa-bar-chart"></i></div>
            <h1>流量监控</h1>
        </div>
        <div class="page-actions">
            <div class="filter-group" style="margin: 0;">
                <select class="form-control" onchange="location.href='?days='+this.value" style="min-width: 120px;">
                    <option value="7" <?php echo $days==7?'selected':''; ?>>最近7天</option>
                    <option value="14" <?php echo $days==14?'selected':''; ?>>最近14天</option>
                    <option value="30" <?php echo $days==30?'selected':''; ?>>最近30天</option>
                </select>
            </div>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon blue">
                    <i class="fa fa-upload"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo formatBytes($today_upload); ?></div>
                    <div class="stat-label">今日上传</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon green">
                    <i class="fa fa-download"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo formatBytes($today_download); ?></div>
                    <div class="stat-label">今日下载</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon orange">
                    <i class="fa fa-hdd-o"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo formatBytes($total_upload); ?></div>
                    <div class="stat-label">总上传量</div>
                </div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-card-header">
                <div class="stat-icon red">
                    <i class="fa fa-exchange"></i>
                </div>
                <div class="stat-info">
                    <div class="stat-num"><?php echo formatBytes($total_download); ?></div>
                    <div class="stat-label">总下载量</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-row">
        <div class="chart-card">
            <h4><i class="fa fa-area-chart"></i> 流量趋势</h4>
            <div class="chart-container">
                <canvas id="trafficChart"></canvas>
            </div>
        </div>
        <div class="chart-card">
            <h4><i class="fa fa-pie-chart"></i> 流量占比</h4>
            <div class="chart-container">
                <canvas id="pieChart"></canvas>
            </div>
        </div>
    </div>

    <!-- 排行区域 -->
    <div class="chart-row">
        <div class="chart-card">
            <h4><i class="fa fa-fire"></i> 热门文件排行 TOP10</h4>
            <div class="table-container" style="margin-top: 15px;">
                <table class="data-table" style="min-width: auto;">
                    <thead>
                        <tr>
                            <th style="width: 50px;">排名</th>
                            <th>文件名</th>
                            <th style="width: 100px;">大小</th>
                            <th style="width: 100px;">下载次数</th>
                            <th style="width: 100px;">总流量</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $rank = 1;
                        $has_download_data = false;
                        if($download_top && !$download_top->rowCount()): 
                        ?>
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 40px; color: #9ca3af;">
                                <i class="fa fa-inbox" style="font-size: 32px; margin-bottom: 10px; display: block;"></i>
                                暂无下载记录
                            </td>
                        </tr>
                        <?php 
                        elseif($download_top):
                            while($row = $download_top->fetch()): 
                                $has_download_data = true;
                        ?>
                        <tr>
                            <td style="text-align: center;">
                                <?php if($rank<=3): ?>
                                <span style="display: inline-block; width: 24px; height: 24px; line-height: 24px; border-radius: 50%; background: <?php echo $rank==1?'#f59e0b':($rank==2?'#9ca3af':'#b45309'); ?>; color: #fff; font-weight: 600; font-size: 12px;"><?php echo $rank; ?></span>
                                <?php else: ?>
                                <span style="color: #9ca3af;"><?php echo $rank; ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="file-name" style="max-width: 200px;">
                                    <a href="<?php echo $row['hash'].'.'.(pathinfo($row['name'], PATHINFO_EXTENSION)?:'file'); ?>" target="_blank">
                                        <?php echo htmlspecialchars($row['name']); ?>
                                    </a>
                                </div>
                            </td>
                            <td class="col-size"><?php echo formatBytes($row['size']); ?></td>
                            <td><?php echo $row['download_count'] ?: 0; ?></td>
                            <td class="col-size"><?php echo formatBytes($row['total_size'] ?: 0); ?></td>
                        </tr>
                        <?php 
                            $rank++;
                            endwhile;
                            if(!$has_download_data):
                        ?>
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 40px; color: #9ca3af;">
                                <i class="fa fa-inbox" style="font-size: 32px; margin-bottom: 10px; display: block;"></i>
                                暂无下载记录
                            </td>
                        </tr>
                        <?php endif; ?>
                        <?php else: ?>
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 40px; color: #9ca3af;">
                                <i class="fa fa-inbox" style="font-size: 32px; margin-bottom: 10px; display: block;"></i>
                                暂无下载记录
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="chart-card">
            <h4><i class="fa fa-users"></i> 活跃用户排行 TOP10</h4>
            <div class="table-container" style="margin-top: 15px;">
                <table class="data-table" style="min-width: auto;">
                    <thead>
                        <tr>
                            <th style="width: 50px;">排名</th>
                            <th>用户</th>
                            <th style="width: 100px;">文件数</th>
                            <th style="width: 100px;">总大小</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $rank = 1;
                        $has_user_data = false;
                        if($user_top && !$user_top->rowCount()): 
                        ?>
                        <tr>
                            <td colspan="4" style="text-align: center; padding: 40px; color: #9ca3af;">
                                <i class="fa fa-inbox" style="font-size: 32px; margin-bottom: 10px; display: block;"></i>
                                暂无用户记录
                            </td>
                        </tr>
                        <?php 
                        elseif($user_top):
                            while($row = $user_top->fetch()): 
                                $has_user_data = true;
                        ?>
                        <tr>
                            <td style="text-align: center;">
                                <?php if($rank<=3): ?>
                                <span style="display: inline-block; width: 24px; height: 24px; line-height: 24px; border-radius: 50%; background: <?php echo $rank==1?'#f59e0b':($rank==2?'#9ca3af':'#b45309'); ?>; color: #fff; font-weight: 600; font-size: 12px;"><?php echo $rank; ?></span>
                                <?php else: ?>
                                <span style="color: #9ca3af;"><?php echo $rank; ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="user-info">
                                    <div class="user-avatar" style="width: 28px; height: 28px; font-size: 12px;">
                                        <?php echo strtoupper(substr($row['nickname']?:$row['username'], 0, 1)); ?>
                                    </div>
                                    <div class="user-details">
                                        <div class="user-name" style="font-size: 13px;"><?php echo htmlspecialchars($row['nickname']?:$row['username']); ?></div>
                                        <div class="user-login" style="font-size: 11px;">UID: <?php echo $row['uid']; ?></div>
                                    </div>
                                </div>
                            </td>
                            <td><?php echo $row['file_count'] ?: 0; ?></td>
                            <td class="col-size"><?php echo formatBytes($row['total_size'] ?: 0); ?></td>
                        </tr>
                        <?php 
                            $rank++;
                            endwhile;
                            if(!$has_user_data):
                        ?>
                        <tr>
                            <td colspan="4" style="text-align: center; padding: 40px; color: #9ca3af;">
                                <i class="fa fa-inbox" style="font-size: 32px; margin-bottom: 10px; display: block;"></i>
                                暂无用户记录
                            </td>
                        </tr>
                        <?php endif; ?>
                        <?php else: ?>
                        <tr>
                            <td colspan="4" style="text-align: center; padding: 40px; color: #9ca3af;">
                                <i class="fa fa-inbox" style="font-size: 32px; margin-bottom: 10px; display: block;"></i>
                                暂无用户记录
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// 流量趋势图
var trafficCtx = document.getElementById('trafficChart').getContext('2d');
var trafficChart = new Chart(trafficCtx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_column($daily_stats, 'date')); ?>,
        datasets: [{
            label: '上传流量 (MB)',
            data: <?php echo json_encode(array_map(function($item){ return round($item['upload']/1048576, 2); }, $daily_stats)); ?>,
            borderColor: '#0d9488',
            backgroundColor: 'rgba(13, 148, 136, 0.1)',
            borderWidth: 2,
            fill: true,
            tension: 0.4
        }, {
            label: '下载流量 (MB)',
            data: <?php echo json_encode(array_map(function($item){ return round($item['download']/1048576, 2); }, $daily_stats)); ?>,
            borderColor: '#3b82f6',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            borderWidth: 2,
            fill: true,
            tension: 0.4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top',
                labels: {
                    usePointStyle: true,
                    padding: 20
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    color: 'rgba(0, 0, 0, 0.05)'
                }
            },
            x: {
                grid: {
                    display: false
                }
            }
        }
    }
});

// 流量占比图
var pieCtx = document.getElementById('pieChart').getContext('2d');
var pieChart = new Chart(pieCtx, {
    type: 'doughnut',
    data: {
        labels: ['上传流量', '下载流量'],
        datasets: [{
            data: [<?php echo $total_upload ?: 0; ?>, <?php echo $total_download ?: 0; ?>],
            backgroundColor: ['#0d9488', '#3b82f6'],
            borderWidth: 0
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '60%',
        plugins: {
            legend: {
                position: 'bottom',
                labels: {
                    usePointStyle: true,
                    padding: 20
                }
            }
        }
    }
});
</script>

</body>
</html>
