<?php
require_once __DIR__ . '/../MPHX/common.php';
require_once __DIR__ . '/../MPHX/AuthManager.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$admin = is_admin_login();

// 获取当前版本号
$current_version = 'v1.1.2'; // 当前系统版本

// 获取统计数据
$bt_count = $DB->get_row("SELECT COUNT(*) as count FROM `bt`")['count'] ?? 0;
$zj_count = $DB->get_row("SELECT COUNT(*) as count FROM `zj`")['count'] ?? 0;
$log_count = $DB->get_row("SELECT COUNT(*) as count FROM `log`")['count'] ?? 0;

// 获取所有用户的充值金额统计（已支付订单）
$total_recharge = 0;

// 从 balance_orders 表统计
$balance_orders_exists = $DB->query("SHOW TABLES LIKE 'balance_orders'");
if ($balance_orders_exists && $DB->num_rows($balance_orders_exists) > 0) {
    $result = $DB->get_row("SELECT SUM(amount) as total FROM `balance_orders` WHERE status='paid' OR status='已支付'");
    if ($result && $result['total']) {
        $total_recharge += floatval($result['total']);
    }
}

// 从 orders 表统计
$orders_table_exists = $DB->query("SHOW TABLES LIKE 'orders'");
if ($orders_table_exists && $DB->num_rows($orders_table_exists) > 0) {
    $result = $DB->get_row("SELECT SUM(amount) as total FROM `orders` WHERE status='已支付' OR status='paid'");
    if ($result && $result['total']) {
        $total_recharge += floatval($result['total']);
    }
}

// 从 dd 表统计（旧订单表）
$dd_table_exists = $DB->query("SHOW TABLES LIKE 'dd'");
if ($dd_table_exists && $DB->num_rows($dd_table_exists) > 0) {
    $result = $DB->get_row("SELECT SUM(money) as total FROM `dd` WHERE zt='已支付' OR zt='paid'");
    if ($result && $result['total']) {
        $total_recharge += floatval($result['total']);
    }
}

// 获取用户地区分布统计
$user_region_stats = array();
$region_table_exists = $DB->query("SHOW TABLES LIKE 'user_login_region'");
if ($region_table_exists && $DB->num_rows($region_table_exists) > 0) {
    // 按地区统计用户数量
    $result = $DB->query("SELECT region, COUNT(DISTINCT user_id) as user_count FROM `user_login_region` WHERE region IS NOT NULL AND region != '' GROUP BY region ORDER BY user_count DESC");
    while ($row = $DB->fetch($result)) {
        $user_region_stats[] = array(
            'name' => $row['region'],
            'value' => intval($row['user_count'])
        );
    }
}

// 从远程获取公告 - 使用缓存，每5分钟更新一次
$announcement = '';
$fetch_error = '';
$auth_info = null;
$online_count = 0;

// 检查缓存文件
$cache_file = __DIR__ . '/../cache/sy_cache.json';
$cache_time = 60; // 1分钟缓存（授权信息需要更频繁更新）
$use_cache = false;

if (file_exists($cache_file) && (time() - filemtime($cache_file)) < $cache_time) {
    $cache_data = json_decode(file_get_contents($cache_file), true);
    if ($cache_data && isset($cache_data['announcement'])) {
        $announcement = $cache_data['announcement'];
        $online_count = $cache_data['online_count'] ?? 0;
        $auth_info = $cache_data['auth_info'] ?? null;
        $use_cache = true;
    }
}

