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


// 定义全局分页数据数组
global $qkcms_pagination_data;
if (!isset($qkcms_pagination_data)) {
    $qkcms_pagination_data = array();
}

/**
 * 获取分页数据
 * @param int $type 分页类型：1=文章列表，2=评论列表
 * @param array $existing_data 已有的分页数据（可选）
 * @param int $page_key 分页绑定的标签ID，用于获取对应的数据
 * @return array 完整的分页数据
 */
function get_pagination_data($type, $existing_data = array(), $page_key = 0)
{
    global $qkcms_pagination_data;

    // 如果已有数据且类型匹配，直接返回
    if (!empty($existing_data) && isset($existing_data['type']) && $existing_data['type'] == $type) {
        return $existing_data;
    }

    // 构建缓存键，使用类型和page_key的组合
    $cache_key = $type . '_' . $page_key;

    // 如果全局数据中已有对应缓存键的数据，直接返回
    if (isset($qkcms_pagination_data[$cache_key])) {
        return $qkcms_pagination_data[$cache_key];
    }

    // 从请求中获取当前页码
    // 支持两种格式：1. ?page=1  2. _page1.html
    $current_page = 1;
    // 只有绑定了分页的标签（page_key > 0）才从URL中获取页码
    if ($page_key > 0) {
        if (isset($_GET['page']) && is_numeric($_GET['page'])) {
            $current_page = max(1, intval($_GET['page']));
        } else {
            // 从URL路径中提取页码
            $current_url = $_SERVER['REQUEST_URI'];
            if (preg_match('/_page(\d+)\.html$/i', $current_url, $matches)) {
                $current_page = max(1, intval($matches[1]));
            }
        }
    }

    // 默认每页条数，将从文章/评论列表设置中继承
    // 这里先使用默认值，实际使用时会从全局变量中获取
    $page_size = 10;

    // 获取总数量
    $total = 0;

    // 优先使用全局变量（由tplrdr.php提供）
    // 评论分页(type=2)优先使用评论专用变量，避免与文章分页冲突
    global $qkcms_total_records, $qkcms_total_comments, $qkcms_total_goods;
    global $qkcms_current_row, $qkcms_current_comments_row, $qkcms_current_goods_row;

    // 标记是否成功获取全局变量
    $global_data_available = false;

    // 根据类型选择使用的全局变量
    if ($type == 2) {
        // 评论分页，优先使用评论专用变量
        if (isset($qkcms_total_comments)) {
            if (is_array($qkcms_total_comments) && $page_key > 0 && isset($qkcms_total_comments[$page_key])) {
                // 如果是关联数组且有page_key，使用对应的数据
                $total = $qkcms_total_comments[$page_key];
                $global_data_available = true;
            } else if (!is_array($qkcms_total_comments) && $qkcms_total_comments > 0) {
                // 兼容旧版，直接使用标量值
                $total = $qkcms_total_comments;
                $global_data_available = true;
            }
        }

        if (isset($qkcms_current_comments_row) && $qkcms_current_comments_row > 0) {
            $page_size = $qkcms_current_comments_row;
        } else if (isset($qkcms_current_row)) {
            if (is_array($qkcms_current_row) && $page_key > 0 && isset($qkcms_current_row[$page_key])) {
                // 如果是关联数组且有page_key，使用对应的数据
                $page_size = $qkcms_current_row[$page_key];
            } else if (!is_array($qkcms_current_row) && $qkcms_current_row > 0) {
                // 兼容旧版，直接使用标量值
                $page_size = $qkcms_current_row;
            } else {
                // 设置默认每页大小
                $page_size = 10;
            }
        } else {
            // 设置默认每页大小
            $page_size = 10;
        }
    } else if ($type == 4) {
        // 商品分页(type=4)，使用商品专用变量
        if (isset($qkcms_total_goods)) {
            if (is_array($qkcms_total_goods) && $page_key > 0 && isset($qkcms_total_goods[$page_key])) {
                // 如果是关联数组且有page_key，使用对应的数据
                $total = $qkcms_total_goods[$page_key];
                $global_data_available = true;
            } else if (!is_array($qkcms_total_goods) && $qkcms_total_goods > 0) {
                // 兼容旧版，直接使用标量值
                $total = $qkcms_total_goods;
                $global_data_available = true;
            }
        }

        if (isset($qkcms_current_goods_row)) {
            if (is_array($qkcms_current_goods_row) && $page_key > 0 && isset($qkcms_current_goods_row[$page_key])) {
                // 如果是关联数组且有page_key，使用对应的数据
                $page_size = $qkcms_current_goods_row[$page_key];
            } else if (!is_array($qkcms_current_goods_row) && $qkcms_current_goods_row > 0) {
                // 兼容旧版，直接使用标量值
                $page_size = $qkcms_current_goods_row;
            } else {
                // 设置默认每页大小
                $page_size = 10;
            }
        } else {
            // 设置默认每页大小
            $page_size = 10;
        }
    } else {
        // 文章分页(type=1)、分类列表分页(type=3)，使用通用变量
        // type=3是新增的分类列表分页类型，与type=1共享同一套变量
        if (isset($qkcms_total_records)) {
            if (is_array($qkcms_total_records) && $page_key > 0 && isset($qkcms_total_records[$page_key])) {
                // 如果是关联数组且有page_key，使用对应的数据
                $total = $qkcms_total_records[$page_key];
                $global_data_available = true;
            } else if (!is_array($qkcms_total_records) && $qkcms_total_records > 0) {
                // 兼容旧版，直接使用标量值
                $total = $qkcms_total_records;
                $global_data_available = true;
            }
        }

        if (isset($qkcms_current_row)) {
            if (is_array($qkcms_current_row) && $page_key > 0 && isset($qkcms_current_row[$page_key])) {
                // 如果是关联数组且有page_key，使用对应的数据
                $page_size = $qkcms_current_row[$page_key];
            } else if (!is_array($qkcms_current_row) && $qkcms_current_row > 0) {
                // 兼容旧版，直接使用标量值
                $page_size = $qkcms_current_row;
            } else {
                // 设置默认每页大小
                $page_size = 10;
            }
        } else {
            // 设置默认每页大小
            $page_size = 10;
        }
    }

    // 如果全局变量未设置，则尝试从数据库获取
    if (!$global_data_available) {
        $db = null;

        try {
            // 检查是否已经有可用的数据库连接（由tplrdr.php提供）
            global $db;
            if (!isset($db) || !is_valid_db_connection($db)) {
                // 如果没有，尝试获取新连接
                $db = get_db_connection();
                if (!is_valid_db_connection($db)) {
                    throw new Exception("数据库连接无效");
                }
            }

            // 检查是否为TAG页面（通过URL或GET参数）
            $is_tag_page = false;
            $tag_value = '';
            if (isset($_GET['tag']) && !empty($_GET['tag'])) {
                $is_tag_page = true;
                $tag_value = $_GET['tag'];
            } elseif (isset($_SERVER['REQUEST_URI'])) {
                $request_uri = $_SERVER['REQUEST_URI'];
                if (strpos($request_uri, 'tag=') !== false || strpos($request_uri, '/tag_') !== false) {
                    $is_tag_page = true;
                    // 尝试从URL中提取tag值
                    if (preg_match('/[?&]tag=([^&]+)/', $request_uri, $matches)) {
                        $tag_value = urldecode($matches[1]);
                    }
                }
            }

            // 如果是TAG页面，使用getArticlesData计算总数（与total_tag标签一致）
            if ($is_tag_page && !empty($tag_value)) {
                $params = array(
                    'tag' => '1,' . $tag_value, // 使用tag=1模式，与total_tag标签一致
                    'row' => 0, // 不限制数量，只获取总数
                    'page' => 1
                );
                $result = getArticlesData($params, $db);
                $total = $result['total'];
            } elseif ($type == 4) {
                // 商品分页(type=4)
                // 动态查找商品表名
                $goods_table = findTable($db, ['goods', 'products', 'qkcms_goods', 'qkcms_products', 'shop_goods', 'store_products']);
                if (!$goods_table) {
                    throw new Exception("未找到商品表");
                }

                // 动态查找字段名
                $field_patterns = array(
                    'status' => array('status', 'goods_status', 'product_status'),
                    'category_id' => array('category_id', 'cat_id', 'cid', 'goods_category_id', 'product_category_id')
                );
                $field_map = getFieldMap($db, $goods_table, $field_patterns);

                // 构建商品列表查询条件
                $where = "WHERE " . $field_map['status'] . " = 1";

                // 分类筛选
                if (isset($_GET['cid']) && intval($_GET['cid']) > 0) {
                    $cat_id = intval($_GET['cid']);
                    $where .= " AND " . $field_map['category_id'] . " = $cat_id";
                } else if (isset($_GET['cat_id']) && intval($_GET['cat_id']) > 0) {
                    $cat_id = intval($_GET['cat_id']);
                    $where .= " AND " . $field_map['category_id'] . " = $cat_id";
                } else if (isset($_GET['category_id']) && intval($_GET['category_id']) > 0) {
                    $cat_id = intval($_GET['category_id']);
                    $where .= " AND " . $field_map['category_id'] . " = $cat_id";
                }

                // 计算总数量
                $count_sql = "SELECT COUNT(*) as total FROM `$goods_table` $where";
                $result = $db->query($count_sql);
                if ($result && $row = $result->fetch_assoc()) {
                    $total = $row['total'];
                    $result->free();
                }
            } elseif ($type == 1 || $type == 3) {
                // 根据type参数明确处理不同类型的分页
                if ($type == 3) {
                    // type=3：分类列表分页
                    // 动态查找分类/分类表名
                    $category_table = findTable($db, ['categories', 'qkcms_category', 'qkcms_category', 'board', 'article_category', 'news_category', 'blog_category', 'post_category', 'site_category', 'content_category', 'product_category', 'cat', 'cats']);
                    if (!$category_table) {
                        throw new Exception("未找到分类/分类表");
                    }

                    // 构建分类列表查询条件
                    $field_patterns = array(
                        'display' => array('display', 'show_home', 'home_display')
                    );
                    $field_map = getFieldMap($db, $category_table, $field_patterns);

                    $where = "";
                    // 检查是否需要显示所有分类
                    $sa = isset($_GET['sa']) ? intval($_GET['sa']) : 2;
                    if (isset($field_map['display']) && $sa == 2) {
                        $where = "WHERE " . $field_map['display'] . " = 1";
                    }

                    // 计算总数量
                    $count_sql = "SELECT COUNT(*) as total FROM `$category_table` $where";
                    $result = $db->query($count_sql);
                    if ($result && $row = $result->fetch_assoc()) {
                        $total = $row['total'];
                        $result->free();
                    }
                } else if ($type == 1 || $type === null) {
                    // type=1：文章列表分页
                    // type=null：默认处理文章列表分页
                    // 动态查找文章表名
                    $article_table = findTable($db, ['articles', 'posts', 'news', 'content', 'article', 'blog']);
                    if (!$article_table) {
                        throw new Exception("未找到文章表");
                    }

                    // 动态查找字段名
                    $field_patterns = array(
                        'status' => array('status', 'post_status', 'article_status'),
                        'category_id' => array('category_id', 'cat_id', 'cid')
                    );
                    $field_map = getFieldMap($db, $article_table, $field_patterns);

                    // 构建文章列表查询条件
                    $where = "WHERE " . $field_map['status'] . " = 1";

                    // 分类筛选
                    if (isset($_GET['cat_id']) && intval($_GET['cat_id']) > 0) {
                        $cat_id = intval($_GET['cat_id']);
                        $where .= " AND " . $field_map['category_id'] . " = $cat_id";
                    }
                    // tag筛选 - 与articles标签的tag=2模式保持一致
                    if (isset($_GET['tag']) && !empty($_GET['tag'])) {
                        $tag = $db->real_escape_string($_GET['tag']);
                        $field_patterns_tags = array(
                            'title' => array('title', 'article_title', 'post_title'),
                            'keywords' => array('keywords', 'tags')
                        );
                        $field_map_tags = getFieldMap($db, $article_table, $field_patterns_tags);
                        $tag_conditions = array();
                        // 匹配标题包含关键词的文章
                        if (isset($field_map_tags['title'])) {
                            $tag_conditions[] = $field_map_tags['title'] . " LIKE '%$tag%'";
                        }
                        // 关键词不为空的文章（后续在PHP中精确匹配）
                        if (isset($field_map_tags['keywords'])) {
                            $tag_conditions[] = "(" . $field_map_tags['keywords'] . " != '' AND " . $field_map_tags['keywords'] . " IS NOT NULL)";
                        }
                        if (!empty($tag_conditions)) {
                            $where .= " AND (" . implode(' OR ', $tag_conditions) . ")";
                        }
                    }

                    // 计算总数量
                    $count_sql = "SELECT COUNT(*) as total FROM `$article_table` $where";
                    $result = $db->query($count_sql);
                    if ($result && $row = $result->fetch_assoc()) {
                        $total = $row['total'];
                        $result->free();
                    }
                } else {
                    // 其他情况，保持原有逻辑（兼容旧版）
                    // 检查是否为分类列表分页
                    $is_category_page = false;
                    $request_uri = $_SERVER['REQUEST_URI'];
                    if (strpos($request_uri, 'category.html') !== false) {
                        $is_category_page = true;
                    }

                    if ($is_category_page) {
                        // 分类列表分页
                        // 动态查找分类表名
                        $category_table = findTable($db, ['categories', 'qkcms_category', 'qkcms_category', 'board', 'article_category', 'news_category', 'blog_category', 'post_category', 'site_category', 'content_category', 'product_category', 'cat', 'cats']);
                        if (!$category_table) {
                            throw new Exception("未找到分类表");
                        }

                        // 构建分类列表查询条件
                        $field_patterns = array(
                            'display' => array('display', 'show_home', 'home_display')
                        );
                        $field_map = getFieldMap($db, $category_table, $field_patterns);

                        $where = "";
                        // 检查是否需要显示所有分类
                        $sa = isset($_GET['sa']) ? intval($_GET['sa']) : 2;
                        if (isset($field_map['display']) && $sa == 2) {
                            $where = "WHERE " . $field_map['display'] . " = 1";
                        }

                        // 计算总数量
                        $count_sql = "SELECT COUNT(*) as total FROM `$category_table` $where";
                        $result = $db->query($count_sql);
                        if ($result && $row = $result->fetch_assoc()) {
                            $total = $row['total'];
                            $result->free();
                        }
                    } else {
                        // 文章列表分页
                        // 动态查找文章表名
                        $article_table = findTable($db, ['articles', 'posts', 'news', 'content', 'article', 'blog']);
                        if (!$article_table) {
                            throw new Exception("未找到文章表");
                        }

                        // 动态查找字段名
                        $field_patterns = array(
                            'status' => array('status', 'post_status', 'article_status'),
                            'category_id' => array('category_id', 'cat_id', 'cid')
                        );
                        $field_map = getFieldMap($db, $article_table, $field_patterns);

                        // 构建文章列表查询条件
                        $where = "WHERE " . $field_map['status'] . " = 1";

                        // 分类筛选
                        if (isset($_GET['cat_id']) && intval($_GET['cat_id']) > 0) {
                            $cat_id = intval($_GET['cat_id']);
                            $where .= " AND " . $field_map['category_id'] . " = $cat_id";
                        }
                        // tag筛选
                        if (isset($_GET['tag']) && !empty($_GET['tag'])) {
                            $tag = $db->real_escape_string($_GET['tag']);
                            $field_patterns_tags = array(
                                'title' => array('title', 'article_title', 'post_title'),
                                'description' => array('description', 'summary'),
                                'keywords' => array('keywords', 'tags')
                            );
                            $field_map_tags = getFieldMap($db, $article_table, $field_patterns_tags);
                            $tag_conditions = array();
                            if (isset($field_map_tags['title'])) {
                                $tag_conditions[] = $field_map_tags['title'] . " LIKE '%$tag%'";
                            }
                            if (isset($field_map_tags['description'])) {
                                $tag_conditions[] = $field_map_tags['description'] . " LIKE '%$tag%'";
                            }
                            if (isset($field_map_tags['keywords'])) {
                                $tag_conditions[] = $field_map_tags['keywords'] . " LIKE '%$tag%'";
                            }
                            if (!empty($tag_conditions)) {
                                $where .= " AND (" . implode(' OR ', $tag_conditions) . ")";
                            }
                        }

                        // 计算总数量
                        $count_sql = "SELECT COUNT(*) as total FROM `$article_table` $where";
                        $result = $db->query($count_sql);
                        if ($result && $row = $result->fetch_assoc()) {
                            $total = $row['total'];
                            $result->free();
                        }
                    }
                }
            } elseif ($type == 2) {
                // 评论分页
                // 动态查找评论表名
                $comment_table = findTable($db, ['comments', 'qkcms_comment', 'qkcms_comment', 'article_comment']);
                if (!$comment_table) {
                    throw new Exception("未找到评论表");
                }

                // 动态查找字段名
                $field_patterns = array(
                    'article_id' => array('article_id', 'post_id', 'content_id'),
                    'parent_id' => array('parent_id'),
                    'status' => array('status', 'check_status', 'approve_status')
                );
                $field_map = getFieldMap($db, $comment_table, $field_patterns);

                // 构建评论查询条件
                $where = "WHERE 1=1";

                // 只查询顶级评论（parent_id=0）
                if (isset($field_map['parent_id'])) {
                    $where .= " AND " . $field_map['parent_id'] . " = 0";
                }

                // 只查询已审核的评论
                if (isset($field_map['status'])) {
                    $where .= " AND " . $field_map['status'] . " = 1";
                }

                // 获取当前文章ID（如果有）
                $article_id = 0;
                $current_url = $_SERVER['REQUEST_URI'];
                $current_file = basename($current_url);

                // 1. 优先从GET参数获取
                if (isset($_GET['id'])) {
                    $article_id = intval($_GET['id']);
                } elseif (isset($_GET['article_id'])) {
                    $article_id = intval($_GET['article_id']);
                }
                // 2. 从URL路径中提取，如 post_id498_comments2.html
                elseif (preg_match('/_id(\d+)/', $current_file, $matches)) {
                    $article_id = intval($matches[1]);
                }
                // 3. 从URL路径中提取，如 article_123_comments2.html
                elseif (preg_match('/article_(\d+)/', $current_file, $matches)) {
                    $article_id = intval($matches[1]);
                }
                // 4. 从URL路径中提取，如 post_123_comments2.html
                elseif (preg_match('/post_(\d+)/', $current_file, $matches)) {
                    $article_id = intval($matches[1]);
                }
                // 5. 从URL路径中提取，如 goods_id298_comments2.html
                elseif (preg_match('/goods_id(\d+)/', $current_file, $matches)) {
                    $article_id = intval($matches[1]);
                }
                // 6. 从URL路径中提取，如 goods_298_comments2.html
                elseif (preg_match('/goods_(\d+)/', $current_file, $matches)) {
                    $article_id = intval($matches[1]);
                }

                // 如果有文章ID，只查询该文章的评论
                if ($article_id > 0 && isset($field_map['article_id'])) {
                    $where .= " AND " . $field_map['article_id'] . " = $article_id";
                }

                // 计算总评论数
                $count_sql = "SELECT COUNT(*) as total FROM `$comment_table` $where";
                $result = $db->query($count_sql);
                if ($result && $row = $result->fetch_assoc()) {
                    $total = $row['total'];
                    $result->free();
                }
            }
        } catch (Exception $e) {
            // 数据库操作失败时，返回默认数据
            $total = 0;
        }

        // 设置默认每页大小
        if (!isset($page_size)) {
            $page_size = 10; // 默认每页10条
        }
    }

    // 计算总页数
    $total_pages = $total > 0 ? ceil($total / $page_size) : 1;
    $current_page = min($current_page, $total_pages);

    // 构建分页数据
    $pagination_data = array(
        'type' => $type,
        'current_page' => $current_page,
        'total_pages' => $total_pages,
        'total_items' => $total,
        'page_size' => $page_size,
        'first_page' => 1,
        'last_page' => $total_pages,
        'prev_page' => max(1, $current_page - 1),
        'next_page' => min($total_pages, $current_page + 1),
        'has_prev' => $current_page > 1,
        'has_next' => $current_page < $total_pages,
        'page_items' => array() // 用于存储页码项
    );

    // 生成页码项（固定显示1-3的页码）
    $fixed_pages = 3; // 固定显示3个页码

    // 固定显示1-3的页码
    $start_page = 1;
    $end_page = min($total_pages, $fixed_pages);

    for ($i = $start_page; $i <= $end_page; $i++) {
        $pagination_data['page_items'][] = array(
            'page' => $i,
            'is_current' => $i == $current_page
        );
    }

    // 保存到全局数组，使用类型和page_key的组合作为缓存键
    $qkcms_pagination_data[$cache_key] = $pagination_data;

    return $pagination_data;
}

