<?php
// 功能：网站后台路由公用文件
// 作者：启肯科技
// Q Q：328493711
// 微信：13738373177（同手机）
// 官网：http://www.qiken.com
// 说明：QKCMS-轻量级AI智能内容管理建站系统
// 版权：© 2025 温州启肯网络有限公司 保留所有权利，盗版必究。

if (!defined('COMMON_LOADED')) {
    require_once '../common.php';

    start_admin_session();

    // 处理URL参数，将action和id存储到session
    handle_url_params();
}

// 处理文章删除AJAX请求（在输出任何HTML之前）
if ((isset($_GET['delete_article']) || isset($_GET['batch_delete'])) && isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    // 定义ADMIN_LOADED常量，确保article.php能正常加载
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    require_once 'article.php';
    exit;
}

// 处理评论删除AJAX请求（在输出任何HTML之前）
if (isset($_GET['tab']) && $_GET['tab'] === 'comments' && isset($_GET['delete_comment']) && isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    require_once 'adcomment.php';
    exit;
}

// 处理商品删除AJAX请求（在输出任何HTML之前）
if (isset($_GET['tab']) && $_GET['tab'] === 'adgoods' && isset($_GET['delete_goods']) && isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    require_once 'adgoods.php';
    exit;
}

// 处理订单删除/清空AJAX请求（在输出任何HTML之前）
if (isset($_GET['tab']) && $_GET['tab'] === 'order' && isset($_GET['action']) && in_array($_GET['action'], array('delete', 'clear_all'), true) && isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    require_once 'order.php';
    exit;
}

// 处理分类删除AJAX请求
if (isset($_GET['tab']) && $_GET['tab'] === 'adcategory' && isset($_GET['delete_category']) && isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    require_once 'adcategory.php';
    exit;
}

// 处理分类开关状态更新AJAX请求
if (isset($_POST['update_display'])) {
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    require_once 'adcategory.php';
    exit;
}

// 处理分类缩略图更新AJAX请求
if (isset($_POST['update_category_thumbnail'])) {
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    require_once 'adcategory.php';
    exit;
}

// 处理文章属性/分类更新AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['update_property']) || isset($_POST['update_category']) || isset($_POST['update_title']) || isset($_POST['update_template']))) {
    if (!defined('ADMIN_LOADED')) define('ADMIN_LOADED', true);
    require_once 'article.php';
    exit;
}

// 处理商品字段更新AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['update_goods_category']) || isset($_POST['update_goods_status']) || isset($_POST['update_goods_title']) || isset($_POST['update_goods_price']) || isset($_POST['update_goods_stock']) || isset($_POST['update_goods_sales']))) {
    if (!defined('COMMON_LOADED')) {
        require_once '../common.php';
        start_admin_session();
    }
    if (!defined('ADMIN_LOADED')) define('ADMIN_LOADED', true);
    require_once 'adgoods.php';
    exit;
}

// 处理统计数据AJAX请求
if (isset($_GET['page']) && $_GET['page'] === 'metrics_ajax') {
    if (!defined('ADMIN_LOADED')) {
        define('ADMIN_LOADED', true);
    }
    global $conn;
    
    $result = [
        'db_size' => '0 MB',
        'db_charset' => 'utf8',
        'db_max_connections' => 'N/A',
        'plugin_count' => 0,
        'file_count' => 0,
        'file_size' => '0 B'
    ];
    
    try {
        if (isset($conn) && ($conn instanceof mysqli) && empty($conn->connect_error)) {
            $res = $conn->query("SELECT ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb FROM information_schema.tables WHERE table_schema = DATABASE()");
            if ($res && ($row = $res->fetch_assoc())) {
                $size = (float)($row['size_mb'] ?? 0);
                $result['db_size'] = $size >= 1024 ? (round($size / 1024, 2) . ' GB') : (number_format($size, 2) . ' MB');
            }
            if ($res) $res->close();
            
            $res = $conn->query("SHOW VARIABLES LIKE 'character_set_connection'");
            if ($res && ($row = $res->fetch_assoc())) {
                $result['db_charset'] = (string)($row['Value'] ?? $result['db_charset']);
            }
            if ($res) $res->close();
            
            $res = $conn->query("SHOW VARIABLES LIKE 'max_connections'");
            if ($res && ($row = $res->fetch_assoc())) {
                $result['db_max_connections'] = (string)($row['Value'] ?? $result['db_max_connections']);
            }
            if ($res) $res->close();
        }
    } catch (Exception $e) {}
    
    if (function_exists('get_installed_plugins')) {
        $installed_plugins = get_installed_plugins();
        $result['plugin_count'] = count($installed_plugins);
    }
    
    if (function_exists('countFilesAndSize')) {
        $file_info = countFilesAndSize(dirname(__DIR__));
        $result['file_count'] = $file_info['count'];
        $result['file_size'] = formatBytes($file_info['size']);
    }
    
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}





// 首先处理从JavaScript传递过来的参数，无论COMMON_LOADED是否已定义
handle_article_params();
// 定义管理员页面加载常量，用于控制被引入文件的访问
if (!defined('ADMIN_LOADED')) {
    define('ADMIN_LOADED', true);
}

global $conn;
$settings = getSettings($conn);
$admin_project_identifier = '';
$favicon_color = isset($settings['primary_color']) ? trim($settings['primary_color']) : '#10b981';
if (!preg_match('/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/', $favicon_color)) {
    $favicon_color = '#10b981';
}

// 根据主题色计算渐变色
function get_gradient_colors($base_color) {
    $hex = ltrim($base_color, '#');
    if (strlen($hex) === 3) {
        $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
    }
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    
    // 计算较亮的颜色（增加亮度）
    $r_light = min(255, $r + 40);
    $g_light = min(255, $g + 40);
    $b_light = min(255, $b + 40);
    $light_color = sprintf('#%02x%02x%02x', $r_light, $g_light, $b_light);
    
    // 计算较暗的颜色（减少亮度）
    $r_dark = max(0, $r - 30);
    $g_dark = max(0, $g - 30);
    $b_dark = max(0, $b - 30);
    $dark_color = sprintf('#%02x%02x%02x', $r_dark, $g_dark, $b_dark);
    
    return array(
        'light' => $light_color,
        'base' => $base_color,
        'dark' => $dark_color
    );
}

$gradient_colors = get_gradient_colors($favicon_color);
$favicon_svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="' . $favicon_color . '"/><text x="32" y="45" text-anchor="middle" fill="#fff" font-size="46" font-family="Arial,Helvetica,sans-serif" font-weight="900">Q</text></svg>';
$favicon_data_uri = 'data:image/svg+xml,' . rawurlencode($favicon_svg);

if (isset($_GET['action']) && $_GET['action'] === 'get_theme_color') {
    header('Content-Type: application/json');
    $primaryColor = isset($settings['primary_color']) ? $settings['primary_color'] : '#7c3aed';
    echo json_encode(['primary_color' => $primaryColor]);
    exit;
}

if (isset($_GET['action']) && $_GET['action'] === 'generate_sitemap') {
    header('Content-Type: application/json');
    check_admin_permission();
    $result = generate_sitemap($conn);
    admin_ajax_response($result);
}

// 处理修改密码请求
if (isset($_GET['action']) && $_GET['action'] === 'change_password') {
    header('Content-Type: application/json');
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => '未登录']);
        exit;
    }

    $old_password = isset($_POST['old_password']) ? $_POST['old_password'] : '';
    $new_password = isset($_POST['new_password']) ? $_POST['new_password'] : '';

    if (empty($old_password) || empty($new_password)) {
        echo json_encode(['success' => false, 'message' => '密码不能为空']);
        exit;
    }

    if (strlen($new_password) < 6) {
        echo json_encode(['success' => false, 'message' => '新密码至少6位']);
        exit;
    }

    // 验证原密码
    $user = get_single_row($conn, "SELECT password FROM users WHERE id = ?", array($_SESSION['user_id']));
    if (!$user || !password_verify($old_password, $user['password'])) {
        echo json_encode(['success' => false, 'message' => '原密码错误']);
        exit;
    }

    // 更新密码
    $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
    $result = execute_non_query($conn, "UPDATE users SET password = ? WHERE id = ?", array($new_password_hash, $_SESSION['user_id']));

    if ($result !== false) {
        echo json_encode(['success' => true, 'message' => '密码修改成功']);
    } else {
        echo json_encode(['success' => false, 'message' => '密码修改失败']);
    }
    exit;
}

// 处理更新用户信息请求（密码和积分）
if (isset($_GET['action']) && $_GET['action'] === 'update_user_info') {
    header('Content-Type: application/json');
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => '未登录']);
        exit;
    }

    $old_password = isset($_POST['old_password']) ? $_POST['old_password'] : '';
    $new_password = isset($_POST['new_password']) ? $_POST['new_password'] : '';
    $points = isset($_POST['points']) ? intval($_POST['points']) : 0;

    if ($points < 0) {
        echo json_encode(['success' => false, 'message' => '积分不能为负数']);
        exit;
    }

    // 如果要修改密码，验证原密码
    if (!empty($new_password)) {
        if (empty($old_password)) {
            echo json_encode(['success' => false, 'message' => '请输入原密码']);
            exit;
        }
        if (strlen($new_password) < 6) {
            echo json_encode(['success' => false, 'message' => '新密码至少6位']);
            exit;
        }

        // 验证原密码
        $user = get_single_row($conn, "SELECT password FROM users WHERE id = ?", array($_SESSION['user_id']));
        if (!$user || !password_verify($old_password, $user['password'])) {
            echo json_encode(['success' => false, 'message' => '原密码错误']);
            exit;
        }
    }

    // 开始事务
    $conn->begin_transaction();
    $success = true;
    $message = '';

    try {
        // 更新积分
        $result = execute_non_query($conn, "UPDATE users SET points = ? WHERE id = ?", array($points, $_SESSION['user_id']));
        if ($result === false) {
            throw new Exception('积分更新失败');
        }

        // 如果提供了新密码，更新密码
        if (!empty($new_password)) {
            $new_password_hash = password_hash($new_password, PASSWORD_DEFAULT);
            $result = execute_non_query($conn, "UPDATE users SET password = ? WHERE id = ?", array($new_password_hash, $_SESSION['user_id']));
            if ($result === false) {
                throw new Exception('密码更新失败');
            }
        }

        // 提交事务
        $conn->commit();
        $message = '信息更新成功';
    } catch (Exception $e) {
        // 回滚事务
        $conn->rollback();
        $success = false;
        $message = $e->getMessage();
    }

    echo json_encode(['success' => $success, 'message' => $message]);
    exit;
}