// 如果没有缓存或缓存过期，异步更新
if (!$use_cache) {
    // 基础统计（不依赖远程API）
    $bt_count = $DB->get_row("SELECT COUNT(*) as count FROM `bt`")['count'] ?? 0;
    
    // 简单的在线检测（只检测第一个服务器作为参考）
    $first_bt = $DB->get_row("SELECT * FROM `bt` LIMIT 1");
    if ($first_bt) {
        try {
            $bt_api = new bt_api();
            $protocol = $first_bt['aqfw'] == 'true' ? 'https' : 'http';
            $bt_api->BT_PANEL = $protocol . '://' . $first_bt['ip'] . ':' . $first_bt['dk'];
            $bt_api->BT_KEY = $first_bt['key'];
            
            $system_info = $bt_api->GetPanelStatus(3);
            $system_data = json_decode($system_info, true);
            
            if ($system_data && isset($system_data['version'])) {
                // 假设如果第一个在线，大部分都在线
                $online_count = min($bt_count, max(1, intval($bt_count * 0.8)));
            }
        } catch (Exception $e) {
            $online_count = 0;
        }
    }
    
    // 尝试获取公告和授权信息（不阻塞页面加载）
    try {
        $authManager = new AuthManager($DB);
        // 强制验证模式，确保获取最新授权状态
        $token_result = $authManager->getToken(true);
        
        if ($token_result['code'] == 200) {
            $token = $token_result['data']['token'];
            $heartbeat = $authManager->heartbeat($token);
            
            if ($heartbeat['code'] == 200 && isset($heartbeat['data']['cloud']['announcements'])) {
                $announcements = [];
                foreach ($heartbeat['data']['cloud']['announcements'] as $ann) {
                    $announcements[] = $ann['content'] ?? '';
                }
                $announcement = implode("\n", array_filter($announcements));
            }
            
            // 同时查询详细授权信息，确保数据准确
            $auth_info_result = $authManager->getAuthInfo($token);
            if ($auth_info_result['code'] == 200) {
                $auth_data = $auth_info_result['data']['auth'] ?? [];
                $auth_info = [
                    'expire_time' => $auth_data['expire_time'] ?? $token_result['data']['expire_time'] ?? '',
                    'remain_seconds' => $auth_data['remain_seconds'] ?? $heartbeat['data']['remain_seconds'] ?? 0,
                    'is_trial' => $auth_data['is_trial'] ?? $token_result['data']['is_trial'] ?? true
                ];
            } else {
                $auth_info = [
                    'expire_time' => $token_result['data']['expire_time'] ?? '',
                    'remain_seconds' => $heartbeat['data']['remain_seconds'] ?? 0,
                    'is_trial' => $token_result['data']['is_trial'] ?? true
                ];
            }
        }
    } catch (Exception $e) {
        $fetch_error = '获取公告失败: ' . $e->getMessage();
    }
    
    // 保存缓存
    if (!is_dir(__DIR__ . '/../cache')) {
        mkdir(__DIR__ . '/../cache', 0755, true);
    }
    file_put_contents($cache_file, json_encode([
        'announcement' => $announcement,
        'online_count' => $online_count,
        'auth_info' => $auth_info,
        'time' => time()
    ]));
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>后台首页 - 宝塔主机管理系统</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/all.min.css">
    <link rel="stylesheet" href="css/style.css?v=2026040501">
</head>
<body>
    <div class="content-area">
        <div class="alert">
            <i class="fas fa-info-circle"></i> 欢迎使用MLEOE宝塔系统 | 系统版本: <?php echo $current_version; ?> | 当前时间: <?php echo date('Y-m-d H:i:s'); ?>
        </div>
        
        <div class="stats-grid">
            <div class="stat-card">
                <div class="icon">
                    <i class="fas fa-network-wired"></i>
                </div>
                <div class="stat-info">
                    <h4>宝塔服务器 (在线: <?php echo $online_count; ?>)</h4>
                    <div class="number"><?php echo $bt_count; ?></div>
                </div>
                <div class="progress">
                    <div class="progress-bar" style="width: 100%"></div>
                </div>
            </div>
            <div class="stat-card">
                <div class="icon">
                    <i class="fas fa-laptop"></i>
                </div>
                <div class="stat-info">
                    <h4>主机数量</h4>
                    <div class="number"><?php echo $zj_count; ?></div>
                </div>
                <div class="progress">
                    <div class="progress-bar" style="width: 100%"></div>
                </div>
            </div>
            <div class="stat-card">
                <div class="icon">
                    <i class="fas fa-yen-sign"></i>
                </div>
                <div class="stat-info">
                    <h4>充值金额</h4>
                    <div class="number">¥<?php echo number_format($total_recharge, 2); ?></div>
                </div>
                <div class="progress">
                    <div class="progress-bar" style="width: 100%"></div>
                </div>
            </div>
            <div class="stat-card">
                <div class="icon">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="stat-info">
                    <h4>操作日志</h4>
                    <div class="number"><?php echo $log_count; ?></div>
                </div>
                <div class="progress">
                    <div class="progress-bar" style="width: 100%"></div>
                </div>
            </div>
        </div>
        
        <div class="row" style="margin: 0 -10px;">
            <div class="col-md-6" style="padding: 0 10px;">
                <div class="card">
                    <h3><i class="fas fa-bullhorn"></i> 网站公告</h3>
                    <?php if (!empty($announcement)): ?>
                        <p style="color: #5f6368; font-size: 13px; line-height: 1.6;"><?php echo nl2br(htmlspecialchars($announcement)); ?></p>
                    <?php else: ?>
                        <p style="color: #999; font-size: 13px; line-height: 1.6;">
                            <i class="fas fa-exclamation-circle"></i> 
                            <?php echo !empty($fetch_error) ? $fetch_error : '暂无公告'; ?>
                        </p>
                    <?php endif; ?>
                </div>
            </div>
            <div class="col-md-6" style="padding: 0 10px;">
                <div class="card">
                    <h3><i class="fas fa-map-marked-alt"></i> 用户地区分布</h3>
                    <div id="userRegionMap" style="width: 100%; height: 300px;"></div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="/static/js/jquery.min.js"></script>
    <script src="/static/js/echarts.min.js"></script>
    <script>
    $(function() {
        // 用户地区分布数据
        var regionData = <?php echo json_encode($user_region_stats); ?>;
        
        // 初始化地图
        var chartDom = document.getElementById('userRegionMap');
        if (!chartDom) return;
        
        if (regionData.length === 0) {
            chartDom.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;"><i class="fas fa-info-circle" style="margin-right: 8px;"></i>暂无用户地区数据</div>';
            return;
        }
        
        // 加载中国地图 GeoJSON
        $.get('/static/js/china_map.json', function(geoJson) {
            echarts.registerMap('china', geoJson);
            
            var myChart = echarts.init(chartDom);
            
            // 省份名称映射 - 转换为ECharts地图需要的格式
            var nameMap = {
                '北京': '北京市', '天津': '天津市', '上海': '上海市', '重庆': '重庆市',
                '河北': '河北省', '山西': '山西省', '辽宁': '辽宁省', '吉林': '吉林省',
                '黑龙江': '黑龙江省', '江苏': '江苏省', '浙江': '浙江省', '安徽': '安徽省',
                '福建': '福建省', '江西': '江西省', '山东': '山东省', '河南': '河南省',
                '湖北': '湖北省', '湖南': '湖南省', '广东': '广东省', '海南': '海南省',
                '四川': '四川省', '贵州': '贵州省', '云南': '云南省', '陕西': '陕西省',
                '甘肃': '甘肃省', '青海': '青海省', '台湾': '台湾省',
                '内蒙古': '内蒙古自治区', '广西': '广西壮族自治区', '西藏': '西藏自治区', 
                '宁夏': '宁夏回族自治区', '新疆': '新疆维吾尔自治区',
                '香港': '香港特别行政区', '澳门': '澳门特别行政区'
            };
            
            // 鲜艳的颜色数组
            var brightColors = [
                '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
                '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
                '#F8B500', '#00CED1', '#FF7F50', '#9370DB', '#20B2AA',
                '#FF69B4', '#00FA9A', '#FFD700', '#1E90FF', '#FF4500'
            ];
            
            // 处理数据
            var processedData = [];
            var colorIndex = 0;
            
            if (regionData && regionData.length > 0) {
                regionData.forEach(function(item) {
                    if (item && item.value > 0) {
                        var mappedName = nameMap[item.name] || item.name;
                        var color = brightColors[colorIndex % brightColors.length];
                        colorIndex++;
                        processedData.push({
                            name: mappedName,
                            value: item.value,
                            itemStyle: { 
                                areaColor: color,
                                borderColor: '#fff',
                                borderWidth: 1
                            }
                        });
                    }
                });
            }
            
            var option = {
                tooltip: {
                    trigger: 'item',
                    backgroundColor: 'rgba(255,255,255,0.95)',
                    borderColor: '#eee',
                    borderWidth: 1,
                    textStyle: { color: '#333' },
                    formatter: function(params) {
                        if (params.value) {
                            return '<b>' + params.name + '</b><br/>用户数: ' + params.value;
                        }
                        return params.name;
                    }
                },
                series: [{
                    name: '用户分布',
                    type: 'map',
                    map: 'china',
                    roam: true,
                    zoom: 1.1,
                    center: [104, 37],
                    scaleLimit: { min: 1, max: 5 },
                    selectedMode: false,
                    label: { show: false },
                    emphasis: { 
                        disabled: false,
                        label: { show: true, fontSize: 12, color: '#333' }, 
                        itemStyle: { 
                            areaColor: '#FFE082',
                            borderColor: '#FFA000',
                            borderWidth: 1
                        } 
                    },
                    itemStyle: { 
                        areaColor: '#f3f3f3', 
                        borderColor: '#ddd', 
                        borderWidth: 0.5 
                    },
                    data: processedData
                }]
            };
            
            myChart.setOption(option);
            
            // 响应式
            window.addEventListener('resize', function() {
                myChart.resize();
            });
        }).fail(function() {
            chartDom.innerHTML = '<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;"><i class="fas fa-exclamation-circle" style="margin-right: 8px;"></i>地图加载失败</div>';
        });
    });
    </script>
</body>
</html>
