<?php
session_start();
require_once '../config.php';
require_once '../includes/functions.php';
require_once '../includes/api.php';

// 检查登录状态
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// 获取统计数据
$total_posts = 0;
$total_categories = 0;
$cache_info = [];

try {
    // 获取文章总数
    $posts_result = get_total_posts();
    if ($posts_result['code'] == 200) {
        $total_posts = $posts_result['data']['total_posts'] ?? 0;
    }
    
    // 获取分类总数
    $categories_result = get_categories();
    if ($categories_result['code'] == 200) {
        $total_categories = count($categories_result['data']['categories'] ?? []);
    }
    
    // 获取缓存信息
    if (isset($GLOBALS['cache']) && method_exists($GLOBALS['cache'], 'info')) {
        $cache_info = $GLOBALS['cache']->info();
    }
} catch (Exception $e) {
    error_log("Dashboard statistics error: " . $e->getMessage());
}

$page_title = '后台首页';
?>
    <?php include 'header.php'; ?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <div class="col-md-10 p-4">
            <h2>后台首页</h2>
            
            <!-- 统计卡片 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card bg-primary text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?php echo $total_posts; ?></h4>
                                    <p>文章总数</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-file-text fs-1"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-success text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?php echo $total_categories; ?></h4>
                                    <p>分类数量</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-folder fs-1"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-warning text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?php echo $cache_info['count'] ?? 0; ?></h4>
                                    <p>缓存文件</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-arrow-repeat fs-1"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card bg-info text-white stats-card">
                        <div class="card-body">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h4><?php echo round(($cache_info['size'] ?? 0) / 1024, 2); ?> KB</h4>
                                    <p>缓存大小</p>
                                </div>
                                <div class="align-self-center">
                                    <i class="bi bi-hdd fs-1"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 快速操作 -->
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">快速操作</h5>
                        </div>
                        <div class="card-body">
                            <div class="d-grid gap-2">
                                <a href="settings.php" class="btn btn-outline-primary">
                                    <i class="bi bi-gear"></i> 系统设置
                                </a>
                                <a href="announcements.php" class="btn btn-outline-success">
                                    <i class="bi bi-megaphone"></i> 公告管理
                                </a>
                                <a href="custom_data.php" class="btn btn-outline-info">
                                    <i class="bi bi-database"></i> 自定义数据
                                </a>
                                <a href="navigation.php" class="btn btn-outline-success">
                                    <i class="bi bi-list-ul"></i> 导航管理
                                </a>
                                <a href="https://www.wenshay.cn/" class="btn btn-outline-primary" target="_blank">
                                    <i class="bi bi-list-ul"></i> 免费虚拟主机&nbsp; &nbsp;&nbsp;免备案云服务器20元/月起&nbsp; &nbsp;&nbsp;免费SSL证书申请
                                </a>
                                 <a href="https://www.wszzw.cn/" class="btn btn-outline-info" target="_blank">
                                    <i class="bi bi-list-ul"></i> 本系统：文煞CMS(api版) v 2.0，其他版本、最新版本动态了解...
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">系统信息</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-sm">
                                <tr>
                                    <td>PHP版本</td>
                                    <td><?php echo PHP_VERSION; ?></td>
                                </tr>
                                <tr>
                                    <td>服务器软件</td>
                                    <td><?php echo $_SERVER['SERVER_SOFTWARE'] ?? '未知'; ?></td>
                                </tr>
                                <tr>
                                    <td>网站主题</td>
                                    <td><?php echo $config['site']['theme']; ?></td>
                                </tr>
                                <tr>
                                    <td>缓存状态</td>
                                    <td>
                                        <span class="badge bg-<?php echo ($config['cache']['enabled'] ?? false) ? 'success' : 'danger'; ?>">
                                            <?php echo ($config['cache']['enabled'] ?? false) ? '已启用' : '已禁用'; ?>
                                        </span>
                                    </td>
                                </tr>
                                <tr>
                                    <td>伪静态</td>
                                    <td>
                                        <span class="badge bg-<?php echo ($config['url']['rewrite'] ?? false) ? 'success' : 'secondary'; ?>">
                                            <?php echo ($config['url']['rewrite'] ?? false) ? '已启用' : '未启用'; ?>
                                        </span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 缓存管理 -->
            <div class="row mt-4">
                <div class="col-md-12">
                    <div class="card">
