<?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);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);

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

/* ==================== 配置区（集中管理） ==================== */

$slider_limit = 10;   // 幻灯片图片数，建议10张以内，太多了手机上放不开
$thumbs_limit = 9;    // 热门图片数量，默认九张，可以改

/**
 * 幻灯片专属配置（软开关）
 * $slider_mode:
 *   'latest'  => 最新发布（默认，按图片上传时间）
 *   'sticky'  => 仅置顶帖（全局置顶 + 普通置顶）
 * $slider_allowed_forums : 只允许指定版面ID数组，留空=全站
 * $slider_exclude_forums : 排除指定版面ID数组（若设置allowed则此项失效）
 * 幻灯片始终只显示一楼（首帖）最大的一张图片
 */
$slider_mode             = 'latest';  // latest / sticky
$slider_allowed_forums   = array();   // 例: array(2, 5, 8)，留空=全站
$slider_exclude_forums   = array();   // 例: array(3, 7)

/**
 * 热门图片专属配置（调用全部楼层中最大尺寸的一张图片）
 * $thumbs_allowed_forums : 只允许指定版面ID数组，留空=全站
 * $thumbs_exclude_forums : 排除指定版面ID数组（若设置allowed则此项失效）
 * $thumbs_sticky_mode:
 *   'include' : 包含置顶帖（默认）
 *   'only'    : 仅显示置顶帖
 *   'exclude' : 排除置顶帖
 */
$thumbs_allowed_forums   = array();   // 例: array(2, 5, 8)，留空=全站
$thumbs_exclude_forums   = array();   // 例: array(3, 7)
$thumbs_sticky_mode      = 'include'; // include / only / exclude

/* ==================== 参数接收 ==================== */

$is_ajax   = $request->variable('ajax', 0); 
$section   = $request->variable('section', ''); 

if (!$is_ajax || !in_array($section, ['slider', 'thumbs'])) {
    exit; 
}
$limit = ($section === 'slider') ? $slider_limit : $thumbs_limit;
$extensions = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp');

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

if (empty($allowed_forums)) {
    echo '<div style="text-align:center;padding:40px;color:#999;">暂无权限查看图片</div>';
    exit;
}

// ====================================================
// 构建基础 WHERE 条件
// ====================================================
$where = array(
    'a.is_orphan = 0',
    'a.in_message = 0',
    $db->sql_in_set('a.extension', $extensions),
    't.topic_visibility = 1',           // 只显示已审核通过的帖子
    't.topic_status IN (0, 1)',         // 0=正常, 1=已删除但可恢复，排除已永久删除
    'p.post_visibility = 1',             // 只显示已审核通过的帖子
);

// 添加版块权限过滤（用户有权限的版块）
$where[] = $db->sql_in_set('p.forum_id', $allowed_forums);

if ($section === 'slider') {
    // 幻灯片：只取一楼（首帖）的图片
    $where[] = 'p.post_id = t.topic_first_post_id';
    
    if (!empty($slider_allowed_forums)) {
        // 额外限制指定版块（取交集）
        $allowed_slider_forums = array_intersect($slider_allowed_forums, $allowed_forums);
        if (!empty($allowed_slider_forums)) {
            $where[] = $db->sql_in_set('p.forum_id', $allowed_slider_forums);
        } else {
            echo '<div style="text-align:center;padding:40px;color:#999;">暂无权限查看图片</div>';
            exit;
        }
    } elseif (!empty($slider_exclude_forums)) {
        $where[] = $db->sql_in_set('p.forum_id', $slider_exclude_forums, true);
    }
    
    if ($slider_mode === 'sticky') {
        $where[] = 't.topic_type IN (' . POST_STICKY . ', ' . POST_GLOBAL . ')';
    }
} else {
    // 缩略图列表：只取一楼（首帖）的图片
    $where[] = 'p.post_id = t.topic_first_post_id';
    
    if (!empty($thumbs_allowed_forums)) {
        // 额外限制指定版块（取交集）
        $allowed_thumbs_forums = array_intersect($thumbs_allowed_forums, $allowed_forums);
        if (!empty($allowed_thumbs_forums)) {
            $where[] = $db->sql_in_set('p.forum_id', $allowed_thumbs_forums);
        } else {
            echo '<div style="text-align:center;padding:40px;color:#999;">暂无权限查看图片</div>';
            exit;
        }
    } elseif (!empty($thumbs_exclude_forums)) {
        $where[] = $db->sql_in_set('p.forum_id', $thumbs_exclude_forums, true);
    }
    
    if ($thumbs_sticky_mode === 'only') {
        $where[] = 't.topic_type IN (' . POST_STICKY . ', ' . POST_GLOBAL . ')';
    } elseif ($thumbs_sticky_mode === 'exclude') {
        $where[] = 't.topic_type NOT IN (' . POST_STICKY . ', ' . POST_GLOBAL . ')';
    }
}