if (isset($_FILES['file']) && !empty($_FILES['file']['name'])) {
    header('Content-Type: application/json');
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['levels_id']) || $_SESSION['levels_id'] != 3) {
        echo json_encode(['errno' => 1, 'message' => '权限不足，需要管理员权限']);
        exit;
    }

    $type = isset($_POST['type']) ? $_POST['type'] : 'article';
    $image_type = isset($_POST['image_type']) ? $_POST['image_type'] : 'thumbnail';

    // 确保上传目录存在
    ensureUploadDirectories();

    $file = $_FILES['file'];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];
    $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    if (!in_array($fileExt, $allowedExts)) {
        echo json_encode(['success' => false, 'message' => '不允许的文件类型']);
        exit;
    }
    if ($fileSize > 2 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => '文件大小超过2MB限制']);
        exit;
    }

    // 根据类型生成文件名前缀
    $prefix = $type === 'category' ? 'category_' : 'thumbnail_';
    $newFileName = $prefix . uniqid('', true) . '.' . $fileExt;
    $destination = TEMP_UPLOAD_DIR . $newFileName;

    if (move_uploaded_file($fileTmpName, $destination)) {
        $fileUrl = qk_build_relative_upload_path($newFileName, '/uploads/Temp/');
        echo json_encode(['success' => true, 'data' => ['url' => $fileUrl]]);
    } else {
        echo json_encode(['success' => false, 'message' => '文件上传失败']);
    }
    exit;
}



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

$page_title = '后台管理中心';
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'metrics';



// 初始化分页参数
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$current_page = 1;
$posts_per_page = 30;

// 优先解析新的简洁格式
foreach ($_GET as $key => $value) {
    // 解析页码和每页显示数量：p{page}_s{per_page}
    if (preg_match('/^p(\d+)_s(\d+)$/', $key, $matches)) {
        $current_page = intval($matches[1]);
        $posts_per_page = intval($matches[2]);
    }
}

// 向后兼容，支持旧格式
if (isset($_GET['page']) && $_GET['page'] > 0) {
    $current_page = intval($_GET['page']);
}
if (isset($_GET['posts_per_page'])) {
    $temp_posts_per_page = intval($_GET['posts_per_page']);
    if ($temp_posts_per_page >= 1 && $temp_posts_per_page <= 1000) $posts_per_page = $temp_posts_per_page;
}

$current_page = max(1, $current_page);
$posts_per_page = max(1, min(1000, $posts_per_page));

if ($active_tab == 'CloudPlug') {
    $has_compact_paging = false;
    foreach ($_GET as $key => $value) {
        if (preg_match('/^p(\d+)_s(\d+)$/', $key)) {
            $has_compact_paging = true;
            break;
        }
    }
    if (!$has_compact_paging && !isset($_GET['posts_per_page'])) {
        $posts_per_page = 12;
    }
}

if ($active_tab == 'adcategory' || $active_tab == 'metrics') {
    $categories = getCategories();
}

if ($active_tab == 'articles' || $active_tab == 'metrics') {
    if ($active_tab == 'metrics') {
        $limit = 5;
        $offset = 0;
        $search_term = '';
        $cat_id = 0;
    } else {
        $limit = $posts_per_page;
        $offset = ($current_page - 1) * $posts_per_page;
        $search_term = $search;

        // 解析分类ID（用于筛选）
        $cat_id = 0;
        foreach ($_GET as $key => $value) {
            if (preg_match('/^p(\d+)_s(\d+)(_cid(\d+))?$/', $key, $matches)) {
                if (isset($matches[4])) $cat_id = intval($matches[4]);
            } elseif (preg_match('/^cid(\d+)$/', $key, $matches)) {
                $cat_id = intval($matches[1]);
            }
        }
        if (isset($_GET['category_id'])) $cat_id = intval($_GET['category_id']);
    }

    $articles = getArticles($limit, $offset, $search_term, $cat_id);
    if ($active_tab == 'articles') {
        $total_articles = getTotalArticles($search_term, $cat_id);
        $total_pages = ceil($total_articles / $posts_per_page);
    }
}

if ($active_tab == 'comments') {
    $limit = $posts_per_page;
    $offset = ($current_page - 1) * $posts_per_page;
    $status = isset($_GET['status']) ? $_GET['status'] : 'all';
    $search_term = $search;

    $where_conditions = array();
    $params = array();
    $types = '';

    if ($status != 'all') {
        $status_value = ($status == 'approved' ? 1 : 0);
        $where_conditions[] = "c.status = ?";
        $params[] = $status_value;
        $types .= 'i';
    }

    if (!empty($search_term)) {
        $where_conditions[] = "(c.content LIKE ? OR u.username LIKE ? OR p.title LIKE ?)";
        $searchPattern = '%' . $search_term . '%';
        $params[] = $searchPattern;
        $params[] = $searchPattern;
        $params[] = $searchPattern;
        $types .= 'sss';
    }

    $sql = "SELECT c.id, c.content, c.post_id as article_id, p.title as article_title, u.username, c.created_at, c.status 
            FROM comments c 
            LEFT JOIN users u ON c.user_id = u.id 
            LEFT JOIN posts p ON c.post_id = p.id";

    if (!empty($where_conditions)) {
        $sql .= " WHERE " . implode(" AND ", $where_conditions);
    }

    $count_sql = "SELECT COUNT(*) as total FROM comments c LEFT JOIN users u ON c.user_id = u.id LEFT JOIN posts p ON c.post_id = p.id";
    if (!empty($where_conditions)) {
        $count_sql .= " WHERE " . implode(" AND ", $where_conditions);
    }

    $sql .= " ORDER BY c.id DESC LIMIT ?, ?";
    $params[] = $offset;
    $params[] = $limit;
    $types .= 'ii';

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        $comments = array();
        while ($row = $result->fetch_assoc()) {
            $comments[] = $row;
        }
        $stmt->close();
    }

    $count_stmt = $conn->prepare($count_sql);
    if ($count_stmt) {
        $count_params = array_slice($params, 0, count($params) - 2);
        if (!empty($count_params)) {
            $count_types = substr($types, 0, -2);
            $count_stmt->bind_param($count_types, ...$count_params);
        }
        $count_stmt->execute();
        $count_result = $count_stmt->get_result();
        $count_row = $count_result->fetch_assoc();
        $total_comments = $count_row['total'];
        $total_pages = ceil($total_comments / $posts_per_page);
        $count_stmt->close();
    }
}


$success = '';
$error = '';

// 获取当前登录用户信息
$current_user = null;
$user_points = 0;
if (isset($_SESSION['user_id'])) {
    $current_user = get_single_row($conn, "SELECT id, username, avatar, points FROM users WHERE id = ?", array($_SESSION['user_id']));
    if ($current_user) {
        $user_points = $current_user['points'];
    }
}

if (!empty($success)) {
    if ($active_tab == 'adcategory') {
        $categories = getCategories($search);
    }
}

// 获取授权信息用于顶部标识
$top_license_data = null;
if (isset($_SESSION['qkcms_license_cache']['data'])) {
    $top_license_data = $_SESSION['qkcms_license_cache']['data'];
} else {
    if (file_exists(dirname(__DIR__) . '/license.php')) {
        require_once dirname(__DIR__) . '/license.php';
        if (function_exists('qk_license_cached_data')) {
            $top_license_data = qk_license_cached_data();
        }
    }
}

global $qkcms_license_info;
if (isset($qkcms_license_info['app_identifier'])) {
    $admin_project_identifier = trim((string)$qkcms_license_info['app_identifier']);
}
if ($admin_project_identifier === '' && isset($top_license_data['app_identifier'])) {
    $admin_project_identifier = trim((string)$top_license_data['app_identifier']);
}
if ($admin_project_identifier === '' && isset($_SESSION['qkcms_license_cache']['data']['app_identifier'])) {
    $admin_project_identifier = trim((string)$_SESSION['qkcms_license_cache']['data']['app_identifier']);
}
if ($admin_project_identifier === '' && function_exists('payapi_settings_get')) {
    $admin_project_identifier = trim((string)payapi_settings_get('app_identifier', ''));
}
if ($admin_project_identifier === '' && isset($settings['site_name'])) {
    $admin_project_identifier = trim((string)$settings['site_name']);
}
if ($admin_project_identifier === '') $admin_project_identifier = 'QKCMS';

?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title><?php echo escape($page_title); ?>-<?php echo escape($settings['site_name']); ?></title>
    <link rel="icon" href="<?php echo escape($favicon_data_uri); ?>" type="image/svg+xml" />
    <link rel="shortcut icon" href="<?php echo escape($favicon_data_uri); ?>" type="image/svg+xml" />
    <link rel="stylesheet" href="/assets/css/admin.css">
   
    <script>
        (function() {
            const savedThemeColor = '<?php echo $settings['primary_color'] ?? '#7c3aed'; ?>';
            if (savedThemeColor && savedThemeColor !== '#7c3aed') {
                document.documentElement.style.setProperty('--primary-color', savedThemeColor);
                document.documentElement.style.setProperty('--primary', savedThemeColor);
            }
        })();
        (function() {
            var menuIds = ['content-menu', 'user-menu', 'extension-menu'];
            var initialStyles = {};
            menuIds.forEach(function(menuId) {
                var savedState = localStorage.getItem('menu_' + menuId);
                initialStyles[menuId] = savedState === 'collapsed' ? false : true;
            });
            window._menuInitialStyles = initialStyles;
        })();
        (function() {
            const defaultColor = <?php echo json_encode($favicon_color, JSON_UNESCAPED_UNICODE); ?>;
            function buildFavicon(color) {
                const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="' + color + '"/><text x="32" y="45" text-anchor="middle" fill="#fff" font-size="46" font-family="Arial,Helvetica,sans-serif" font-weight="900">Q</text></svg>';
                return 'data:image/svg+xml,' + encodeURIComponent(svg);
            }
            function applyFaviconByTheme() {
                const cssColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();
                const color = cssColor || defaultColor || '#10b981';
                const href = buildFavicon(color);
                const links = document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]');
                links.forEach(function(link) {
                    link.href = href;
                });
            }
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', applyFaviconByTheme);
            } else {
                applyFaviconByTheme();
            }
        })();
        
        // LOGO 渐变色计算
        (function() {
            const defaultColor = <?php echo json_encode($favicon_color, JSON_UNESCAPED_UNICODE); ?>;
            
            function calculateGradientColors(baseColor) {
                const hex = baseColor.replace('#', '');
                const r = parseInt(hex.substr(0, 2), 16);
                const g = parseInt(hex.substr(2, 2), 16);
                const b = parseInt(hex.substr(4, 2), 16);
                
                const r_light = Math.min(255, r + 40);
                const g_light = Math.min(255, g + 40);
                const b_light = Math.min(255, b + 40);
                const lightColor = '#' + [r_light, g_light, b_light].map(x => x.toString(16).padStart(2, '0')).join('');
                
                const r_dark = Math.max(0, r - 30);
                const g_dark = Math.max(0, g - 30);
                const b_dark = Math.max(0, b - 30);
                const darkColor = '#' + [r_dark, g_dark, b_dark].map(x => x.toString(16).padStart(2, '0')).join('');
                
                return { light: lightColor, base: baseColor, dark: darkColor };
            }
            
            function applyGradient() {
                const cssColor = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim();
                const color = cssColor || defaultColor || '#10b981';
                const gradients = calculateGradientColors(color);
                
                document.documentElement.style.setProperty('--primary-color-light', gradients.light);
                document.documentElement.style.setProperty('--primary-color-dark', gradients.dark);
            }
            
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', applyGradient);
            } else {
                applyGradient();
            }
        })();

    </script>

    <?php include 'seapage.php'; ?>
