<?php
/**
 * 卫巾纸薄 B 站数据分析平台 - 纯 PHP 版本
 * 单文件部署版本，无需后端服务和数据库
 *
 * 使用方法：
 * 1. 修改下方的 API_KEY 配置
 * 2. 将本文件上传到 PHP 服务器
 * 3. 访问 index.php 即可
 */

// ============ 配置部分 ============
const API_KEY = 'your_uapis_cn_api_key'; // 从 https://uapis.cn 获取
const UP_MID = 108054533; // B 站 UP 主 ID
const CACHE_DIR = '/tmp/bilibili_cache';
const CACHE_TIME = 3600; // 缓存时间（秒）

// ============ 功能函数 ============

/**
 * 调用 uapis.cn API
 */
function callBilibiliAPI($endpoint, $params = []) {
    $params['key'] = uapi-yjukqvkpSpVBa-Y1dt7qGo0brlXiAGaLSYXyIYWx;
    $url = "https://api.uapis.cn/bilibili/archive/search?mid=" . UP_MID;

    foreach ($params as $key => $value) {
        $url .= "&" . urlencode($key) . "=" . urlencode($value);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode === 200) {
        return json_decode($response, true);
    }

    return null;
}

/**
 * 获取缓存数据
 */
function getCache($key) {
    if (!is_dir(CACHE_DIR)) {
        mkdir(CACHE_DIR, 0755, true);
    }

    $file = CACHE_DIR . '/' . $key . '.json';

    if (file_exists($file)) {
        $mtime = filemtime($file);
        if (time() - $mtime < CACHE_TIME) {
            $data = file_get_contents($file);
            return json_decode($data, true);
        }
    }

    return null;
}

/**
 * 保存缓存数据
 */
