<?php
/**
 * 首页最新回覆列表 + 一楼图片缩图 + 分頁
 * 调用方式：在模板中使用 <!-- INCLUDE ./styles/artery_2026/theme/recent_topics.php -->
 */

if (!defined('IN_PHPBB')) {
    exit;
}

// ====================================================
// 自訂：首頁最新回覆列表 + 一楼图片缩图 + 分頁
// ====================================================

if (!function_exists('display_forums')) {
    include_once($phpbb_root_path . 'includes/functions_display.php');
}

if (!function_exists('topic_has_attachment')) {
    function topic_has_attachment($topic_id) {
        global $db;
        $sql = 'SELECT COUNT(attach_id) AS total FROM ' . ATTACHMENTS_TABLE . ' WHERE topic_id = ' . (int)$topic_id;
        $result = $db->sql_query($sql);
        $total = (int) $db->sql_fetchfield('total');
        $db->sql_freeresult($result);
        return $total > 0;
    }
}

if (!function_exists('topic_has_image')) {
    function topic_has_image($topic_id) {
        global $db;
        $sql = 'SELECT COUNT(attach_id) AS total FROM ' . ATTACHMENTS_TABLE . ' WHERE topic_id = ' . (int)$topic_id . ' AND (mimetype LIKE "image/%" OR extension IN ("jpg", "jpeg", "png", "gif", "webp"))';
        $result = $db->sql_query($sql);
        $total = (int) $db->sql_fetchfield('total');
        $db->sql_freeresult($result);
        return $total > 0;
    }
}

// ====================================================
// 配置参数（可自行修改）
// ====================================================
$max_thumbs = 5;               // 最多显示几张图片（实际只取一楼图片，此参数仍保留）
$recent_per_page = 10;          // 每页显示帖子数量
$recent_start = request_var('start', 0);
$allowed_forum_ids = array();   // 空数组 = 全站调用；指定版块：array(2, 3, 4, 5)

// ====================================================
// 获取用户有权限的版块
// ====================================================
$forum_read_ary = $auth->acl_getf('f_read');
$allowed_forums = array_keys($forum_read_ary);

