<?php
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../../../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);

include($phpbb_root_path . 'common.' . $phpEx);

$user->session_begin();
$auth->acl($user->data);
$user->setup();

$topic_id = (int) request_var('t', 0);
if ($topic_id <= 0) exit;

$allowed_forums = null;

$sql = 'SELECT forum_id FROM ' . TOPICS_TABLE . ' WHERE topic_id = ' . $topic_id;
$result = $db->sql_query_limit($sql, 1);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);

if ($row && $allowed_forums !== null && !in_array((int)$row['forum_id'], $allowed_forums)) {
    exit;
}

$sql = "SELECT topic_first_post_id
        FROM " . TOPICS_TABLE . "
        WHERE topic_id = $topic_id
        AND topic_status <> " . ITEM_MOVED;
$result = $db->sql_query_limit($sql, 1);
$topic_row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);

if (!$topic_row) exit;

$first_post_id = (int)$topic_row['topic_first_post_id'];

$sql = 'SELECT attach_id, thumbnail
        FROM ' . ATTACHMENTS_TABLE . '
        WHERE topic_id = ' . $topic_id . '
          AND post_msg_id = ' . $first_post_id . '
          AND is_orphan = 0
          AND ' . $db->sql_in_set('extension', ['jpg','jpeg','png','gif','webp','bmp','avif'], false, true) . '
        ORDER BY filetime ASC
        LIMIT 5';

$result = $db->sql_query($sql);

if ($db->sql_affectedrows($result) === 0) {
    $db->sql_freeresult($result);
    exit;
}

header('Content-Type: text/html; charset=UTF-8');
echo '<div class="topic-preview-images">';

while ($row = $db->sql_fetchrow($result)) {
    // 🔥 关键修复：有缩略图用缩略图，没有就用原图
    if ($row['thumbnail']) {
        $src = './download/file.' . $phpEx . '?id=' . $row['attach_id'] . '&t=1';
    } else {
        $src = './download/file.' . $phpEx . '?id=' . $row['attach_id'];
    }
    $full = './download/file.' . $phpEx . '?id=' . $row['attach_id'];

    echo '<img src="' . htmlspecialchars($src) . '"
               data-full="' . htmlspecialchars($full) . '"
               class="topic-thumb" alt="预览">';
}

echo '</div>';
$db->sql_freeresult($result);
?>