/**
 * 解析分页标签
 * @param string $content 包含分页标签的内容
 * @param int $type 分页类型
 * @param int $page_key 分页绑定的标签ID，用于获取对应的数据
 * @return string 解析后的内容
 */
function parse_pagination_tags($content, $type, $page_key = 0)
{
    // 获取分页数据
    $pagination = get_pagination_data($type, array(), $page_key);

    // 获取当前页面URL并处理
    $current_url = $_SERVER['REQUEST_URI'];
    $current_file = basename($current_url);

    // 移除可能存在的_pageX.html后缀
    $base_file = preg_replace('/_page\d+\.html$/', '.html', $current_file);

    // 解析当前URL，保留原有查询参数（除了page参数）
    $url_parts = parse_url($current_url);
    $base_path = $url_parts['path'];
    $query_params = array();
    if (isset($url_parts['query'])) {
        parse_str($url_parts['query'], $query_params);
        // 移除page参数，避免重复
        unset($query_params['page']);
    }

    // 生成页码URL的函数，根据类型使用不同格式
    $get_page_url = function ($page) use ($base_path, $query_params) {
        // 所有分页统一使用 ?page=X 格式，保留原有查询参数
        $params = $query_params;
        if ($page > 1) {
            $params['page'] = $page;
        }
        if (!empty($params)) {
            return $base_path . '?' . http_build_query($params);
        }
        return $base_path;
    };

    // 生成页码数字链接（1 2 3 4 5）
    $page_numbers = '';
    foreach ($pagination['page_items'] as $item) {
        if ($item['is_current']) {
            $page_numbers .= '<span class="current page-number">' . $item['page'] . '</span>';
        } else {
            $page_numbers .= '<a href="' . $get_page_url($item['page']) . '" class="page-number">' . $item['page'] . '</a>';
        }
    }

    // 生成页码信息（第X页/共X页）
    $page_status = '第 ' . $pagination['current_page'] . ' 页 / 共 ' . $pagination['total_pages'] . ' 页';

    // 生成页码跳转下拉框
    $jump_to_page = '<select class="page-jump">';
    for ($i = 1; $i <= $pagination['total_pages']; $i++) {
        $selected = $i == $pagination['current_page'] ? 'selected' : '';
        $jump_to_page .= '<option value="' . $get_page_url($i) . '" ' . $selected . '>' . $i . '</option>';
    }
    $jump_to_page .= '</select>';

    // 生成首页链接
    $first_page_link = '<a href="' . $get_page_url($pagination['first_page']) . '" class="first">首页</a>';

    // 生成上一页链接
    $prev_page_link = $pagination['has_prev'] ? '<a href="' . $get_page_url($pagination['prev_page']) . '" class="prev">上一页</a>' : '<span class="disabled prev">上一页</span>';

    // 生成下一页链接
    $next_page_link = $pagination['has_next'] ? '<a href="' . $get_page_url($pagination['next_page']) . '" class="next">下一页</a>' : '<span class="disabled next">下一页</span>';

    // 生成尾页链接
    $last_page_link = '<a href="' . $get_page_url($pagination['last_page']) . '" class="last">尾页</a>';

    // 替换子标签，同时支持{}和[]包裹的标签
    $tags = array(
        '{first_page}' => $first_page_link,
        '[first_page]' => $first_page_link,
        '{prev_page}' => $prev_page_link,
        '[prev_page]' => $prev_page_link,
        '{page_numbers}' => $page_numbers,
        '[page_numbers]' => $page_numbers,
        '{next_page}' => $next_page_link,
        '[next_page]' => $next_page_link,
        '{last_page}' => $last_page_link,
        '[last_page]' => $last_page_link,
        '{page_status}' => $page_status,
        '[page_status]' => $page_status,
        '{jump_to_page}' => $jump_to_page,
        '[jump_to_page]' => $jump_to_page,
        '{current_page}' => $pagination['current_page'],
        '[current_page]' => $pagination['current_page'],
        '{total_pages}' => $pagination['total_pages'],
        '[total_pages]' => $pagination['total_pages'],
        '{total_items}' => $pagination['total_items'],
        '[total_items]' => $pagination['total_items']
    );

    // 替换所有标签
    $content = strtr($content, $tags);

    return $content;
}