</head>

<body>
    <header class="header">
        <div class="header-content">
            <div style="position: relative;"> 
                <a href="/index.php" class="logo" style="position: relative; display: inline-block; color: var(--primary-color); font-weight: 800; letter-spacing: 1px; text-decoration: none;">
                    <span id="logo-gradient" style="background: linear-gradient(90deg, var(--primary-color-dark, var(--primary-color)) 0%, var(--primary-color) 50%, var(--primary-color-light, var(--primary-color)) 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; text-fill-color: transparent;"><?php echo escape($admin_project_identifier); ?></span>
                </a> 
                <?php if (isset($_SESSION['username']) && $_SESSION['username'] === 'demo'): ?>
                    <span style="margin-left: 2px; padding: 1px 8px; background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); border-radius: 10px 10px 10px 0; color: #dc2626; font-size: 9px; font-weight: 600; display: inline-block; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border: 1px solid #fca5a5; transform: skew(-5deg);"> 演示版 </span>
                <?php elseif ($top_license_data && $top_license_data['has_license']): ?>
                    <span style="margin-left: 2px; padding: 1px 8px; background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%); border-radius: 10px 10px 10px 0; color: #059669; font-size: 9px; font-weight: 600; display: inline-block; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border: 1px solid #86efac; transform: skew(-5deg);"> 已授权 </span>
                <?php elseif ($top_license_data && $top_license_data['in_trial']): ?>
                    <span style="margin-left: 2px; padding: 1px 8px; background: linear-gradient(135deg, #fff7ed 0%, #ffedd5 100%); border-radius: 10px 10px 10px 0; color: #ea580c; font-size: 9px; font-weight: 600; display: inline-block; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border: 1px solid #fed7aa; transform: skew(-5deg);"> 试用中 </span>
                <?php else: ?>
                    <span style="margin-left: 2px; padding: 1px 8px; background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); border-radius: 10px 10px 10px 0; color: #dc2626; font-size: 9px; font-weight: 600; display: inline-block; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); border: 1px solid #fca5a5; transform: skew(-5deg);"> 未授权 </span>
                <?php endif; ?>
            </div>
            <div class="main-nav-area">
                <nav class="nav">
                    <div class="sidebar-toggle-btn" id="sidebarToggleBtn" title="收起导航">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 1792 1408" fill="#9ca3af">
                            <path d="M343 681Q352 690 352 704Q352 718 343 727L55 1015Q46 1024 32 1024Q19 1024 9.50 1014.50Q0 1005 0 992L0 416Q0 403 9.50 393.50Q19 384 32 384Q46 384 55 393L343 681ZM1792 1184L1792 1376Q1792 1389 1782.50 1398.50Q1773 1408 1760 1408L32 1408Q19 1408 9.50 1398.50Q0 1389 0 1376L0 1184Q0 1171 9.50 1161.50Q19 1152 32 1152L1760 1152Q1773 1152 1782.50 1161.50Q1792 1171 1792 1184ZM1792 800L1792 992Q1792 1005 1782.50 1014.50Q1773 1024 1760 1024L672 1024Q659 1024 649.50 1014.50Q640 1005 640 992L640 800Q640 787 649.50 777.50Q659 768 672 768L1760 768Q1773 768 1782.50 777.50Q1792 787 1792 800ZM1792 416L1792 608Q1792 621 1782.50 630.50Q1773 640 1760 640L672 640Q659 640 649.50 630.50Q640 621 640 608L640 416Q640 403 649.50 393.50Q659 384 672 384L1760 384Q1773 384 1782.50 393.50Q1792 403 1792 416ZM1792 32L1792 224Q1792 237 1782.50 246.50Q1773 256 1760 256L32 256Q19 256 9.50 246.50Q0 237 0 224L0 32Q0 19 9.50 9.50Q19 0 32 0L1760 0Q1773 0 1782.50 9.50Q1792 19 1792 32Z" />
                        </svg>
                    </div>
                    <div class="common-tools-dropdown" id="commonToolsDropdown">
                        <a href="javascript:void(0);" class="common-tools-trigger" id="commonToolsTrigger" data-demo-account="<?php echo function_exists('isDemoAdmin') && isDemoAdmin() ? '1' : '0'; ?>">常用工具</a>
                        <div class="common-tools-menu" id="commonToolsMenu"></div>
                    </div>
                    
                    <a href="javascript:void(0);" onclick="generateSitemap()">生成地图</a>
                    <a href="/" target="_blank">前台首页</a>
                </nav>
                <?php echo getGlobalHeaderUI($current_page, $posts_per_page); ?>
            </div>
            <div class="header-right">
                <script>
                    function generateSitemap() {
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', '/admin/admin.php?action=generate_sitemap', true);
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        xhr.onreadystatechange = function() {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                showToast('地图文件已生成', 'success', 2000);
                            }
                        };
                        xhr.send();
                    }
                </script>
                <div class="user-dropdown">
                    <div class="user-dropdown-trigger" onclick="toggleUserDropdown(event)"> 
                        <span class="user-name"><?php 
                            if (isset($_SESSION['username']) && $_SESSION['username'] === 'demo') {
                                echo '演示号';
                            } else {
                                echo escape($current_user ? $current_user['username'] : '管理员');
                            }
                        ?></span> 
                        <img src="<?php echo escape($current_user && $current_user['avatar'] ? $current_user['avatar'] : '/assets/images/admin.jpg'); ?>" alt="头像" class="user-avatar">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="dropdown-arrow">
                            <polyline points="6 9 12 15 18 9"></polyline>
                        </svg>
                    </div>
                    <div class="user-dropdown-menu" id="userDropdownMenu">
                        <div class="dropdown-header"> <span class="points-label" style="    width: 50px;">积分</span> <input type="number" id="userPoints" value="<?php echo intval($user_points); ?>" class="dropdown-input points-input"> </div>
                        <div class="dropdown-divider"></div>
                        <div class="dropdown-form">
                            <div class="password-input-wrapper">
                                <input type="password" id="oldPassword" placeholder="原密码" class="dropdown-input">
                                <span class="password-toggle" onclick="togglePasswordVisibility('oldPassword', this)">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="eye-icon">
                                        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                        <circle cx="12" cy="12" r="3"></circle>
                                    </svg>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="eye-off-icon" style="display: none;">
                                        <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
                                        <line x1="1" y1="1" x2="23" y2="23"></line>
                                    </svg>
                                </span>
                            </div>
                            <div class="password-input-wrapper">
                                <input type="password" id="newPassword" placeholder="新密码" class="dropdown-input">
                                <span class="password-toggle" onclick="togglePasswordVisibility('newPassword', this)">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="eye-icon">
                                        <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                        <circle cx="12" cy="12" r="3"></circle>
                                    </svg>
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="eye-off-icon" style="display: none;">
                                        <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path>
                                        <line x1="1" y1="1" x2="23" y2="23"></line>
                                    </svg>
                                </span>
                            </div>
                            <button class="dropdown-btn" onclick="updateUserInfo()">确认修改</button>
                        </div>
                        <div class="dropdown-divider"></div>
                        <a href="javascript:void(0);" class="dropdown-item logout-item" onclick="handleLogout(event)">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                                <polyline points="16 17 21 12 16 7"></polyline>
                                <line x1="21" y1="12" x2="9" y2="12"></line>
                            </svg>
                            退出登录 </a>
                    </div>
                </div>
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="3" y1="12" x2="21" y2="12"></line>
                        <line x1="3" y1="6" x2="21" y2="6"></line>
                        <line x1="3" y1="18" x2="21" y2="18"></line>
                    </svg>
                </button>
            </div>
        </div>
    </header>
    <div class="sidebar-overlay" onclick="toggleSidebar()"></div>
    <script>
        // 用户下拉菜单功能
        function toggleUserDropdown(event) {
            event.stopPropagation();
            const menu = document.getElementById('userDropdownMenu');
            menu.classList.toggle('show');
        }

        // 点击其他地方关闭下拉菜单
        document.addEventListener('click', function(event) {
            const dropdown = document.querySelector('.user-dropdown');
            const menu = document.getElementById('userDropdownMenu');
            if (dropdown && !dropdown.contains(event.target)) {
                menu.classList.remove('show');
            }
        });

        // 切换密码可见性
        function togglePasswordVisibility(inputId, toggleElement) {
            const input = document.getElementById(inputId);
            const eyeIcon = toggleElement.querySelector('.eye-icon');
            const eyeOffIcon = toggleElement.querySelector('.eye-off-icon');

            if (input.type === 'password') {
                input.type = 'text';
                eyeIcon.style.display = 'none';
                eyeOffIcon.style.display = 'block';
            } else {
                input.type = 'password';
                eyeIcon.style.display = 'block';
                eyeOffIcon.style.display = 'none';
            }
        }

        // 更新用户信息功能（密码和积分）
        function updateUserInfo() {
            const oldPassword = document.getElementById('oldPassword').value.trim();
            const newPassword = document.getElementById('newPassword').value.trim();
            const userPoints = document.getElementById('userPoints').value.trim();

            // 验证积分输入
            if (!userPoints || isNaN(userPoints) || parseInt(userPoints) < 0) {
                showToast('请输入有效的积分值', 'error');
                return;
            }

            // 如果要修改密码，验证密码输入
            if (newPassword) {
                if (!oldPassword) {
                    showToast('请输入原密码', 'error');
                    return;
                }
                if (newPassword.length < 6) {
                    showToast('新密码至少6位', 'error');
                    return;
                }
            }

            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/admin/admin.php?action=update_user_info', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            showToast('信息更新成功', 'info');
                            document.getElementById('oldPassword').value = '';
                            document.getElementById('newPassword').value = '';
                            document.getElementById('userDropdownMenu').classList.remove('show');
                        } else {
                            showToast(response.message || '信息更新失败', 'error');
                        }
                    } catch (e) {
                        showToast('信息更新失败', 'error');
                    }
                }
            };
            xhr.send('old_password=' + encodeURIComponent(oldPassword) + '&new_password=' + encodeURIComponent(newPassword) + '&points=' + encodeURIComponent(userPoints));
        }

        function handleLogout(event) {
            event.preventDefault();
            // 触发全局同步退出信号
            if (window.LoginSync && window.LoginSync.triggerLogout) {
                window.LoginSync.triggerLogout();
            } else {
                localStorage.setItem('qkcms_logout_sync', JSON.stringify({
                    action: 'logout',
                    time: Date.now()
                }));
            }
            try {
                const loginKeys = [
                    'qkcms_logged_in', 'username', 'user_id', 'is_logged_in',
                    'admin_logged_in', 'auth_token', 'session_data',
                    'login_time', 'last_activity'
                ];
                loginKeys.forEach(key => {
                    localStorage.removeItem(key);
                });
                loginKeys.forEach(key => {
                    sessionStorage.removeItem(key);
                });
                if (document.body.classList.contains('logged-in')) {
                    document.body.classList.remove('logged-in');
                }
                if (document.documentElement.classList.contains('user-logged-in')) {
                    document.documentElement.classList.remove('user-logged-in');
                }
                document.cookie.split(";").forEach(function(c) {
                    const cookieName = c.split('=')[0].trim();
                    if (cookieName.includes('PHPSESSID') ||
                        cookieName.includes('session') ||
                        cookieName.includes('user') ||
                        cookieName.includes('auth')) {
                        document.cookie = cookieName + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
                    }
                });
            } catch (e) {}
            window.stop();
            const randomParam = '?_=' + new Date().getTime();
            setTimeout(function() {
                window.location.href = '/admin/login.php?action=logout' + randomParam;
            }, 500);
        }

        function toggleSidebar() {
            const sidebar = document.querySelector('.admin-sidebar');
            const overlay = document.querySelector('.sidebar-overlay');
            if (sidebar) {
                sidebar.classList.toggle('active');
            }
            if (overlay) {
                overlay.classList.toggle('active');
            }
            document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
            
            // 触发一个自定义事件，通知其他组件侧边栏状态已改变
            document.dispatchEvent(new CustomEvent('sidebarToggled'));
        }

        // 更新分类模板
        function updateCategoryTemplate(categoryId, template) {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/admin/admin.php?action=update_category_template', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            showToast('模板更新成功', 'info');
                            // 不需要刷新整个列表，只更新当前行的模板状态
                            const selectElement = document.querySelector('select[onchange="updateCategoryTemplate(' + categoryId + ', this.value)"]');
                            if (selectElement) {
                                // 保持当前选择状态
                                selectElement.value = template;
                            }
                        } else {
                            showToast('模板更新失败', 'error');
                        }
                    } catch (e) {
                        showToast('模板更新失败', 'error');
                    }
                }
            };
            xhr.send('category_id=' + categoryId + '&template=' + encodeURIComponent(template));
        }

        // 编辑分类自定义URL
        function editCategoryCustomUrl(categoryId) {
            const cell = document.querySelector('.category-custom-url-cell[data-category-id="' + categoryId + '"]');
            if (!cell) return;

            const display = cell.querySelector('.custom-url-display');
            const input = cell.querySelector('.custom-url-input');

            display.style.display = 'none';
            input.style.display = 'inline-block';
            input.focus();
            input.select();
        }

        // 取消编辑分类自定义URL
        function cancelEditCategoryCustomUrl(categoryId) {
            const cell = document.querySelector('.category-custom-url-cell[data-category-id="' + categoryId + '"]');
            if (!cell) return;

            const display = cell.querySelector('.custom-url-display');
            const input = cell.querySelector('.custom-url-input');
            const originalUrl = display.getAttribute('data-original-url') || '';

            input.value = originalUrl;
            input.style.display = 'none';
            display.style.display = 'inline';
        }

        // 保存分类自定义URL
        function saveCategoryCustomUrl(categoryId, input) {
            const cell = document.querySelector('.category-custom-url-cell[data-category-id="' + categoryId + '"]');
            if (!cell) return;

            const display = cell.querySelector('.custom-url-display');
            const newUrl = input.value.trim();
            const originalUrl = display.getAttribute('data-original-url') || '';
            const defaultUrl = display.getAttribute('data-default-url') || 'list_id' + categoryId + '.html';

            // 隐藏输入框，显示文本
            input.style.display = 'none';
            display.style.display = 'inline';

            // 如果没有变化，不保存也不提示
            if (newUrl === originalUrl) {
                return;
            }

            // 如果留空，自动恢复默认URL
            if (!newUrl) {
                display.innerHTML = defaultUrl;
                display.setAttribute('data-original-url', defaultUrl);
                input.value = defaultUrl;
                // 清空数据库中的自定义URL，不显示成功提示
                saveCategoryCustomUrlToServer(categoryId, '', display, defaultUrl, false);
                return;
            }

            // 验证URL格式
            if (!/^[a-zA-Z0-9_-]+\.(html|php)$/.test(newUrl)) {
                // 使用全局确认框
                callParentConfirm('URL格式错误！\n\n只能包含字母、数字、下划线、连字符，且必须以.html或.php结尾\n\n点击确定恢复默认值').then(function(result) {
                    if (result) {
                        display.innerHTML = defaultUrl;
                        display.setAttribute('data-original-url', defaultUrl);
                        input.value = defaultUrl;
                        // 清空数据库中的自定义URL，不显示成功提示
                        saveCategoryCustomUrlToServer(categoryId, '', display, defaultUrl, false);
                    }
                });
                return;
            }

            // 发送AJAX请求保存，显示成功提示
            saveCategoryCustomUrlToServer(categoryId, newUrl, display, defaultUrl, true);
        }

        // 发送保存请求到服务器
        function saveCategoryCustomUrlToServer(categoryId, customUrl, display, defaultUrl, showSuccessToast = true) {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/admin/admin.php?action=update_category_custom_url', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            if (showSuccessToast) {
                            showToast('自定义URL更新成功', 'info');
                            }
                            const newUrl = customUrl ? customUrl : defaultUrl;
                            display.innerHTML = newUrl;
                            display.setAttribute('data-original-url', newUrl);
                            // 不需要刷新整个列表，只更新当前显示
                            const input = display.nextElementSibling;
                            if (input && input.classList.contains('custom-url-input')) {
                                input.value = newUrl;
                            }
                        } else {
                            // 使用全局确认框显示错误
                            callParentConfirm('保存失败：' + (response.message || '未知错误') + '\n\n点击确定恢复默认值').then(function(result) {
                                display.innerHTML = defaultUrl;
                                display.setAttribute('data-original-url', '');
                                const input = display.nextElementSibling;
                                if (input && input.classList.contains('custom-url-input')) {
                                    input.value = defaultUrl;
                                }
                            });
                        }
                    } catch (e) {
                        showToast('更新失败', 'error');
                    }
                }
            };
            xhr.send('category_id=' + categoryId + '&custom_url=' + encodeURIComponent(customUrl));
        }

        // HTML转义函数
        function escape(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }





        // 导航链接点击优化：先选中再跳转
        function restoreAdminSidebarScroll() {
            try {
                const saved = sessionStorage.getItem('qk_admin_sidebar_scroll');
                if (!saved) return;
                const data = JSON.parse(saved);
                if (!data || typeof data.top !== 'number') return;
                if (data.ts && (Date.now() - data.ts) > 24 * 60 * 60 * 1000) return;
                const sidebar = document.querySelector('.admin-sidebar');
                if (!sidebar) return;
                sidebar.scrollTop = data.top;
            } catch (e) {}
        }

        function saveAdminSidebarScroll() {
            try {
                const sidebar = document.querySelector('.admin-sidebar');
                if (!sidebar) return;
                sessionStorage.setItem('qk_admin_sidebar_scroll', JSON.stringify({
                    top: sidebar.scrollTop || 0,
                    ts: Date.now()
                }));
            } catch (e) {}
        }

        window.addEventListener('pagehide', saveAdminSidebarScroll, { capture: true });
        window.addEventListener('beforeunload', saveAdminSidebarScroll, { capture: true });

        function initNavigationEvents() {
            const navLinks = document.querySelectorAll('.admin-sidebar a[href^="/admin?tab="]');
            navLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    document.dispatchEvent(new CustomEvent('qk-admin-page-leave'));
                    saveAdminSidebarScroll();
                    // 立即更新导航选中状态
                    const activeLink = document.querySelector('.admin-sidebar a.active');
                    if (activeLink) {
                        activeLink.classList.remove('active');
                    }
                    this.classList.add('active');

                    // 直接跳转，不使用preventDefault避免可能的卡顿
                    // 浏览器会自然处理跳转，同时用户能看到选中状态
                });
            });
        }

        // 搜索相关代码已移至页面底部公用代码区

        function initPageEvents() {
            // 初始化分页按钮事件
            const paginationButtons = document.querySelectorAll('.pagination-btn:not(.disabled)');
            paginationButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    const href = this.getAttribute('href');
                    if (!href) return;
                    loadPageContent(href);
                });
            });
            // 初始化批量操作功能
            if (typeof initBatchOperations === 'function') {
                initBatchOperations();
            }
        }

        function loadPageContent(url) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = xhr.responseText;
                    const newContent = tempDiv.querySelector('.admin-content');
                    const currentContent = document.querySelector('.admin-content');

                    if (newContent && currentContent) {
                        currentContent.innerHTML = newContent.innerHTML;

                        // 手动提取并执行加载内容中的脚本
                        const scripts = newContent.querySelectorAll('script');
                        let scriptsLoaded = 0;
                        const externalScripts = Array.from(scripts).filter(s => s.src);
                        const totalExternalScripts = externalScripts.length;

                        function runInternalScripts() {
                            scripts.forEach(oldScript => {
                                if (!oldScript.src) {
                                    const newScript = document.createElement('script');
                                    newScript.textContent = oldScript.textContent;
                                    document.body.appendChild(newScript);
                                    // 内部脚本执行后立即移除
                                    if (newScript.parentNode) newScript.parentNode.removeChild(newScript);
                                }
                            });

                            // 所有外部脚本和内部脚本处理完后，执行页面初始化
                            setTimeout(() => {
                                if (typeof initializeAdgoodsPage === 'function') {
                                    initializeAdgoodsPage();
                                }
                                initPageEvents();
                                if (typeof HeaderPagination !== 'undefined' && document.getElementById('top-page-control')) {
                                    HeaderPagination.updateUI();
                                }
                            }, 100);
                        }

                        if (totalExternalScripts > 0) {
                            externalScripts.forEach(oldScript => {
                                const newScript = document.createElement('script');
                                Array.from(oldScript.attributes).forEach(attr => {
                                    newScript.setAttribute(attr.name, attr.value);
                                });
                                newScript.onload = () => {
                                    scriptsLoaded++;
                                    if (scriptsLoaded === totalExternalScripts) {
                                        runInternalScripts();
                                    }
                                };
                                newScript.onerror = () => {
                                    scriptsLoaded++;
                                    if (scriptsLoaded === totalExternalScripts) {
                                        runInternalScripts();
                                    }
                                };
                                document.body.appendChild(newScript);
                            });
                        } else {
                            runInternalScripts();
                        }
                    }
                } else {
                    showToast('页面加载失败，请重试', 'error');
                }
            };
            xhr.onerror = function() {
                showToast('网络错误，请重试', 'error');
            };
            xhr.send();
        }
        document.addEventListener('DOMContentLoaded', function() {
            initPageEvents();
            initNavigationEvents();
        });
    </script>
    <div class="admin-sidebar qk-sidebar-v2">
        <script>
            (function() {
                try {
                    const saved = sessionStorage.getItem('qk_admin_sidebar_scroll');
                    if (!saved) return;
                    const data = JSON.parse(saved);
                    if (!data || typeof data.top !== 'number') return;
                    if (data.ts && (Date.now() - data.ts) > 24 * 60 * 60 * 1000) return;
                    const sidebar = document.querySelector('.admin-sidebar');
                    if (!sidebar) return;
                    sidebar.scrollTop = data.top;
                    requestAnimationFrame(function() {
                        sidebar.scrollTop = data.top;
                    });
                } catch (e) {}
            })();
        </script>
        <ul class="sidebar-menu">
            <li class="sidebar-menu-item">
                <a href="/admin?tab=metrics" class="sidebar-menu-link top-level <?php echo $active_tab == 'metrics' ? 'active' : ''; ?>" title="后台首页">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="23" height="23" fill="currentColor"><path d="M1023.616 555.52h-85.333333c0-234.752-191.018667-425.770667-425.770667-425.770667-234.752 0-425.770667 191.018667-425.770667 425.770667h-85.333333c0-281.813333 229.290667-511.104 511.104-511.104S1023.616 273.706667 1023.616 555.52zM512.512 939.989333c-103.68 0-187.989333-84.352-187.989333-187.989333s84.352-187.989333 187.989333-187.989333c103.637333 0 187.989333 84.352 187.989333 187.989333s-84.352 187.989333-187.989333 187.989333z m0-290.645333c-56.618667 0-102.656 46.037333-102.656 102.656s46.08 102.656 102.656 102.656 102.656-46.037333 102.656-102.656-46.037333-102.656-102.656-102.656z"></path><path d="M555.178667 566.016c0 22.442667-19.072 40.661333-42.666667 40.661333-23.552 0-42.666667-18.218667-42.666667-40.661333V311.338667c0-22.442667 19.114667-40.661333 42.666667-40.661334s42.666667 18.218667 42.666667 40.661334v254.677333z"></path></svg>
                    <span class="link-text">
                        <span class="link-text-default">后台首页</span>
                        <span class="link-text-short" style="display: none;">首页</span>
                    </span>
                </a>
            </li>
            <li class="sidebar-menu-item">
                <a href="/admin?tab=settings" class="sidebar-menu-link top-level <?php echo ($active_tab == 'settings' && !isset($_GET['nav'])) ? 'active' : ''; ?>" title="网站设置">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
                    <span class="link-text">
                        <span class="link-text-default">网站设置</span>
                        <span class="link-text-short" style="display: none;">设置</span>
                    </span>
                </a>
            </li>
        </ul>

        <div class="sidebar-section menu-dropdown">
            <a href="#" class="sidebar-section-title" onclick="toggleMenu('content-menu'); return false;" title="内容">
                <svg class="sidebar-section-icon" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                <span class="sidebar-section-line sidebar-section-line-left" aria-hidden="true"></span>
                <span class="sidebar-section-text">内容</span>
                <span class="sidebar-section-line sidebar-section-line-right" aria-hidden="true"></span>
            </a>
            <ul class="sidebar-menu dropdown-content" id="content-menu">
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=navigation" class="sidebar-menu-link <?php echo ($active_tab == 'navigation') ? 'active' : ''; ?>" title="导航管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="3 11 22 2 13 21 11 13 3 11"></polygon></svg>
                        <span class="link-text">
                            <span class="link-text-default">导航管理</span>
                            <span class="link-text-short" style="display: none;">导航</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=adcategory" class="sidebar-menu-link <?php echo $active_tab == 'adcategory' ? 'active' : ''; ?>" title="栏目管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
                        <span class="link-text">
                            <span class="link-text-default">栏目管理</span>
                            <span class="link-text-short" style="display: none;">栏目</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=articles" class="sidebar-menu-link <?php echo $active_tab == 'articles' ? 'active' : ''; ?>" title="文章管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>
                        <span class="link-text">
                            <span class="link-text-default">文章管理</span>
                            <span class="link-text-short" style="display: none;">文章</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=adgoods" class="sidebar-menu-link <?php echo $active_tab == 'adgoods' ? 'active' : ''; ?>" title="商品管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>
                        <span class="link-text">
                            <span class="link-text-default">商品管理</span>
                            <span class="link-text-short" style="display: none;">商品</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=tagSearch&tag" class="sidebar-menu-link <?php echo $active_tab == 'tagSearch' ? 'active' : ''; ?>" title="词库管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line></svg>
                        <span class="link-text">
                            <span class="link-text-default">词库管理</span>
                            <span class="link-text-short" style="display: none;">词库</span>
                        </span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section menu-dropdown">
            <a href="#" class="sidebar-section-title" onclick="toggleMenu('user-menu'); return false;" title="互动">
                <svg class="sidebar-section-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                <span class="sidebar-section-line sidebar-section-line-left" aria-hidden="true"></span>
                <span class="sidebar-section-text">互动</span>
                <span class="sidebar-section-line sidebar-section-line-right" aria-hidden="true"></span>
            </a>
            <ul class="sidebar-menu dropdown-content" id="user-menu">
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=users" class="sidebar-menu-link <?php echo $active_tab == 'users' ? 'active' : ''; ?>" title="用户管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                        <span class="link-text">
                            <span class="link-text-default">用户管理</span>
                            <span class="link-text-short" style="display: none;">用户</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=comments" class="sidebar-menu-link <?php echo $active_tab == 'comments' ? 'active' : ''; ?>" title="评论管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
                        <span class="link-text">
                            <span class="link-text-default">评论管理</span>
                            <span class="link-text-short" style="display: none;">评论</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=reports" class="sidebar-menu-link <?php echo $active_tab == 'reports' ? 'active' : ''; ?>" title="举报管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
                        <span class="link-text">
                            <span class="link-text-default">举报管理</span>
                            <span class="link-text-short" style="display: none;">举报</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=publish" class="sidebar-menu-link <?php echo $active_tab == 'publish' ? 'active' : ''; ?>" title="投稿管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19l7-7 3 3-7 7-3-3z"></path><path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"></path><path d="M2 2l7.586 7.586"></path><circle cx="11" cy="11" r="2"></circle></svg>
                        <span class="link-text">
                            <span class="link-text-default">投稿管理</span>
                            <span class="link-text-short" style="display: none;">投稿</span>
                        </span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section menu-dropdown">
            <a href="#" class="sidebar-section-title" onclick="toggleMenu('extension-menu'); return false;" title="扩展">
                <svg class="sidebar-section-icon" xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="width:22px;height:22px;"><path d="M12 22v-5"></path><path d="M9 8V2"></path><path d="M15 8V2"></path><path d="M18 8v4a6 6 0 0 1-12 0V8Z"></path><path d="M5 8h14"></path></svg>
                <span class="sidebar-section-line sidebar-section-line-left" aria-hidden="true"></span>
                <span class="sidebar-section-text">扩展</span>
                <span class="sidebar-section-line sidebar-section-line-right" aria-hidden="true"></span>
            </a>
            <ul class="sidebar-menu dropdown-content" id="extension-menu">
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=plugin" class="sidebar-menu-link <?php echo ($active_tab == 'plugin' || $active_tab == 'CloudPlug') ? 'active' : ''; ?>" title="扩展管理">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="width:20px;height:20px;"><path d="M12 22v-5"></path><path d="M9 8V2"></path><path d="M15 8V2"></path><path d="M18 8v4a6 6 0 0 1-12 0V8Z"></path><path d="M5 8h14"></path></svg>
                        <span class="link-text">
                            <span class="link-text-default">扩展管理</span>
                            <span class="link-text-short" style="display: none;">扩展</span>
                        </span>
                    </a>
                </li>
                <li class="sidebar-menu-item">
                    <a href="/admin?tab=template" class="sidebar-menu-link <?php echo $active_tab == 'template' ? 'active' : ''; ?>" title="模板市场">
                        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22a10 10 0 1 1 10-10c0 1.38-.56 2.63-1.46 3.54-.91.9-2.16 1.46-3.54 1.46h-1.2a1.8 1.8 0 0 0-1.8 1.8 3.2 3.2 0 0 1-3.2 3.2Z"></path><circle cx="7.5" cy="10.5" r="1"></circle><circle cx="12" cy="7.5" r="1"></circle><circle cx="16.5" cy="10.5" r="1"></circle></svg>
                        <span class="link-text">
                            <span class="link-text-default">模板市场</span>
                            <span class="link-text-short" style="display: none;">模板</span>
                        </span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-divider"></div>

        <ul class="sidebar-menu">
            <li class="sidebar-menu-item">
                <a href="/admin?tab=order" class="sidebar-menu-link top-level <?php echo $active_tab == 'order' ? 'active' : ''; ?>" title="订单管理">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>
                    <span class="link-text">
                        <span class="link-text-default">订单管理</span>
                        <span class="link-text-short" style="display: none;">订单</span>
                    </span>
                </a>
            </li>
            <li class="sidebar-menu-item">
                <a href="/admin?tab=counter" class="sidebar-menu-link top-level <?php echo $active_tab == 'counter' ? 'active' : ''; ?>" title="流量统计">
                    <svg xmlns="http://www.w3.org/2000/svg" width="22" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
                    <span class="link-text">
                        <span class="link-text-default">流量统计</span>
                        <span class="link-text-short" style="display: none;">统计</span>
                    </span>
                </a>
            </li>
        </ul>
        <script>
            function toggleMenu(menuId) {
                var menu = document.getElementById(menuId);
                var arrow = menu.parentNode.querySelector('.dropdown-arrow');
                if (event) event.stopPropagation();
                var computedStyle = window.getComputedStyle(menu);
                var isVisible = computedStyle.display !== 'none';
                if (!isVisible) {
                    menu.style.display = 'block';
                    if (arrow) arrow.style.transform = 'rotate(180deg)';
                    localStorage.setItem('menu_' + menuId, 'expanded');
                } else {
                    menu.style.display = 'none';
                    if (arrow) arrow.style.transform = 'rotate(0deg)';
                    localStorage.setItem('menu_' + menuId, 'collapsed');
                }
            }
            (function() {
                var menuIds = ['content-menu', 'user-menu', 'extension-menu'];
                var initialStyles = window._menuInitialStyles || {};
                menuIds.forEach(function(menuId) {
                    var menu = document.getElementById(menuId);
                    if (menu) {
                        var arrow = menu.parentNode.querySelector('.dropdown-arrow');
                        var shouldShow = initialStyles[menuId] !== false;
                        if (shouldShow) {
                            menu.style.display = 'block';
                            if (arrow) {
                                arrow.style.transform = 'rotate(180deg)';
                            }
                        } else {
                            menu.style.display = 'none';
                            if (arrow) {
                                arrow.style.transform = 'rotate(0deg)';
                            }
                        }
                    }
                });
            })();
            document.addEventListener('click', function(event) {});
        </script>


        <script>
            // 导航收缩/展开功能
            (function() {
                const sidebarToggleBtn = document.getElementById('sidebarToggleBtn');
                const adminSidebar = document.querySelector('.admin-sidebar');
                const mainContent = document.querySelector('.main');
                const footer = document.querySelector('.footer');

                // 从localStorage读取状态
                const isCollapsed = localStorage.getItem('sidebar_collapsed') === 'true';

                // 初始化状态
                if (isCollapsed) {
                    document.body.classList.add('sidebar-collapsed');
                    sidebarToggleBtn.title = '展开导航';
                    // 收缩状态：展开图标
                    sidebarToggleBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 1792 1408" fill="var(--primary-color)"><path d="M343 681Q352 690 352 704Q352 718 343 727L55 1015Q46 1024 32 1024Q19 1024 9.50 1014.50Q0 1005 0 992L0 416Q0 403 9.50 393.50Q19 384 32 384Q46 384 55 393L343 681ZM1792 1184L1792 1376Q1792 1389 1782.50 1398.50Q1773 1408 1760 1408L32 1408Q19 1408 9.50 1398.50Q0 1389 0 1376L0 1184Q0 1171 9.50 1161.50Q19 1152 32 1152L1760 1152Q1773 1152 1782.50 1161.50Q1792 1171 1792 1184ZM1792 800L1792 992Q1792 1005 1782.50 1014.50Q1773 1024 1760 1024L672 1024Q659 1024 649.50 1014.50Q640 1005 640 992L640 800Q640 787 649.50 777.50Q659 768 672 768L1760 768Q1773 768 1782.50 777.50Q1792 787 1792 800ZM1792 416L1792 608Q1792 621 1782.50 630.50Q1773 640 1760 640L672 640Q659 640 649.50 630.50Q640 621 640 608L640 416Q640 403 649.50 393.50Q659 384 672 384L1760 384Q1773 384 1782.50 393.50Q1792 403 1792 416ZM1792 32L1792 224Q1792 237 1782.50 246.50Q1773 256 1760 256L32 256Q19 256 9.50 246.50Q0 237 0 224L0 32Q0 19 9.50 9.50Q19 0 32 0L1760 0Q1773 0 1782.50 9.50Q1792 19 1792 32Z"/></svg>`;
                } else {
                    sidebarToggleBtn.title = '收起导航';
                    // 展开状态：收缩图标
                    sidebarToggleBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 1792 1408" fill="#9ca3af"><path d="M384 416L384 992Q384 1005 374.50 1014.50Q365 1024 352 1024Q338 1024 329 1015L41 727Q32 718 32 704Q32 690 41 681L329 393Q338 384 352 384Q365 384 374.50 393.50Q384 403 384 416ZM1792 1184L1792 1376Q1792 1389 1782.50 1398.50Q1773 1408 1760 1408L32 1408Q19 1408 9.50 1398.50Q0 1389 0 1376L0 1184Q0 1171 9.50 1161.50Q19 1152 32 1152L1760 1152Q1773 1152 1782.50 1161.50Q1792 1171 1792 1184ZM1792 800L1792 992Q1792 1005 1782.50 1014.50Q1773 1024 1760 1024L672 1024Q659 1024 649.50 1014.50Q640 1005 640 992L640 800Q640 787 649.50 777.50Q659 768 672 768L1760 768Q1773 768 1782.50 777.50Q1792 787 1792 800ZM1792 416L1792 608Q1792 621 1782.50 630.50Q1773 640 1760 640L672 640Q659 640 649.50 630.50Q640 621 640 608L640 416Q640 403 649.50 393.50Q659 384 672 384L1760 384Q1773 384 1782.50 393.50Q1792 403 1792 416ZM1792 32L1792 224Q1792 237 1782.50 246.50Q1773 256 1760 256L32 256Q19 256 9.50 246.50Q0 237 0 224L0 32Q0 19 9.50 9.50Q19 0 32 0L1760 0Q1773 0 1782.50 9.50Q1792 19 1792 32Z"/></svg>`;
                }

                // 点击切换
                sidebarToggleBtn.addEventListener('mousedown', function(e) {
                    e.preventDefault(); // 阻止默认的文本选中行为
                });
                
                sidebarToggleBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    // 清除可能存在的文本选中状态
                    if (window.getSelection) {
                        window.getSelection().removeAllRanges();
                    } else if (document.selection) {
                        document.selection.empty();
                    }

                    if (typeof showTimeout !== 'undefined' && showTimeout) {
                        clearTimeout(showTimeout);
                        showTimeout = null;
                    }
                    if (typeof hideTimeout !== 'undefined' && hideTimeout) {
                        clearTimeout(hideTimeout);
                        hideTimeout = null;
                    }

                    document.querySelectorAll('.dropdown-content.popup-menu').forEach(menu => {
                        menu.classList.remove('popup-menu');
                        menu.style.display = 'none';
                        menu.style.top = '';
                        menu.style.left = '';
                    });
                    document.querySelectorAll('.admin-sidebar .menu-dropdown > a.active').forEach(link => {
                        link.classList.remove('active');
                    });
                    
                    const isNowCollapsed = document.body.classList.toggle('sidebar-collapsed');
                    localStorage.setItem('sidebar_collapsed', isNowCollapsed);
                    
                    // 触发侧边栏切换事件，关闭可能打开的下拉菜单
                    document.dispatchEvent(new CustomEvent('sidebarToggled'));

                    if (isNowCollapsed) {
                        this.title = '展开导航';
                        // 收缩状态：展开图标
                        this.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 1792 1408" fill="var(--primary-color)"><path d="M343 681Q352 690 352 704Q352 718 343 727L55 1015Q46 1024 32 1024Q19 1024 9.50 1014.50Q0 1005 0 992L0 416Q0 403 9.50 393.50Q19 384 32 384Q46 384 55 393L343 681ZM1792 1184L1792 1376Q1792 1389 1782.50 1398.50Q1773 1408 1760 1408L32 1408Q19 1408 9.50 1398.50Q0 1389 0 1376L0 1184Q0 1171 9.50 1161.50Q19 1152 32 1152L1760 1152Q1773 1152 1782.50 1161.50Q1792 1171 1792 1184ZM1792 800L1792 992Q1792 1005 1782.50 1014.50Q1773 1024 1760 1024L672 1024Q659 1024 649.50 1014.50Q640 1005 640 992L640 800Q640 787 649.50 777.50Q659 768 672 768L1760 768Q1773 768 1782.50 777.50Q1792 787 1792 800ZM1792 416L1792 608Q1792 621 1782.50 630.50Q1773 640 1760 640L672 640Q659 640 649.50 630.50Q640 621 640 608L640 416Q640 403 649.50 393.50Q659 384 672 384L1760 384Q1773 384 1782.50 393.50Q1792 403 1792 416ZM1792 32L1792 224Q1792 237 1782.50 246.50Q1773 256 1760 256L32 256Q19 256 9.50 246.50Q0 237 0 224L0 32Q0 19 9.50 9.50Q19 0 32 0L1760 0Q1773 0 1782.50 9.50Q1792 19 1792 32Z"/></svg>`;
                        // 收缩时关闭所有子菜单
                        const dropdowns = document.querySelectorAll('.dropdown-content');
                        dropdowns.forEach(menu => {
                            menu.style.display = 'none';
                            const arrow = menu.parentNode.querySelector('.dropdown-arrow');
                            if (arrow) arrow.style.transform = 'rotate(0deg)';
                        });
                    } else {
                        this.title = '收起导航';
                        // 展开状态：收缩图标
                        this.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 1792 1408" fill="#9ca3af"><path d="M384 416L384 992Q384 1005 374.50 1014.50Q365 1024 352 1024Q338 1024 329 1015L41 727Q32 718 32 704Q32 690 41 681L329 393Q338 384 352 384Q365 384 374.50 393.50Q384 403 384 416ZM1792 1184L1792 1376Q1792 1389 1782.50 1398.50Q1773 1408 1760 1408L32 1408Q19 1408 9.50 1398.50Q0 1389 0 1376L0 1184Q0 1171 9.50 1161.50Q19 1152 32 1152L1760 1152Q1773 1152 1782.50 1161.50Q1792 1171 1792 1184ZM1792 800L1792 992Q1792 1005 1782.50 1014.50Q1773 1024 1760 1024L672 1024Q659 1024 649.50 1014.50Q640 1005 640 992L640 800Q640 787 649.50 777.50Q659 768 672 768L1760 768Q1773 768 1782.50 777.50Q1792 787 1792 800ZM1792 416L1792 608Q1792 621 1782.50 630.50Q1773 640 1760 640L672 640Q659 640 649.50 630.50Q640 621 640 608L640 416Q640 403 649.50 393.50Q659 384 672 384L1760 384Q1773 384 1782.50 393.50Q1792 403 1792 416ZM1792 32L1792 224Q1792 237 1782.50 246.50Q1773 256 1760 256L32 256Q19 256 9.50 246.50Q0 237 0 224L0 32Q0 19 9.50 9.50Q19 0 32 0L1760 0Q1773 0 1782.50 9.50Q1792 19 1792 32Z"/></svg>`;
                        // 展开时恢复之前保存的子菜单状态
                        document.querySelectorAll('.dropdown-content').forEach(menu => {
                            const menuId = menu.id;
                            if (menuId) {
                                const savedState = localStorage.getItem('menu_' + menuId);
                                if (savedState === 'expanded') {
                                    menu.style.display = 'block';
                                    const arrow = menu.parentNode.querySelector('.dropdown-arrow');
                                    if (arrow) arrow.style.transform = 'rotate(180deg)';
                                }
                            }
                        });
                    }
                });

                // 处理菜单悬停 - 在收缩状态下鼠标悬停显示右侧弹出菜单
                const menuDropdowns = document.querySelectorAll('.menu-dropdown > a');
                let hideTimeout = null;
                let showTimeout = null;

                menuDropdowns.forEach(dropdown => {
                    // 鼠标进入导航项
                    dropdown.addEventListener('mouseenter', function(e) {
                        // 如果处于收缩状态，显示右侧弹出菜单
                        if (document.body.classList.contains('sidebar-collapsed')) {
                            // 清除隐藏定时器
                            if (hideTimeout) {
                                clearTimeout(hideTimeout);
                                hideTimeout = null;
                            }

                            // 清除之前的显示定时器
                            if (showTimeout) {
                                clearTimeout(showTimeout);
                            }

                            // 延迟显示，避免误触发
                            showTimeout = setTimeout(() => {
                                // 获取菜单ID
                                const onclickAttr = this.getAttribute('onclick');
                                if (!onclickAttr) return;
                                
                                const match = onclickAttr.match(/toggleMenu\('([^']+)'\)/);
                                if (!match) return;
                                
                                const menuId = match[1];
                                const menu = document.getElementById(menuId);

                                // 检查当前菜单是否已显示
                                const isVisible = menu && menu.classList.contains('popup-menu');

                                // 移除所有主导航的选中状态
                                document.querySelectorAll('.admin-sidebar > a, .admin-sidebar .menu-dropdown > a').forEach(link => {
                                    link.classList.remove('active');
                                });

                                // 关闭所有弹出菜单
                                document.querySelectorAll('.dropdown-content.popup-menu').forEach(m => {
                                    m.classList.remove('popup-menu');
                                    m.style.display = 'none';
                                    m.style.top = '';
                                    m.style.left = '';
                                });

                                // 如果当前菜单未显示，则显示它并添加选中状态
                                if (menu && !isVisible) {
                                    this.classList.add('active');
                                    menu.classList.add('popup-menu');
                                    menu.style.display = 'block';

                                    // 设置弹出菜单位置与悬停的图标顶部对齐
                                    const rect = this.getBoundingClientRect();
                                    menu.style.top = (rect.top - 3) + 'px';
                                    menu.style.left = '55px';
                                }
                            }, 50);
                        }
                    });

                    // 鼠标离开导航项
                    dropdown.addEventListener('mouseleave', function(e) {
                        // 如果处于收缩状态，延迟隐藏弹出菜单
                        if (document.body.classList.contains('sidebar-collapsed')) {
                            // 清除显示定时器
                            if (showTimeout) {
                                clearTimeout(showTimeout);
                                showTimeout = null;
                            }

                            hideTimeout = setTimeout(() => {
                                document.querySelectorAll('.dropdown-content.popup-menu').forEach(menu => {
                                    menu.classList.remove('popup-menu');
                                    menu.style.display = 'none';
                                    menu.style.top = '';
                                    menu.style.left = '';
                                });
                                document.querySelectorAll('.admin-sidebar .menu-dropdown > a.active').forEach(link => {
                                    link.classList.remove('active');
                                });
                            }, 400);
                        }
                    });
                });

                // 处理弹出菜单的悬停
                const dropdownContents = document.querySelectorAll('.dropdown-content');
                dropdownContents.forEach(menu => {
                    // 鼠标进入弹出菜单
                    menu.addEventListener('mouseenter', function() {
                        if (this.classList.contains('popup-menu')) {
                            // 清除隐藏定时器
                            if (hideTimeout) {
                                clearTimeout(hideTimeout);
                                hideTimeout = null;
                            }
                        }
                    });

                    // 鼠标离开弹出菜单
                    menu.addEventListener('mouseleave', function() {
                        if (this.classList.contains('popup-menu')) {
                            hideTimeout = setTimeout(() => {
                                this.classList.remove('popup-menu');
                                this.style.display = 'none';
                                this.style.top = '';
                                this.style.left = '';
                                const parentDropdown = this.closest('.menu-dropdown');
                                if (parentDropdown) {
                                    const parentLink = parentDropdown.querySelector('a');
                                    if (parentLink) {
                                        parentLink.classList.remove('active');
                                    }
                                }
                            }, 400);
                        }
                    });
                });

                // 点击其他地方关闭弹出菜单
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('.menu-dropdown')) {
                        document.querySelectorAll('.dropdown-content.popup-menu').forEach(menu => {
                            menu.classList.remove('popup-menu');
                            menu.style.display = 'none';
                            menu.style.top = '';
                            menu.style.left = '';
                        });
                        // 移除选中状态
                        document.querySelectorAll('.admin-sidebar .menu-dropdown > a.active').forEach(link => {
                            link.classList.remove('active');
                        });
                    }
                    
                    // 确保点击其他地方时，常用工具下拉菜单也会关闭
                    const commonToolsDropdown = document.getElementById('commonToolsDropdown');
                    if (commonToolsDropdown && commonToolsDropdown.classList.contains('show') && !e.target.closest('#commonToolsDropdown')) {
                        commonToolsDropdown.classList.remove('show');
                    }
                });
            })();
        </script>
    </div>
    <main class="main">
        <div class="admin-container">
            <div class="admin-content">
                <script>
                    <?php if (!empty($success)) echo "showToast('" . addslashes($success) . "', 'success', 2000);";
                    if (!empty($error)) echo "showToast('" . addslashes($error) . "', 'error', 2000);";
                    ?>


                </script>
                <?php if ($active_tab == 'template'): ?>
                    <?php include 'Template.php'; ?>
                <?php elseif ($active_tab == 'generator'): ?>
                    <?php include 'generator.php'; ?>
                <?php elseif ($active_tab == 'plugin' || $active_tab == 'CloudPlug'): ?>
                    <?php
                    $extType = isset($_GET['ext_type']) ? strtolower(trim((string)$_GET['ext_type'])) : 'all';
                    if (!in_array($extType, array('all', 'plugin', 'tool'), true)) $extType = 'all';
                    $extCharge = isset($_GET['ext_charge']) ? strtolower(trim((string)$_GET['ext_charge'])) : 'all';
                    if (!in_array($extCharge, array('all', 'paid', 'free'), true)) $extCharge = 'all';
                    ?>
                    <link rel="stylesheet" href="/assets/css/Plugin.css">
                    <div class="section-header" style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
                        <h2 style="margin:0;">
                            <a href="?tab=plugin" class="plugin-tab-link <?php echo $active_tab === 'plugin' ? 'plugin-tab-link-active' : 'plugin-tab-link-inactive'; ?>">我的扩展</a>
                            <a href="?tab=CloudPlug" class="plugin-tab-link plugin-tab-link-cloud <?php echo $active_tab === 'CloudPlug' ? 'plugin-tab-link-active' : 'plugin-tab-link-inactive'; ?>">云端扩展</a>
                        </h2>
                        <div class="qk-ext-filter-bar" style="display:flex;align-items:center;gap:10px;">
                            <?php if ($active_tab === 'plugin'): ?>
                                <button type="button" id="resetPluginOrderBtn" class="btn btn-secondary" style="height:34px;line-height:34px;padding:0 14px;">重置排序</button>
                            <?php endif; ?>
                            <span style="font-size:13px;color:#64748b;">类型</span>
                            <select id="qkExtTypeFilter" class="plugin-type-select" aria-label="类型筛选">
                                <option value="all" <?php echo $extType === 'all' ? 'selected' : ''; ?>>全部</option>
                                <option value="plugin" <?php echo $extType === 'plugin' ? 'selected' : ''; ?>>插件</option>
                                <option value="tool" <?php echo $extType === 'tool' ? 'selected' : ''; ?>>工具</option>
                            </select>
                            <span style="font-size:13px;color:#64748b;">是否收费</span>
                            <select id="qkExtChargeFilter" class="plugin-type-select" aria-label="收费筛选">
                                <option value="all" <?php echo $extCharge === 'all' ? 'selected' : ''; ?>>全部</option>
                                <option value="paid" <?php echo $extCharge === 'paid' ? 'selected' : ''; ?>>收费</option>
                                <option value="free" <?php echo $extCharge === 'free' ? 'selected' : ''; ?>>免费</option>
                            </select>
                        </div>
                    </div>
                    <?php if ($active_tab == 'plugin'): ?>
                        <?php include 'Plugin.php'; ?>
                    <?php else: ?>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                setTimeout(function() {
                                    if (typeof HeaderPagination !== 'undefined') {
                                        HeaderPagination.state.page = <?php echo $current_page; ?>;
                                        HeaderPagination.state.pageSize = 12;
                                        HeaderPagination.state.total = 0;
                                        HeaderPagination.state.totalPages = 1;
                                        HeaderPagination.cache.page = null;
                                        HeaderPagination.cache.pageSize = null;
                                        HeaderPagination.cache.totalPages = null;
                                        HeaderPagination.init();
                                        HeaderPagination.updateUI();
                                    }
                                }, 100);
                            });
                        </script>
                        <div class="admin-card" id="cloud">
                            <?php
                            if (!defined('CLOUDPLUG_EMBEDDED')) define('CLOUDPLUG_EMBEDDED', true);
                            require __DIR__ . '/CloudPlug.php';
                            ?>
                        </div>
                    <?php endif; ?>
                <?php elseif ($active_tab == 'tagSearch'): ?>
                    <?php include 'tagSearch.php'; ?>
                <?php elseif ($active_tab == 'publish'): ?>
                    <?php include 'adpublish.php'; ?>
                <?php elseif ($active_tab == 'order'): ?>
                    <?php include 'order.php'; ?>
                <?php elseif ($active_tab == 'adgoods'): ?>
                    <?php include 'adgoods.php'; ?>
                <?php elseif ($active_tab == 'metrics'): ?>
                    <?php require_once 'metrics.php'; ?>
                <?php elseif ($active_tab == 'counter'): ?>
                    <?php require_once 'counter.php'; ?>
                <?php endif; ?>
                <?php if ($active_tab == 'articles' || $active_tab == 'articlesyg'): ?>
                    <script>
                        // 初始化文章管理页面
                        document.addEventListener('DOMContentLoaded', function() {
                            // 延迟执行，确保seapage.php的insertUI先完成
                            setTimeout(function() {
                                if (typeof HeaderPagination !== 'undefined') {
                                    // 设置初始状态
                                    HeaderPagination.state.page = <?php echo $current_page; ?>;
                                    HeaderPagination.state.pageSize = <?php echo $posts_per_page; ?>;
                                    HeaderPagination.state.totalPages = <?php echo $total_pages ?? 1; ?>;

                                    // 设置缓存，标记第一页已加载，防止 init() 触发重复请求
                                    HeaderPagination.cache.page = <?php echo $current_page; ?>;
                                    HeaderPagination.cache.pageSize = <?php echo $posts_per_page; ?>;
                                    HeaderPagination.cache.totalPages = <?php echo $total_pages ?? 1; ?>;

                                    // 初始化分页组件
                                    HeaderPagination.init();
                                    HeaderPagination.updateUI();
                                }
                            }, 100);
                        });
                    </script>
                    <?php require_once 'article.php'; ?>
                <?php endif; ?>
                <?php if ($active_tab == 'users'): ?>
                    <script>
                        // 初始化用户管理页面
                        document.addEventListener('DOMContentLoaded', function() {
                            if (typeof HeaderPagination !== 'undefined') {
                                // 设置初始状态，与PHP预渲染保持一致
                                HeaderPagination.state.page = <?php echo $current_page; ?>;
                                HeaderPagination.state.pageSize = <?php echo $posts_per_page; ?>;
                                HeaderPagination.state.total = <?php echo $total_users ?? 0; ?>;
                                HeaderPagination.state.totalPages = <?php echo $total_pages ?? 1; ?>;

                                // 设置缓存，标记第一页已加载，防止 init() 触发重复请求
                                HeaderPagination.cache.page = <?php echo $current_page; ?>;
                                HeaderPagination.cache.pageSize = <?php echo $posts_per_page; ?>;
                                HeaderPagination.cache.totalPages = <?php echo $total_pages ?? 1; ?>;

                                // 初始化分页组件
                                HeaderPagination.init();
                                HeaderPagination.updateUI();
                            }
                        });
                    </script>
                    <?php require_once 'users.php'; ?>
                <?php endif; ?>
                <?php if ($active_tab == 'adcategory'): ?>
                    <?php include 'adcategory.php'; ?>
                <?php endif; ?>
                <?php if ($active_tab == 'comments'): ?>
                    <?php require_once 'adcomment.php'; ?>
                <?php endif; ?>
                <?php if ($active_tab == 'reports'): ?>
                    <script>
                        // 初始化举报管理页面
                        document.addEventListener('DOMContentLoaded', function() {
                            if (typeof HeaderPagination !== 'undefined') {
                                // 设置初始状态，与PHP预渲染保持一致
                                HeaderPagination.state.page = <?php echo $current_page; ?>;
                                HeaderPagination.state.pageSize = <?php echo $posts_per_page; ?>;
                                HeaderPagination.state.total = <?php echo $total_reports ?? 0; ?>;
                                HeaderPagination.state.totalPages = <?php echo $total_pages ?? 1; ?>;

                                // 设置缓存，标记第一页已加载，防止 init() 触发重复请求
                                HeaderPagination.cache.page = <?php echo $current_page; ?>;
                                HeaderPagination.cache.pageSize = <?php echo $posts_per_page; ?>;
                                HeaderPagination.cache.totalPages = <?php echo $total_pages ?? 1; ?>;

                                // 初始化分页组件
                                HeaderPagination.init();
                                HeaderPagination.updateUI();
                            }
                        });
                    </script>
                    <?php require_once 'reports.php'; ?>
                <?php endif; ?>
                <?php if ($active_tab == 'settings' || $active_tab == 'navigation'): ?>
                    <?php include 'settings.php'; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>
    <footer class="footer">
        <p><?php echo isset($settings['site_copyright']) ? $settings['site_copyright'] : ''; ?></p>
    </footer>
    <script>
        // 确认框函数 - 直接使用原生confirm
        window.callParentConfirm = function(message) {
            return new Promise(function(resolve) {
                var result = confirm(message);
                resolve(result);
            });
        };

        function deleteCategoryConfirm(categoryId) {
            callParentConfirm('确定要删除这个分类吗？删除后相关文章将被移动到未分类，此操作不可撤销！').then(function(result) {
                if (result) {
                    const baseUrl = '/admin/admin.php?tab=adcategory&delete_category=' + categoryId;
                    const searchParams = new URLSearchParams(window.location.search);
                    const searchTerm = searchParams.get('search');
                    const url = searchTerm ? baseUrl + '&search=' + encodeURIComponent(searchTerm) : baseUrl;
                    window.location.href = url;
                }
            });
        }

        // 替换分类缩略图
        function replaceCategoryThumbnail(categoryId, imgElement) {
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = 'image/png,image/jpeg,image/gif';
            fileInput.style.display = 'none';
            document.body.appendChild(fileInput);

            fileInput.click();

            fileInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (!file) return;

                // 验证文件类型
                const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif'];
                const allowedExtensions = ['.png', '.jpg', '.jpeg', '.gif'];
                const fileExtension = '.' + file.name.split('.').pop().toLowerCase();

                if (!allowedTypes.includes(file.type) || !allowedExtensions.includes(fileExtension)) {
                    showToast('只能上传 PNG、JPG、GIF 格式的图片文件！', 'error');
                    fileInput.remove();
                    return;
                }

                const formData = new FormData();
                formData.append('file', file);
                formData.append('action', 'upload_image');
                formData.append('type', 'category');
                formData.append('image_type', 'thumbnail');

                fetch('/admin/admin.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const newImageUrl = data.data.url;
                            // 动态更新缩略图
                            if (imgElement.tagName === 'IMG') {
                                imgElement.src = newImageUrl + '?t=' + new Date().getTime();
                            } else {
                                // 替换文字为图片
                                const img = document.createElement('img');
                                img.src = newImageUrl;
                                img.alt = '分类缩略图';
                                img.style.width = '60px';
                                img.style.height = '45px';
                                img.style.objectFit = 'cover';
                                img.style.borderRadius = '4px';
                                img.style.cursor = 'pointer';
                                img.onclick = function() {
                                    replaceCategoryThumbnail(categoryId, this);
                                };
                                imgElement.parentNode.replaceChild(img, imgElement);
                            }
                            // 更新数据库
                            fetch('/admin/admin.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded'
                                },
                                body: `update_category_thumbnail=1&category_id=${categoryId}&thumbnail=${encodeURIComponent(newImageUrl)}`
                            });
                        }
                    });
            });
        }
    </script>
    <script>
        function submitCategoryDisplayForm(checkbox) {
            const form = checkbox.closest('form');
            form.addEventListener('submit', function(e) {
                e.preventDefault();
            }, {
                once: true
            });
            const formData = new FormData(form);
            formData.delete('display');
            formData.append('display', checkbox.checked ? '1' : '0');
            const url = '/admin/admin.php';
            fetch(url, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('服务器响应错误');
                    }
                    return response.text();
                })
                .then(data => {
                    if (data.trim() === 'success') {
                        const label = checkbox.closest('label');
                        label.style.transition = 'background-color 0.3s';
                        label.style.backgroundColor = 'rgba(16, 185, 129, 0.1)';
                        setTimeout(() => {
                            label.style.backgroundColor = '';
                        }, 300);
                        // 不需要刷新整个列表，只更新当前行的状态
                    } else {
                        throw new Error('更新失败，服务器返回异常');
                    }
                })
                .catch(error => {
                    console.error('更新失败:', error);
                    checkbox.checked = !checkbox.checked;
                    const label = checkbox.closest('label');
                    label.style.transition = 'background-color 0.3s';
                    label.style.backgroundColor = 'rgba(239, 68, 68, 0.1)';
                    setTimeout(() => {
                        label.style.backgroundColor = '';
                    }, 300);
                });
        }
    </script>
    <script>
        // 处理URL参数，隐藏action和id参数
        document.addEventListener('DOMContentLoaded', function() {
            // 从URL中获取参数
            const urlParams = new URLSearchParams(window.location.search);
            const tab = urlParams.get('tab');
            const action = urlParams.get('action');
            const id = urlParams.get('id');


        });
    </script>
    <script src="../assets/js/toast.js"></script>
    <script src="../assets/js/admin.js?v=<?php echo (int)@filemtime(__DIR__ . '/../assets/js/admin.js'); ?>"></script>
</body>

</html>