if (empty($allowed_forums)) {
    $template->assign_vars(array(
        'S_RECENT_TOPICS' => false,
    ));
} else {
    // 决定要显示的版块ID
    $display_forum_ids = $allowed_forums; // 默认：所有有权限的版块
    
    if (!empty($allowed_forum_ids)) {
        // 如果指定了版块，则取交集（用户有权限的 ∩ 指定的版块）
        $display_forum_ids = array_intersect($allowed_forum_ids, $allowed_forums);
    }
    
    // 如果没有可显示的版块
    if (empty($display_forum_ids)) {
        $template->assign_vars(array(
            'S_RECENT_TOPICS' => false,
        ));
    } else {
        // ====================== 统计数量 ======================
        // 置顶帖数量
        $sql_sticky_count = 'SELECT COUNT(topic_id) AS total FROM ' . TOPICS_TABLE . '
                             WHERE topic_status IN (0, 1) AND topic_type = 1 
                             AND ' . $db->sql_in_set('forum_id', $display_forum_ids);
        $result_sticky = $db->sql_query($sql_sticky_count);
        $sticky_count = (int) $db->sql_fetchfield('total');
        $db->sql_freeresult($result_sticky);
        
        // 本栏公告数量
        $sql_announce_count = 'SELECT COUNT(topic_id) AS total FROM ' . TOPICS_TABLE . '
                               WHERE topic_status IN (0, 1) AND topic_type = 2 
                               AND ' . $db->sql_in_set('forum_id', $display_forum_ids);
        $result_announce = $db->sql_query($sql_announce_count);
        $announce_count = (int) $db->sql_fetchfield('total');
        $db->sql_freeresult($result_announce);
        
        // 全局公告数量（全站公告，不限制版块）
        $sql_global_count = 'SELECT COUNT(topic_id) AS total FROM ' . TOPICS_TABLE . '
                             WHERE topic_status IN (0, 1) AND topic_type = 3';
        $result_global = $db->sql_query($sql_global_count);
        $global_count = (int) $db->sql_fetchfield('total');
        $db->sql_freeresult($result_global);
        
        // 普通帖子数量
        $sql_normal_count = 'SELECT COUNT(topic_id) AS total FROM ' . TOPICS_TABLE . '
                             WHERE topic_status IN (0, 1) AND topic_type = 0 
                             AND ' . $db->sql_in_set('forum_id', $display_forum_ids);
        $result_normal = $db->sql_query($sql_normal_count);
        $normal_count = (int) $db->sql_fetchfield('total');
        $db->sql_freeresult($result_normal);
        
        $total_recent = $sticky_count + $announce_count + $global_count + $normal_count;
        
        // ====================== 主查询 ======================
        $sql_array = array(
            'SELECT' => 't.topic_id, t.topic_title, t.topic_last_post_id, t.topic_last_post_time, t.topic_last_poster_id, t.topic_last_poster_name, 
                        (t.topic_posts_approved - 1) AS topic_replies, t.topic_views, t.topic_type, t.topic_time, 
                        t.topic_poster, t.topic_first_poster_name, f.forum_id, f.forum_name, 
                        u.user_id, u.username, u.user_avatar, u.user_avatar_type, u.user_avatar_width, u.user_avatar_height',
            'FROM' => array(TOPICS_TABLE => 't'),
            'LEFT_JOIN' => array(
                array(
                    'FROM' => array(FORUMS_TABLE => 'f'),
                    'ON' => 't.forum_id = f.forum_id'
                ),
                array(
                    'FROM' => array(USERS_TABLE => 'u'),
                    'ON' => 't.topic_poster = u.user_id'
                )
            ),
            'WHERE' => $db->sql_in_set('t.topic_status', array(0, 1)) . ' 
                       AND ' . $db->sql_in_set('t.topic_type', array(0, 1, 2, 3)),
            'ORDER_BY' => 't.topic_type DESC, t.topic_last_post_time DESC'
        );

        // 全局公告不限制论坛，其他类型限制在允许的版块内
        $sql_array['WHERE'] .= ' AND (t.topic_type = 3 OR ' . $db->sql_in_set('t.forum_id', $display_forum_ids) . ')';

        $sql = $db->sql_build_query('SELECT', $sql_array);
        
        // ====================== 分页查询 ======================
        if ($recent_start == 0) {
            $result = $db->sql_query_limit($sql, $recent_per_page, 0);
        } else {
            $adjusted_start = $recent_start - ($sticky_count + $announce_count + $global_count);
            if ($adjusted_start < 0) $adjusted_start = 0;
            
            $sql_array_temp = $sql_array;
            $sql_array_temp['WHERE'] .= ' AND t.topic_type = 0';  // 只查普通帖子做分页
            $sql_temp = $db->sql_build_query('SELECT', $sql_array_temp);
            $result = $db->sql_query_limit($sql_temp, $recent_per_page, $adjusted_start);
        }
        
        $recent_topics = array();
        
        while ($row = $db->sql_fetchrow($result)) {
            $topic_title = !empty($row['topic_title']) ? $row['topic_title'] : '暂无信息';
            $has_attachment = topic_has_attachment($row['topic_id']);
            $has_image = topic_has_image($row['topic_id']);
            
            if (!function_exists('phpbb_get_user_avatar')) {
                include_once($phpbb_root_path . 'includes/functions_display.php');
            }
            
            if (!empty($row['user_avatar'])) {
                $user_avatar = phpbb_get_user_avatar($row);
            } else {
                $user_avatar = '<img src="' . $phpbb_root_path . 'styles/' . $user->style['style_path'] . '/theme/images/no_avatar.gif" class="topic-avatar-img" alt="">';
            }
            
            $author_full = get_username_string('full', $row['topic_poster'], $row['topic_first_poster_name']);
            $author_profile = get_username_string('profile', $row['topic_poster'], $row['topic_first_poster_name']);
            $replies = max(0, (int)$row['topic_replies']);
            
            // 一楼图片缩图提取
            $thumb_images = array();
            
            if ($has_image) {
                $sql_first_post = 'SELECT post_id FROM ' . POSTS_TABLE . ' 
                                   WHERE topic_id = ' . (int)$row['topic_id'] . ' 
                                   AND post_visibility = 1 
                                   ORDER BY post_time ASC 
                                   LIMIT 1';
                $result_first_post = $db->sql_query($sql_first_post);
                $first_post_id = 0;
                if ($row_first = $db->sql_fetchrow($result_first_post)) {
                    $first_post_id = $row_first['post_id'];
                }
                $db->sql_freeresult($result_first_post);
                
                if ($first_post_id > 0) {
                    $sql_attach = 'SELECT attach_id, physical_filename, real_filename, thumbnail, mimetype, filesize 
                                   FROM ' . ATTACHMENTS_TABLE . ' 
                                   WHERE topic_id = ' . (int)$row['topic_id'] . ' 
                                   AND post_msg_id = ' . (int)$first_post_id . '
                                   AND in_message = 0 
                                   AND mimetype LIKE "image/%" 
                                   ORDER BY filetime ASC 
                                   LIMIT ' . (int)$max_thumbs;
                    $result_attach = $db->sql_query($sql_attach);
                    
                    while ($attach = $db->sql_fetchrow($result_attach)) {
                        $orig_url = $phpbb_root_path . 'download/file.php?id=' . $attach['attach_id'];
                        $list_url = ($attach['thumbnail'] == 1) 
                            ? $phpbb_root_path . 'download/file.php?id=' . $attach['attach_id'] . '&t=1' 
                            : $orig_url;
                        
                        $thumb_images[] = array(
                            'THUMB_SRC' => $list_url,
                            'ORIG_SRC'  => $orig_url,
                            'FILENAME'  => $attach['real_filename']
                        );
                    }
                    $db->sql_freeresult($result_attach);
                }
            }
            
            $recent_topics[] = array(
                'TOPIC_TITLE'    => censor_text($topic_title),
                'U_VIEW_TOPIC'   => append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $row['forum_id'] . '&t=' . $row['topic_id']),
                'HAS_ATTACHMENT' => $has_attachment,
                'HAS_IMAGE'      => $has_image,
                'FORUM_NAME'     => !empty($row['forum_name']) ? $row['forum_name'] : '全站公告',
                'U_VIEW_FORUM'   => !empty($row['forum_id']) ? append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $row['forum_id']) : '#',
                'TOPIC_AUTHOR'   => $author_full,
                'U_VIEW_AUTHOR'  => $author_profile,
                'LAST_POST_TIME' => $user->format_date($row['topic_last_post_time']),
                'TOPIC_TIME'     => $user->format_date($row['topic_time']),
                'VIEWS'          => (int)$row['topic_views'],
                'REPLIES'        => $replies,
                'USER_AVATAR'    => $user_avatar,
                'TOPIC_TYPE'     => (int)$row['topic_type'],
                'THUMB_IMAGES'   => $thumb_images,
                'MAX_THUMBS'     => $max_thumbs,
                'IS_GLOBAL'      => ($row['topic_type'] == 3)
            );
        }
        $db->sql_freeresult($result);
        
        // 分配模板变量
        if (!empty($recent_topics)) {
            $template->assign_block_vars_array('recent_topics', $recent_topics);
        }
        
        // 分页处理
        $pagination_url = append_sid("{$phpbb_root_path}index.$phpEx");
        $start = request_var('start', 0);
        
        if (isset($phpbb_container) && $phpbb_container->has('pagination')) {
            $pagination = $phpbb_container->get('pagination');
            $pagination->generate_template_pagination($pagination_url, 'pagination', 'start', $total_recent, $recent_per_page, $start);
            $total_pages = ceil($total_recent / $recent_per_page);
            $current_page = floor($start / $recent_per_page) + 1;
            $last_page_start = ($total_pages - 1) * $recent_per_page;
            $template->assign_vars(array(
                'S_RECENT_TOPICS'        => !empty($recent_topics),
                'TOTAL_RECENT'           => $total_recent,
                'RECENT_PER_PAGE'        => $recent_per_page,
                'U_VIEW_FIRST_PAGE'      => $pagination_url,
                'U_VIEW_LAST_PAGE'       => $pagination_url . '?start=' . $last_page_start,
                'U_VIEW_PREVIOUS_PAGE'   => $start > 0 ? $pagination_url . '?start=' . ($start - $recent_per_page) : '',
                'U_VIEW_NEXT_PAGE'       => ($start + $recent_per_page) < $total_recent ? $pagination_url . '?start=' . ($start + $recent_per_page) : '',
                'TOTAL_PAGES'            => $total_pages,
                'CURRENT_PAGE'           => $current_page,
            ));
        } else {
            generate_pagination($pagination_url, $total_recent, $recent_per_page, $start);
            $template->assign_vars(array(
                'S_RECENT_TOPICS' => !empty($recent_topics),
                'TOTAL_RECENT'    => $total_recent,
                'RECENT_PER_PAGE' => $recent_per_page,
            ));
        }
    }
}
// 首页最新帖子结束
?>