/**
 * 生成分页HTML
 * @param int $type 分页类型
 * @param string $template 自定义模板（可选）
 * @param int $page_key 分页绑定的标签ID，用于获取对应的数据
 * @return string 分页HTML
 */
function generate_pagination($type, $template = '', $page_key = 0)
{
    // 添加分页CSS样式
    $pagination_css = "<style>
    

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto;
            max-width: 1200px;
            padding: 0 20px;
            flex-wrap: wrap;
            gap: 8px;    margin-top: 25px;    padding-bottom: 25px;
}
     
        
        .pagination a{
       
    display: inline-block;
  
    margin: 0;
    border: 1px solid #dee2e6;
    border-radius:5px;
    text-decoration: none;
    color: #495057;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.5;
    transition: all 0.3s ease;
    background-color: #fff;
    width: 60px;
    height: 30px;text-align:center;line-height: 30px;
    box-shadow: 0 0px 0px rgba(0, 0, 0, 0.1);

        }
        
        .pagination a:hover {
            background-color: var(--primary);
            color: white;
            border-color: var(--primary);
          
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        }
        
                                                            
    .pagination span {
    display: inline-block;
    margin: 0;
    border: 1px solid #dee2e6;
    border-radius: 5px;
    text-decoration: none;
    color: #495057;
    font-size: 14px;
    font-weight: 500;

    transition: all 0.3s ease;
    background-color: #fff;
   width: 120px;
    height: 30px;
    text-align:center;line-height: 30px;

        }
        
                                                                                                                    
     
        .pagination .page-number {
            width: 40px;
        }
        
  
        .pagination span.current {
            background-color:var(--primary);
            color: white; 
            box-shadow: 0 0px 0px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
         
           
        }
        
        .pagination span.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
            background-color: #f9fafb;
            color: #adb5bd;    width: 60px;
            box-shadow: 0 0px 0px rgba(0, 0, 0, 0.1);
        }
        
        .pagination .page-status {
          
            font-size: 14px;
            color: #6c757d;
            font-weight: 500;
            background-color: transparent;
            border: none;
        }
        
        .pagination select {
             box-shadow: 0 0px 0px rgba(0, 0, 0, 0.1);
            border: 1px solid #dee2e6;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 500;
            background-color: #fff;
            color: #495057;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 50px; 
            height: 32px;
            text-align: center;
            line-height: 32px;
            
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
            
            background-image: url('data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2212%22 height=%2212%22 viewBox=%220 0 12 12%22%3E%3Cpath fill=%22%23495057%22 d=%22M6 9L1 4h10z%22/%3E%3C/svg%3E');
            background-repeat: no-repeat;
            background-position: right 5px center;
            background-size: 12px;
            padding-right: 20px;
            padding-left: 5px;
        }
        
        .pagination select:hover {
            border-color: #adb5bd;
            box-shadow: 0 0px 0px rgba(0, 0, 0, 0.1);
        }
        
        .pagination select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 0px rgba(99, 102, 241, 0.2);
        }
        
        
        @media (max-width: 768px) {
            .pagination a.first,
            .pagination a.last,
            .pagination span.page-status,
            .pagination .first,
            .pagination .last,
            .pagination .page-status {
                display: none !important;
            }
        }

        
        .loading-indicator {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            color: #6c757d;
            font-size: 14px;
        }

        .loading-indicator::before {
            content: '';
            width: 16px;
            height: 16px;
            margin-right: 8px;
            border: 2px solid #dee2e6;
            border-top: 2px solid var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
  
       
    </style>";

    // 如果没有提供自定义模板，使用默认模板
    if (empty($template)) {
        $template = '<div class="pagination">
            {first_page}
            {prev_page}
            {page_numbers}
            {next_page}
            {last_page}
            <span class="page-status">{page_status}</span>
            <span>跳转至：</span>
            {jump_to_page}
        </div>';
    }

    // 解析模板中的分页标签
    $pagination_html = parse_pagination_tags($template, $type, $page_key);

    // 添加AJAX无刷新翻页JavaScript
    $pagination_js = '<script>
        // 页面加载完成后绑定初始事件
        document.addEventListener("DOMContentLoaded", function() {
            // 绑定页码跳转下拉框的change事件
            const pageJumpSelects = document.querySelectorAll(".pagination select.page-jump");
            pageJumpSelects.forEach(select => {
                select.addEventListener("change", function(e) {
                    loadPageByAjax(this.value);
                });
            });

            // 绑定分页链接点击事件
            const paginationLinks = document.querySelectorAll(".pagination a.page-number, .pagination a.first, .pagination a.prev, .pagination a.next, .pagination a.last");
            paginationLinks.forEach(link => {
                link.addEventListener("click", function(e) {
                    e.preventDefault();
                    loadPageByAjax(this.href);
                });
            });
        });

        // AJAX加载页面内容
        function loadPageByAjax(url) {
            // 显示加载状态
            const commentList = document.querySelector("#tag-article-list, .article-list, .topic-list, .comment-list, #latest, #category-list");
            if (!commentList) {
                // 如果没有找到列表元素，使用普通页面跳转
                window.location.href = url;
                return;
            }
            
            // 创建加载指示器并添加到评论列表
            const loadingIndicator = document.createElement("div");
            loadingIndicator.className = "loading-indicator";
            loadingIndicator.textContent = "加载中...";
            loadingIndicator.style.position = "absolute";
            loadingIndicator.style.top = "50%";
            loadingIndicator.style.left = "50%";
            loadingIndicator.style.transform = "translate(-50%, -50%)";
            loadingIndicator.style.background = "rgba(255, 255, 255, 0.9)";
            loadingIndicator.style.padding = "10px 20px";
            loadingIndicator.style.borderRadius = "4px";
            loadingIndicator.style.boxShadow = "0 2px 10px rgba(0, 0, 0, 0.1)";
            loadingIndicator.style.zIndex = "1000";
            
            // 确保评论列表有相对定位，以便加载指示器可以绝对定位
            if (window.getComputedStyle(commentList).position === "static") {
                commentList.style.position = "relative";
            }
            
            commentList.appendChild(loadingIndicator);
            
            // 应用淡入淡出效果
            commentList.style.transition = "opacity 0.2s ease";
            commentList.style.opacity = "0.6";

            // 发送AJAX请求
            fetch(url, {
                method: "GET",
                headers: {
                    "X-Requested-With": "XMLHttpRequest"
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error("HTTP error! status: " + response.status);
                }
                return response.text();
            })
            .then(html => {
                // 解析返回的HTML，提取列表部分
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, "text/html");
                const newCommentList = doc.querySelector("#tag-article-list, .article-list, .topic-list, .comment-list, #latest, #category-list");
                const newPagination = doc.querySelector(".pagination");

                // 更新评论列表和分页
                if (newCommentList) {
                    // 移除加载指示器
                    const loadingIndicator = commentList.querySelector(".loading-indicator");
                    if (loadingIndicator) {
                        loadingIndicator.remove();
                    }
                    
                    // 保存当前容器的属性
                    const containerAttributes = {};
                    for (let i = 0; i < commentList.attributes.length; i++) {
                        containerAttributes[commentList.attributes[i].name] = commentList.attributes[i].value;
                    }
                    
                    // 优化DOM更新：只替换内容，保持容器结构
                    // 先清空容器
                    while (commentList.firstChild) {
                        commentList.removeChild(commentList.firstChild);
                    }
                    
                    // 逐个添加新元素，减少重排
                    const fragment = document.createDocumentFragment();
                    Array.from(newCommentList.children).forEach(child => {
                        fragment.appendChild(child.cloneNode(true));
                    });
                    
                    // 一次性添加所有元素
                    commentList.appendChild(fragment);
                    
                    // 恢复容器属性
                    for (const [name, value] of Object.entries(containerAttributes)) {
                        commentList.setAttribute(name, value);
                    }
                    
                    // 恢复透明度
                    commentList.style.opacity = "1";
                    
                    // 调整评论列表高度
                    if (typeof adjustCommentListHeight === "function") {
                        adjustCommentListHeight();
                    }
                    
                    // 初始化自定义滚动条（确保在任何情况下都执行）
                    if (typeof reinitCustomScrollbar === "function") {
                        reinitCustomScrollbar();
                    }
                    
                    // 重新初始化滚动控制
                    if (typeof reinitScrollControls === "function") {
                        reinitScrollControls();
                    }
                    
                } else {
                    console.error("未找到新评论列表");
                    // 恢复页面状态
                    commentList.style.opacity = "1";
                    const loadingIndicator = commentList.querySelector(".loading-indicator");
                    if (loadingIndicator) {
                        loadingIndicator.remove();
                    }
                }

                if (newPagination) {
                    const oldPagination = document.querySelector(".pagination");
                    if (oldPagination) {
                        // 直接替换分页内容，而不是整个元素
                        oldPagination.innerHTML = newPagination.innerHTML;
                        
                        // 重新绑定事件
                        bindPaginationEvents();
                        
                    }
                }

                // 更新URL而不刷新页面
                history.pushState({}, "", url);
            })
            .catch(error => {
                console.error("加载页面失败:", error);
                // 恢复页面状态
                if (commentList) {
                    commentList.style.opacity = "1";
                    const loadingIndicator = commentList.querySelector(".loading-indicator");
                    if (loadingIndicator) {
                        loadingIndicator.remove();
                    }
                }
            });
        }

        // 重新绑定分页事件
        function bindPaginationEvents() {
            // 绑定页码跳转下拉框的change事件
            const pageJumpSelects = document.querySelectorAll(".pagination select.page-jump");
            pageJumpSelects.forEach(select => {
                select.addEventListener("change", function(e) {
                    loadPageByAjax(this.value);
                });
            });

            // 绑定分页链接点击事件
            const paginationLinks = document.querySelectorAll(".pagination a.page-number, .pagination a.first, .pagination a.prev, .pagination a.next, .pagination a.last");
            paginationLinks.forEach(link => {
                link.addEventListener("click", function(e) {
                    e.preventDefault();
                    loadPageByAjax(this.href);
                });
            });
        }
    </script>';

    // 组合返回完整的分页HTML
    return $pagination_css . $pagination_html . $pagination_js;
}
