<?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();

// 设置输出为 JSON
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');

try {
    $forum_data = get_forum_hierarchy_with_stats();
    
    // 输出 JSON
    echo json_encode($forum_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}

/**
 * 获取带统计的论坛层级树
 * 只包含有查看权限的分类和普通论坛
 * @return array
 */
function get_forum_hierarchy_with_stats() {
    global $db, $auth;

    $forums = [];
    
    // 选取需要的字段（包含现成的统计字段）
    $sql = 'SELECT 
                forum_id, 
                forum_name, 
                parent_id, 
                forum_type, 
                left_id, 
                forum_topics_approved   AS topics_count,
                forum_posts_approved    AS posts_count
            FROM ' . FORUMS_TABLE . '
            ORDER BY left_id ASC';
    
    $result = $db->sql_query($sql);
    
    while ($row = $db->sql_fetchrow($result)) {
        $forum_id = (int)$row['forum_id'];
        
        // 权限过滤：分类总是显示，普通论坛只显示有 f_list 权限的
        if ($row['forum_type'] == FORUM_CAT || $auth->acl_get('f_list', $forum_id)) {
            $forums[$forum_id] = [
                'id'           => $forum_id,
                'name'         => $row['forum_name'],
                'parent_id'    => (int)$row['parent_id'],
                'type'         => (int)$row['forum_type'],
                'left_id'      => (int)$row['left_id'],
                'topics_count' => (int)$row['topics_count'],
                'posts_count'  => (int)$row['posts_count'],
                'children'     => []
            ];
        }
    }
    $db->sql_freeresult($result);

    // 构建树
    $tree = [];
    
    foreach ($forums as $forum_id => &$forum) {
        $parent_id = $forum['parent_id'];
        
        if ($parent_id == 0) {
            $tree[] = &$forum;
        } elseif (isset($forums[$parent_id])) {
            $forums[$parent_id]['children'][] = &$forum;
        } else {
            // 孤立节点当作一级（很少发生）
            $tree[] = &$forum;
        }
    }
    unset($forum); // 解除引用

    return $tree;
}