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

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

$admin = is_admin_login();

// 获取统计数据
$bt_count = $DB->count("SELECT COUNT(*) FROM `bt`");
$online_count = $DB->count("SELECT COUNT(*) FROM `bt` WHERE `jkkg`='true'");
$offline_count = $DB->count("SELECT COUNT(*) FROM `bt` WHERE `jkkg`!='true'");

$normal_count = $DB->count("SELECT COUNT(*) FROM `zj` WHERE `zt`='正常'");
$expired_count = $DB->count("SELECT COUNT(*) FROM `zj` WHERE `zt`='已过期'");
$disabled_count = $DB->count("SELECT COUNT(*) FROM `zj` WHERE `zt`='已禁用'");
$paused_count = $DB->count("SELECT COUNT(*) FROM `zj` WHERE `zt`='已暂停'");
$total_hosts = $normal_count + $expired_count + $disabled_count + $paused_count;

// 获取当前协议（http 或 https）
// 支持多种方式检测HTTPS：HTTPS变量、HTTP_X_FORWARDED_PROTO、HTTP_X_FORWARDED_SSL
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
    $protocol = 'https';
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
    $protocol = 'https';
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on') {
    $protocol = 'https';
} else {
    $protocol = 'http';
}

// 获取宝塔服务器列表
$bts = $DB->query("SELECT * FROM `bt` ORDER BY `id` DESC");
?>
<!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">
    <style>
        .monitor-card {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 1px 2px rgba(60,64,67,0.1);
        }
        .monitor-card h3 {
            color: #202124;
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 16px;
            display: flex;
            align-items: center;
        }
        .monitor-card h3 i {
            margin-right: 8px;
            color: #1a73e8;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(8, 1fr);
            gap: 12px;
            margin-bottom: 20px;
        }
        @media (max-width: 1400px) {
            .stats-grid {
                grid-template-columns: repeat(4, 1fr);
            }
        }
        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        .stat-item {
            background: #fff;
            border-radius: 8px;
            padding: 12px 8px;
            text-align: center;
            box-shadow: 0 1px 2px rgba(60,64,67,0.1);
            border: 1px solid #e8eaed;
            min-width: 0;
        }
        .stat-item .number {
            font-size: 28px;
            font-weight: 600;
            color: #202124;
            margin-bottom: 4px;
        }
        .stat-item .label {
            font-size: 13px;
            color: #5f6368;
        }
        .stat-item.success .number {
            color: #188038;
        }
        .stat-item.warning .number {
            color: #f9ab00;
        }
        .stat-item.danger .number {
            color: #d93025;
        }
        .stat-item.info .number {
            color: #1a73e8;
        }
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-badge.online {
            background: #e6f4ea;
            color: #188038;
        }
        .status-badge.offline {
            background: #fce8e8;
            color: #d93025;
        }
        .status-badge i {
            margin-right: 4px;
            font-size: 8px;
        }
        .code-block {
            background: #f1f3f4;
            border-radius: 4px;
            padding: 12px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            color: #202124;
            overflow-x: auto;
            margin: 8px 0;
            position: relative;
        }
        .copy-btn {
            background: #1a73e8;
            color: #fff;
            border: none;
            border-radius: 4px;
            padding: 4px 12px;
            font-size: 11px;
            cursor: pointer;
            transition: background 0.2s;
            margin-top: 8px;
        }
        .copy-btn:hover {
            background: #1557b0;
        }
        .copy-btn.copied {
            background: #188038;
        }
        .task-item {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 16px;
            margin-bottom: 12px;
        }
        .task-item h5 {
            color: #202124;
            font-size: 14px;
            margin-bottom: 8px;
        }
        .task-item p {
            color: #5f6368;
            font-size: 13px;
            margin-bottom: 8px;
        }
        .task-item code {
            background: #e8eaed;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="content-area">
        <div class="alert">
            <i class="fas fa-info-circle"></i> 
            <strong>系统监控</strong> | 实时监控服务器状态和主机统计信息
        </div>

        <!-- 任务执行状态 -->
        <div class="monitor-card">
            <h3><i class="fas fa-tasks"></i> 任务执行状态</h3>
            <div class="stats-grid">
                <?php
                // 获取所有监控任务统计
                $cron_stats = array();
                $stats_res = $DB->query("SELECT * FROM `cron_monitor_stats` ORDER BY FIELD(task_type, 'web', 'sql', 'fh', 'fhq', 'cleanup')");
                while ($stat = $DB->fetch($stats_res)) {
                    $cron_stats[$stat['task_type']] = $stat;
                }
                
                $task_info = array(
                    'web' => array('name' => '空间监控', 'icon' => 'fa-hdd', 'color' => '#1a73e8'),
                    'sql' => array('name' => '数据库监控', 'icon' => 'fa-database', 'color' => '#1a73e8'),
                    'fh' => array('name' => '流量监控', 'icon' => 'fa-chart-line', 'color' => '#1a73e8'),
                    'fhq' => array('name' => '流量清零', 'icon' => 'fa-redo', 'color' => '#1a73e8'),
                    'cleanup' => array('name' => '临时文件清理', 'icon' => 'fa-broom', 'color' => '#1a73e8'),
                    'stop_expire' => array('name' => '到期自动停止', 'icon' => 'fa-stop-circle', 'color' => '#1a73e8'),
                    'delete_expire' => array('name' => '到期自动删除', 'icon' => 'fa-trash-alt', 'color' => '#1a73e8'),
                    'all' => array('name' => '全部监控任务', 'icon' => 'fa-layer-group', 'color' => '#1a73e8')
                );
                
                foreach ($task_info as $type => $info):
                    $stat = isset($cron_stats[$type]) ? $cron_stats[$type] : array('total_count' => 0, 'success_count' => 0, 'fail_count' => 0, 'last_run_time' => null, 'last_run_status' => null);
                    $is_success = $stat['last_run_status'] == 'success';
                    $status_class = $is_success ? 'success' : ($stat['last_run_status'] ? 'danger' : 'secondary');
                    $status_text = $is_success ? '正常' : ($stat['last_run_status'] ? '异常' : '未执行');
                ?>
                <div class="stat-item" style="border-top: 3px solid <?php echo $info['color']; ?>;">
                    <div style="font-size: 24px; color: <?php echo $info['color']; ?>; margin-bottom: 6px;">
                        <i class="fas <?php echo $info['icon']; ?>"></i>
                    </div>
                    <div class="label" style="font-size: 12px; font-weight: 600; color: #202124; margin-bottom: 6px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;"><?php echo $info['name']; ?></div>
                    <div class="number" style="font-size: 22px; margin-bottom: 6px;"><?php echo $stat['total_count']; ?></div>
                    <div style="margin-bottom: 6px;">
                        <span class="badge badge-<?php echo $status_class; ?>" style="font-size: 10px; padding: 3px 8px;">
                            <i class="fas fa-circle" style="font-size: 5px; margin-right: 2px;"></i><?php echo $status_text; ?>
                        </span>
                    </div>
                    <?php if ($stat['last_run_time']): ?>
                    <div style="font-size: 10px; color: #80868b;">
                        <?php echo date('m-d H:i', strtotime($stat['last_run_time'])); ?>
                    </div>
                    <?php else: ?>
                    <div style="font-size: 10px; color: #80868b;">
                        未执行
                    </div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- 监控脚本配置 -->
        <div class="monitor-card">
            <h3><i class="fas fa-clock"></i> 定时任务配置</h3>
            <p style="color: #5f6368; font-size: 13px; margin-bottom: 16px;">
                在宝塔面板中添加定时任务，执行以下命令进行系统监控：
            </p>
            
            <div class="row" style="margin: 0 -10px;">
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item">
                        <h5><i class="fas fa-hdd"></i> 空间监控</h5>
                        <p>同步网页空间和数据库使用量，检查是否超出配额</p>
                        <div class="code-block" id="cmd-web">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=web'</div>
                        <p><strong>建议周期：</strong>每30分钟</p>
                        <button class="copy-btn" onclick="copyCommand('cmd-web', this)">复制</button>
                    </div>
                </div>
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item">
                        <h5><i class="fas fa-database"></i> 数据库监控</h5>
                        <p>同步数据库空间使用量，检查是否超出配额</p>
                        <div class="code-block" id="cmd-sql">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=sql'</div>
                        <p><strong>建议周期：</strong>每30分钟</p>
                        <button class="copy-btn" onclick="copyCommand('cmd-sql', this)">复制</button>
                    </div>
                </div>
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item">
                        <h5><i class="fas fa-chart-line"></i> 流量监控</h5>
                        <p>收集流量统计数据，更新用户使用情况</p>
                        <div class="code-block" id="cmd-fh">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=fh'</div>
                        <p><strong>建议周期：</strong>每10分钟</p>
                        <button class="copy-btn" onclick="copyCommand('cmd-fh', this)">复制</button>
                    </div>
                </div>
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item">
                        <h5><i class="fas fa-redo"></i> 流量清零</h5>
                        <p>每月1日自动重置所有主机流量使用量</p>
                        <div class="code-block" id="cmd-fhq">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=fhq'</div>
                        <p><strong>建议周期：</strong>每月1日 0:00</p>
                        <button class="copy-btn" onclick="copyCommand('cmd-fhq', this)">复制</button>
                    </div>
                </div>
            </div>
            <div class="row" style="margin: 15px -10px 0 -10px;">
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item">
                        <h5><i class="fas fa-broom"></i> 临时文件清理</h5>
                        <p>清理过期压缩包、临时目录和未使用文件</p>
                        <div class="code-block" id="cmd-cleanup">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=cleanup'</div>
                        <p><strong>建议周期：</strong>每天凌晨2点</p>
                        <button class="copy-btn" onclick="copyCommand('cmd-cleanup', this)">复制</button>
                    </div>
                </div>
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item">
                        <h5><i class="fas fa-stop-circle"></i> 到期自动停止</h5>
                        <p>检查并停止已到期的用户主机</p>
                        <div class="code-block" id="cmd-stop">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=stop_expire'</div>
                        <p><strong>建议周期：</strong>每天凌晨1点</p>
                        <button class="copy-btn" onclick="copyCommand('cmd-stop', this)">复制</button>
                    </div>
                </div>
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item">
                        <h5><i class="fas fa-trash-alt"></i> 到期自动删除</h5>
                        <p>删除已暂停超过指定天数的主机数据</p>
                        <div class="code-block" id="cmd-delete">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=delete_expire'</div>
                        <p><strong>建议周期：</strong>每天凌晨2点</p>
                        <button class="copy-btn" onclick="copyCommand('cmd-delete', this)">复制</button>
                    </div>
                </div>
                <div class="col-md-3" style="padding: 0 10px;">
                    <div class="task-item" style="border: 2px solid #1a73e8; background: linear-gradient(135deg, #f8f9ff 0%, #e8f0ff 100%);">
                        <h5 style="color: #1a73e8;"><i class="fas fa-layer-group"></i> 全部监控执行</h5>
                        <p>一键执行所有监控任务（不含流量清零）</p>
                        <div class="code-block" id="cmd-all">curl -s '<?php echo $protocol; ?>://<?php echo $_SERVER['HTTP_HOST']; ?>/jk.php?my=<?php echo $conf['api']; ?>&gn=all'</div>
                        <p><strong>建议周期：</strong>每小时执行</p>
                        <button class="copy-btn" style="background: #1a73e8;" onclick="copyCommand('cmd-all', this)">复制</button>
                    </div>
                </div>
            </div>

            <script>
            function copyCommand(elementId, btn) {
                const element = document.getElementById(elementId);
                if (!element) {
                    alert('复制失败：找不到元素');
                    return;
                }
                
                // 获取纯文本内容
                let text = element.textContent.trim();
                
                // 检查是否支持现代剪贴板API
                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(text).then(function() {
                        showCopied(btn);
                    }).catch(function(err) {
                        // 降级到传统方法
                        fallbackCopy(text, btn);
                    });
                } else {
                    // 使用传统方法
                    fallbackCopy(text, btn);
                }
            }
            
            function fallbackCopy(text, btn) {
                const textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none;z-index:-1;';
                document.body.appendChild(textarea);
                
                // 选择文本
                textarea.focus();
                textarea.select();
                
                try {
                    const successful = document.execCommand('copy');
                    if (successful) {
                        showCopied(btn);
                    } else {
                        alert('复制失败，请手动复制');
                    }
                } catch (e) {
                    console.error('复制失败:', e);
                    alert('复制失败，请手动复制');
                }
                
                document.body.removeChild(textarea);
            }
            
            function showCopied(btn) {
                var originalText = btn.textContent;
                btn.textContent = '已复制';
                btn.classList.add('copied');
                btn.style.background = '#188038';
                setTimeout(function() {
                    btn.textContent = originalText || '复制';
                    btn.classList.remove('copied');
                    btn.style.background = '';
                }, 2000);
            }
            </script>
            
            <div class="alert alert-info" style="margin-top: 16px;">
                <i class="fas fa-info-circle"></i>
                <strong>配置说明：</strong>
                <ol style="margin: 8px 0 0 20px; font-size: 13px;">
                    <li>登录宝塔面板，进入 <strong>计划任务</strong></li>
                    <li>添加 <strong>Shell脚本</strong> 任务</li>
                    <li>选择执行周期并粘贴对应命令</li>
                    <li>保存后点击"执行"测试任务是否正常</li>
                </ol>
            </div>
        </div>

        <!-- 实时监控说明 -->
        <div class="monitor-card">
            <h3><i class="fas fa-info-circle"></i> 监控说明</h3>
            <div class="row" style="margin: 0 -10px;">
                <div class="col-md-4" style="padding: 0 10px;">
                    <h5 style="color: #202124; font-size: 14px; margin-bottom: 12px;">空间监控功能</h5>
                    <ul style="color: #5f6368; font-size: 13px; line-height: 1.8; margin-bottom: 16px;">
                        <li>同步网页空间使用量</li>
                        <li>同步数据库使用量</li>
                        <li>检查是否超出配额</li>
                        <li>自动暂停超出的主机</li>
                    </ul>
                </div>
                <div class="col-md-4" style="padding: 0 10px;">
                    <h5 style="color: #202124; font-size: 14px; margin-bottom: 12px;">流量监控功能</h5>
                    <ul style="color: #5f6368; font-size: 13px; line-height: 1.8; margin-bottom: 16px;">
                        <li>收集每日流量统计数据</li>
                        <li>生成流量使用趋势图表</li>
                        <li>超出流量限制自动暂停</li>
                        <li>每月自动重置流量</li>
                    </ul>
                </div>
                <div class="col-md-4" style="padding: 0 10px;">
                    <h5 style="color: #202124; font-size: 14px; margin-bottom: 12px;">临时文件清理功能</h5>
                    <ul style="color: #5f6368; font-size: 13px; line-height: 1.8; margin-bottom: 16px;">
                        <li>清理系统临时目录过期压缩包（24小时）</li>
                        <li>清理程序导出/导入临时文件夹（24小时）</li>
                        <li>清理用户目录过期压缩包（7天）</li>
                        <li>清理未使用的上传文件（30天）</li>
                    </ul>
                </div>
            </div>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle"></i>
                <strong>注意事项：</strong>
                <ul style="margin: 8px 0 0 20px; font-size: 13px;">
                    <li>确保监控脚本已正确配置，否则统计数据可能不准确</li>
                    <li>建议将空间监控任务的执行周期设置为每30分钟或更长，避免频繁查询影响性能</li>
                    <li>流量监控建议每10分钟执行一次，以保证数据实时性</li>
                    <li>临时文件清理建议每天凌晨2点执行，自动清理过期文件释放空间</li>
                </ul>
            </div>
        </div>
    </div>

    <script src="/static/js/jquery.min.js"></script>
</body>
</html>