// ====================================================
// 修改子查询：按文件大小降序排序，取每个帖子中最大的一张图片
// ====================================================
$subquery = '(SELECT a2.attach_id
              FROM ' . ATTACHMENTS_TABLE . ' a2
              WHERE a2.post_msg_id = a.post_msg_id
                AND a2.is_orphan = 0
                AND a2.in_message = 0
                AND ' . $db->sql_in_set('a2.extension', $extensions) . '
              ORDER BY a2.filesize DESC, a2.filetime DESC
              LIMIT 1)';

// ====================================================
// 主查询：获取每个帖子中最大尺寸的一张图片（一楼）
// ====================================================
$sql = 'SELECT a.attach_id, a.real_filename, a.physical_filename, a.thumbnail, a.filesize,
               a.post_msg_id, p.forum_id, t.topic_id AS attach_topic_id, t.topic_title
        FROM ' . ATTACHMENTS_TABLE . ' a
        LEFT JOIN ' . POSTS_TABLE . ' p ON a.post_msg_id = p.post_id
        LEFT JOIN ' . TOPICS_TABLE . ' t ON a.topic_id = t.topic_id
        WHERE ' . implode(' AND ', $where) . '
          AND a.attach_id = ' . $subquery . '
        ORDER BY a.filetime DESC';

$result = $db->sql_query_limit($sql, max($slider_limit, $thumbs_limit));

$images = array();
$board_url = generate_board_url();

while ($row = $db->sql_fetchrow($result)) {
    $attach_id = (int)$row['attach_id'];
    $thumbnail = (int)$row['thumbnail'];
    $physical_filename = $row['physical_filename'];
    $filesize = (int)$row['filesize'];
    
    // 构建原图地址和缩略图地址
    $original_url = $board_url . "/download/file.$phpEx?id=" . $attach_id;
    $thumbnail_url = $board_url . "/download/file.$phpEx?id=" . $attach_id . '&t=1';
    
    // 判断是否有缩略图：thumbnail = 1 表示该附件已生成缩略图
    $has_thumbnail = ($thumbnail == 1);
    
    // 备用判断：如果 thumbnail 字段不是 1，但文件名以 thumb_ 开头，也认为有缩略图
    if (!$has_thumbnail && strpos($physical_filename, 'thumb_') === 0) {
        $has_thumbnail = true;
    }
    
    // 优先调用缩略图（如果有），否则调用原图
    if ($has_thumbnail) {
        $image_url = $thumbnail_url;
    } else {
        $image_url = $original_url;
    }
    
    // 构建帖子链接
    $view_topic = '';
    if ($row['post_msg_id'] && $row['forum_id'] && $row['attach_topic_id']) {
        $view_topic = append_sid($board_url . "/viewtopic.$phpEx", array(
            'f' => (int)$row['forum_id'],
            't' => (int)$row['attach_topic_id'],
            'p' => (int)$row['post_msg_id']
        )) . '#p' . (int)$row['post_msg_id'];
    }
    
    $images[] = array(
        'image_url'     => $image_url,
        'thumbnail_url' => $thumbnail_url, 
        'original_url'  => $original_url,
        'view_topic'    => $view_topic,
        'filename'      => htmlspecialchars($row['real_filename']),
        'topic_title'   => htmlspecialchars($row['topic_title'] ?? '未知主题'),
        'has_thumbnail' => $has_thumbnail,
        'filesize'      => $filesize
    );
}
$db->sql_freeresult($result);

header('Content-Type: text/html; charset=UTF-8');

if (empty($images)) {
    echo '<div style="text-align:center;padding:40px;color:#999;">暂无图片附件</div>';
    exit;
}

$images = array_slice($images, 0, $limit);

// ====================================================
// 输出 HTML
// ====================================================
if ($section === 'slider') {
    foreach ($images as $img) {
        echo '<div class="item">';
        if ($img['view_topic']) {
            echo '<a href="' . $img['view_topic'] . '" target="_blank">';
        }
        echo '<img src="' . $img['image_url'] . '" 
                   alt="' . $img['filename'] . '"
                   loading="lazy"
                   onerror="this.onerror=null; this.src=\'' . $img['original_url'] . '\';">';
        if ($img['view_topic']) {
            echo '</a>';
        }
        echo '</div>';
    }
} else {
    foreach ($images as $img) {
        echo '<a href="' . $img['view_topic'] . '" class="thumb-item" target="_blank" title="' . $img['topic_title'] . '">';
        echo '<img src="' . $img['image_url'] . '" 
                   alt="' . $img['filename'] . '"
                   loading="lazy"
                   onerror="this.onerror=null; this.src=\'' . $img['original_url'] . '\';">';
        echo '</a>';
    }
}
exit;
?>