function setCache($key, $data) {
    if (!is_dir(CACHE_DIR)) {
        mkdir(CACHE_DIR, 0755, true);
    }

    $file = CACHE_DIR . '/' . $key . '.json';
    file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

/**
 * 获取视频列表
 */
function getVideos() {
    $cacheKey = 'videos_' . date('Y-m-d-H');
    $cached = getCache($cacheKey);

    if ($cached !== null) {
        return $cached;
    }

    $result = callBilibiliAPI('search', ['page' => 1, 'pageSize' => 30]);

    if ($result && isset($result['data']['list'])) {
        $videos = array_map(function($item) {
            return [
                'aid' => $item['aid'] ?? 0,
                'bvid' => $item['bvid'] ?? '',
                'title' => $item['title'] ?? '未知视频',
                'cover' => $item['pic'] ?? '',
                'description' => $item['description'] ?? '',
                'pubdate' => ($item['pubdate'] ?? 0) * 1000,
                'duration' => $item['duration'] ?? 0,
                'stat' => [
                    'view' => $item['play'] ?? 0,
                    'like' => $item['like'] ?? 0,
                    'coin' => $item['coin'] ?? 0,
                    'favorite' => $item['favorite'] ?? 0,
                    'reply' => $item['dm'] ?? 0,
                ]
            ];
        }, $result['data']['list']);

        setCache($cacheKey, $videos);
        return $videos;
    }

    return [];
}

/**
 * 计算统计数据
 */
function getStats($videos) {
    $totalViews = 0;
    $totalLikes = 0;
    $totalCoins = 0;
    $totalFavorites = 0;
    $totalComments = 0;

    foreach ($videos as $video) {
        $stat = $video['stat'] ?? [];
        $totalViews += $stat['view'] ?? 0;
        $totalLikes += $stat['like'] ?? 0;
        $totalCoins += $stat['coin'] ?? 0;
        $totalFavorites += $stat['favorite'] ?? 0;
        $totalComments += $stat['reply'] ?? 0;
    }

    return [
        'totalVideos' => count($videos),
        'totalViews' => $totalViews,
        'totalLikes' => $totalLikes,
        'totalCoins' => $totalCoins,
        'totalFavorites' => $totalFavorites,
        'totalComments' => $totalComments,
        'avgViewsPerVideo' => count($videos) > 0 ? round($totalViews / count($videos)) : 0,
    ];
}

/**
 * 格式化数字（显示为万/百万等）
 */
function formatNumber($num) {
    if ($num >= 1000000) {
        return round($num / 1000000, 1) . 'M';
    } elseif ($num >= 10000) {
        return round($num / 10000, 1) . '万';
    } elseif ($num >= 1000) {
        return round($num / 1000, 1) . 'K';
    }
    return $num;
}

// ============ 路由处理 ============

$action = $_GET['action'] ?? 'home';
header('Content-Type: application/json; charset=utf-8');

switch ($action) {
    case 'api_videos':
        $videos = getVideos();
        echo json_encode($videos, JSON_UNESCAPED_UNICODE);
        exit;

    case 'api_stats':
        $videos = getVideos();
        $stats = getStats($videos);
        echo json_encode($stats, JSON_UNESCAPED_UNICODE);
        exit;

    default:
        header('Content-Type: text/html; charset=utf-8');
        break;
}

// ============ 获取数据 ============
$videos = getVideos();
$stats = getStats($videos);
$lastUpdate = date('Y-m-d H:i:s');

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>卫巾纸薄 - B站数据分析平台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.js"></script>
    <style>
        .stat-card {
            @apply bg-white rounded-lg shadow p-6 hover:shadow-lg transition;
        }
        .video-card {
            @apply bg-white rounded-lg overflow-hidden shadow hover:shadow-lg transition hover:scale-105;
        }
        .fade-in {
            animation: fadeIn 0.3s ease-in;
        }
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Header -->
    <nav class="bg-white shadow">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center gap-2">
                    <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                    </svg>
                    <h1 class="text-xl font-bold">卫巾纸薄 - 数据分析平台</h1>
                </div>
                <div class="text-sm text-gray-600">
                    最后更新: <?php echo $lastUpdate; ?>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Stats Section -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8 fade-in">
            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">总视频数</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo $stats['totalVideos']; ?></p>
                    </div>
                    <svg class="w-12 h-12 text-blue-600 opacity-20" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M2 11a1 1 0 011-1h2a1 1 0 011 1v5a1 1 0 01-1 1H3a1 1 0 01-1-1v-5zM8 7a1 1 0 011-1h2a1 1 0 011 1v9a1 1 0 01-1 1H9a1 1 0 01-1-1V7zM14 4a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1h-2a1 1 0 01-1-1V4z"></path>
                    </svg>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">总播放量</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo formatNumber($stats['totalViews']); ?></p>
                    </div>
                    <svg class="w-12 h-12 text-green-600 opacity-20" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3.293 1.707a1 1 0 011.414 0L10 9.414l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"></path>
                    </svg>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">总评论数</p>
                        <p class="text-3xl font-bold text-purple-600"><?php echo formatNumber($stats['totalComments']); ?></p>
                    </div>
                    <svg class="w-12 h-12 text-purple-600 opacity-20" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5z"></path>
                    </svg>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-600 text-sm">总点赞数</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo formatNumber($stats['totalLikes']); ?></p>
                    </div>
                    <svg class="w-12 h-12 text-red-600 opacity-20" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M9.172 15.172a4 4 0 005.656 0m0-5.656a4 4 0 00-5.656 0m7.072-7.072a8 8 0 11-11.314 0m5.656 5.656a6 6 0 11-8.485 0"></path>
                    </svg>
                </div>
            </div>
        </div>

        <!-- Videos Grid -->
        <div class="mb-8">
            <h2 class="text-2xl font-bold mb-6">视频列表</h2>

            <?php if (empty($videos)): ?>
                <div class="text-center py-12">
                    <p class="text-gray-500 mb-4">暂无视频数据</p>
                    <p class="text-sm text-gray-400">请确保 API_KEY 已正确配置</p>
                </div>
            <?php else: ?>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 fade-in">
                    <?php foreach ($videos as $index => $video): ?>
                        <div class="video-card" style="animation-delay: <?php echo $index * 0.05; ?>s">
                            <!-- 视频封面 -->
                            <div class="relative bg-gray-200 h-40 overflow-hidden">
                                <?php if (!empty($video['cover'])): ?>
                                    <img src="<?php echo htmlspecialchars($video['cover']); ?>"
                                         alt="<?php echo htmlspecialchars($video['title']); ?>"
                                         class="w-full h-full object-cover"
                                         onerror="this.style.display='none'">
                                <?php endif; ?>
                                <div class="absolute inset-0 bg-gradient-to-t from-black to-transparent opacity-0 hover:opacity-60 transition flex items-end justify-center pb-4">
                                    <span class="text-white font-semibold">查看详情</span>
                                </div>
                            </div>

                            <!-- 视频信息 -->
                            <div class="p-4">
                                <h3 class="font-semibold text-sm mb-3 line-clamp-2 h-10">
                                    <?php echo htmlspecialchars($video['title']); ?>
                                </h3>

                                <!-- 统计数据 -->
                                <div class="space-y-2 text-xs text-gray-600 mb-3">
                                    <div class="flex items-center gap-2">
                                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                            <path d="M10 12a2 2 0 100-4 2 2 0 000 4z"></path>
                                            <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd"></path>
                                        </svg>
                                        <span><?php echo formatNumber($video['stat']['view']); ?> 播放</span>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                            <path d="M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5z"></path>
                                        </svg>
                                        <span><?php echo formatNumber($video['stat']['reply']); ?> 评论</span>
                                    </div>
                                </div>

                                <!-- 互动数据 -->
                                <div class="flex gap-3 pt-3 border-t text-xs">
                                    <span class="flex items-center gap-1 flex-1">
                                        <svg class="w-3 h-3 text-blue-500" fill="currentColor" viewBox="0 0 20 20">
                                            <path d="M2 10.5a1.5 1.5 0 113 0v-1a1.5 1.5 0 01-3 0v1z"></path>
                                            <path fill-rule="evenodd" d="M14 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89-3.476l2.817 2.817A1 1 0 0015 8H2z" clip-rule="evenodd"></path>
                                        </svg>
                                        <?php echo formatNumber($video['stat']['like']); ?>
                                    </span>
                                    <span class="flex items-center gap-1 flex-1">
                                        <svg class="w-3 h-3 text-yellow-500" fill="currentColor" viewBox="0 0 20 20">
                                            <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"></path>
                                        </svg>
                                        <?php echo formatNumber($video['stat']['coin']); ?>
                                    </span>
                                    <span class="flex items-center gap-1 flex-1">
                                        <svg class="w-3 h-3 text-red-500" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" clip-rule="evenodd"></path>
                                        </svg>
                                        <?php echo formatNumber($video['stat']['favorite']); ?>
                                    </span>
                                </div>

                                <!-- 发布时间 -->
                                <div class="mt-3 pt-3 border-t text-xs text-gray-500">
                                    发布: <?php echo date('Y-m-d', $video['pubdate'] / 1000); ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- Footer -->
        <footer class="bg-white rounded-lg shadow p-6 mt-8 text-center text-gray-600 text-sm">
            <p>卫巾纸薄 B 站数据分析平台 • PHP 单文件版本</p>
            <p class="mt-2">数据通过 <a href="https://uapis.cn" class="text-blue-600 hover:underline">uapis.cn API</a> 获取 • 实时更新</p>
        </footer>
    </div>

    <!-- JavaScript for refresh and interactivity -->
    <script>
        // 自动刷新数据（每小时）
        setInterval(function() {
            location.reload();
        }, 3600000);

        // 添加点击效果
        document.querySelectorAll('.video-card').forEach(card => {
            card.addEventListener('click', function(e) {
                if (e.target.closest('.video-card')) {
                    // 在新标签页打开 B 站视频
                    const aid = this.dataset.aid;
                    if (aid) {
                        window.open('https://www.bilibili.com/video/av' + aid);
                    }
                }
            });
        });
    </script>
</body>
</html>
