<?php

namespace XZD\AI\V5\Theme\Integrations;

/**
 * Zibll BBS 论坛集成 — AI分析帖子质量、评论区AI按钮、BBS首页推荐
 */
class ZibllBBSIntegration
{
    public static function register(): void
    {
        // BBS 发帖后 AI 分析
        add_action('bbs_add_posts', [self::class, 'onNewTopic'], 10, 1);
        add_action('bbs_edit_posts', [self::class, 'onNewTopic'], 10, 1);

        // 评论区添加 AI 按钮
        add_filter('comments_action_lists', [self::class, 'addCommentActions'], 10, 2);

        // 回答被采纳后给AI奖励
        add_action('answer_adopted', [self::class, 'onAnswerAdopted'], 10, 2);

        // BBS 单页固定按钮
        add_filter('bbs_single_fixed_btns', [self::class, 'addBBSSingleButtons']);

        // BBS 首页推荐tab
        add_filter('bbs_home_tab_options', [self::class, 'addHomeTab']);
        add_action('bbs_home_tab_content_airec', [self::class, 'renderHomeTab']);
    }

    /**
     * BBS 新帖发布后 AI 分析
     */
    public static function onNewTopic($postObj): void
    {
        $postId = is_object($postObj) ? ($postObj->ID ?? 0) : (int) $postObj;
        if (!$postId) return;

        // 异步调用 AI 进行质量评分
        if (function_exists('wp_schedule_single_event')) {
            wp_schedule_single_event(time() + 5, 'xzd_ai_analyze_bbs_post', [$postId]);
        }
    }

    /**
     * 评论区添加 AI 操作按钮
     */
    public static function addCommentActions($lists, $comment)
    {
        // AI 评分按钮
        $aiBtn = '<li><a href="javascript:;" class="xzd-ai-score-comment muted-2-color" data-comment-id="' . esc_attr($comment->comment_ID) . '"><i class="fa fa-robot"></i> AI评分</a></li>';

        // 兼容字符串和数组两种格式
        if (is_array($lists)) {
            $lists[] = $aiBtn;
        } else {
            $lists .= $aiBtn;
        }

        return $lists;
    }

    /**
     * 回答被采纳后给AI奖励
     */
    public static function onAnswerAdopted($comment, $desc): void
    {
        $userId = (int) ($comment->user_id ?? 0);
        if (!$userId) return;

        // 奖励 AI 额度
        $current = (int) get_user_meta($userId, '_xzd_ai_free_quota', true);
        update_user_meta($userId, '_xzd_ai_free_quota', $current + 5);
    }

    /**
     * BBS 单页固定按钮 - 添加 AI 分析
     */
    public static function addBBSSingleButtons($btns)
    {
        $postId = get_the_ID();

        if (is_array($btns)) {
            $btns[] = [
                'text'  => 'AI分析',
                'icon'  => 'fa-robot',
                'class' => 'xzd-ai-analyze-btn',
                'attrs' => 'data-post-id="' . esc_attr($postId) . '"',
            ];
            return $btns;
        }

        // 字符串格式（Zibll默认）：直接追加HTML按钮
        $btnHtml = '<a href="javascript:;" class="xzd-ai-analyze-btn" data-post-id="' . esc_attr($postId) . '"><i class="fa fa-robot"></i> AI分析</a>';
        return $btns . $btnHtml;
    }

    /**
     * BBS 首页添加 AI推荐 tab
     */
    public static function addHomeTab($options): array
    {
        if (!is_array($options)) {
            $options = [];
        }
        $options['airec'] = 'AI推荐';
        return $options;
    }

    /**
     * 渲染 AI推荐 tab 内容
     */
    public static function renderHomeTab(): void
    {
        // AI 推荐：基于热门和质量评分的帖子
        $posts = get_posts([
            'post_type'      => 'forum_post',
            'posts_per_page' => 10,
            'meta_key'       => '_xzd_ai_quality_score',
            'orderby'        => 'meta_value_num',
            'order'          => 'DESC',
            'post_status'    => 'publish',
        ]);

        if (empty($posts)) {
            echo '<div class="ajaxpager text-center muted-2-color" style="padding:40px">暂无AI推荐内容，发表更多帖子后AI将自动推荐</div>';
            return;
        }

        foreach ($posts as $post) {
            $score = get_post_meta($post->ID, '_xzd_ai_quality_score', true);
            ?>
            <div class="flex ac jsb" style="padding:10px;border-bottom:1px solid var(--main-border-color)">
                <div style="flex:1;min-width:0">
                    <a href="<?php echo esc_url(get_permalink($post)); ?>" style="font-weight:500"><?php echo esc_html($post->post_title); ?></a>
                    <div class="muted-2-color em09 mt6"><?php echo wp_trim_words($post->post_content, 20); ?></div>
                </div>
                <span class="ml10" style="flex-shrink:0;color:var(--theme-color);font-weight:600">⭐<?php echo (int) $score; ?></span>
            </div>
            <?php
        }
    }
}