<div class="card-header d-flex justify-content-between align-items-center">
    <h5 class="mb-0">缓存管理</h5>
    <!-- 按钮改为点击事件触发，移除target="_blank" -->
    <button id="updateCacheBtn" class="btn btn-sm btn-primary">
        <i class="bi bi-arrow-repeat"></i> 更新缓存
    </button>
</div>
<!-- 新增结果显示区域，默认隐藏 -->
<div id="cacheResult" class="mt-3 p-3 rounded d-none" style="display: none;"></div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4">
                                    <strong>缓存文件数:</strong> <?php echo $cache_info['count'] ?? 0; ?>
                                </div>
                                <div class="col-md-4">
                                    <strong>缓存大小:</strong> <?php echo round(($cache_info['size'] ?? 0) / 1024, 2); ?> KB
                                </div>
                                <div class="col-md-4">
                                    <strong>缓存状态:</strong> 
                                    <span class="badge bg-<?php echo ($cache_info['enabled'] ?? false) ? 'success' : 'danger'; ?>">
                                        <?php echo ($cache_info['enabled'] ?? false) ? '正常' : '异常'; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
// 获取按钮和结果显示元素
const updateBtn = document.getElementById('updateCacheBtn');
const resultDiv = document.getElementById('cacheResult');

// 点击按钮触发更新请求
updateBtn.addEventListener('click', function() {
    // 按钮置灰，防止重复点击
    updateBtn.disabled = true;
    updateBtn.innerHTML = '<i class="bi bi-spinner bi-spin"></i> 更新中...';
    
    // 发送异步请求
    fetch('../update-cache')
        .then(response => response.json()) // 解析返回的JSON数据
        .then(data => {
            // 清空原有结果
            resultDiv.innerHTML = '';
            // 设置结果区域样式（成功为绿色，失败为红色）
            resultDiv.className = data.code === 200 
                ? 'mt-3 p-3 rounded bg-success text-white' 
                : 'mt-3 p-3 rounded bg-danger text-white';
            
            // 显示状态信息
            resultDiv.innerHTML += `<p><strong>状态：</strong>${data.message}</p>`;
            
            // 显示成功列表（若有）
            if (data.data.success.length > 0) {
                resultDiv.innerHTML += `<p><strong>成功项：</strong></p><ul>`;
                data.data.success.forEach(item => {
                    resultDiv.innerHTML += `<li>${item}</li>`;
                });
                resultDiv.innerHTML += `</ul>`;
            }
            
            // 显示失败列表（若有）
            if (data.data.failed.length > 0) {
                resultDiv.innerHTML += `<p><strong>失败项：</strong></p><ul>`;
                data.data.failed.forEach(item => {
                    resultDiv.innerHTML += `<li>${item}</li>`;
                });
                resultDiv.innerHTML += `</ul>`;
            }
            
            // 显示结果区域
            resultDiv.style.display = 'block';
        })
        .catch(error => {
            // 捕获请求错误
            resultDiv.className = 'mt-3 p-3 rounded bg-danger text-white';
            resultDiv.innerHTML = `<p><strong>请求失败：</strong>网络错误或服务器异常，请重试</p>`;
            resultDiv.style.display = 'block';
        })
        .finally(() => {
            // 恢复按钮状态
            updateBtn.disabled = false;
            updateBtn.innerHTML = '<i class="bi bi-arrow-repeat"></i> 更新缓存';
        });
});
</script>
</body>
</html>