<?php

namespace XZD\AI\V5\Theme\Integrations;

/**
 * Zibll 用户中心集成 — 添加 AI助手 标签页、侧边栏入口、使用统计
 */
class ZibllUserCenterIntegration
{
    private static string $tabKey = 'aidashboard';

    public static function register(): void
    {
        // 添加用户中心标签
        add_filter('user_ctnter_main_tabs_array', [self::class, 'addTab'], 10, 1);

        // 标签内容（动态钩子: main_user_tab_content_{key}）
        add_action('main_user_tab_content_' . self::$tabKey, [self::class, 'renderTabContent']);

        // 侧边栏按钮
        add_filter('zib_user_center_page_sidebar_button_1_args', [self::class, 'addSidebarButton']);
    }

    /**
     * 添加 AI助手 标签页
     */
    public static function addTab(array $tabs): array
    {
        $tabs[self::$tabKey] = [
            'title'    => 'AI助手',
            'icon'     => 'fa-magic',
            'order'    => 99,
            'nav_attr' => '',
        ];
        return $tabs;
    }

    /**
     * 添加侧边栏入口按钮
     */
    public static function addSidebarButton(array $args): array
    {
        // 追加侧边栏按钮
        add_filter('zib_user_center_page_sidebar_button_2_args', function ($buttons) {
            $buttons[] = [
                'html' => '',
                'icon' => zib_get_svg('gift-color'),
                'name' => 'AI助手',
                'tab'  => self::$tabKey,
            ];
            return $buttons;
        });
        return $args;
    }

    /**
     * 渲染 AI助手 标签页内容
     */
    public static function renderTabContent(): void
    {
        $userId = get_current_user_id();
        if (!$userId) {
            echo '<div class="zib-widget"><div class="box-body text-center muted-2-color">请先登录</div></div>';
            return;
        }

        // 获取AI统计数据
        $freeQuota = (int) get_user_meta($userId, '_xzd_ai_free_quota', true);
        $todayCalls = self::getTodayCalls($userId);
        $monthCalls = self::getMonthCalls($userId);
        $lastSessions = self::getRecentSessions($userId, 5);
        $aiPosts = self::getAIGeneratedPosts($userId, 5);

        ?>
        <!-- AI使用统计卡片 -->
        <div class="zib-widget">
            <div class="title-h-left"><h4>AI使用统计</h4></div>
            <div class="box-body">
                <div class="flex ac jsb" style="gap:12px;flex-wrap:wrap">
                    <div class="text-center" style="flex:1;min-width:80px">
                        <div class="font-bold" style="font-size:24px;color:var(--theme-color)"><?php echo $freeQuota; ?></div>
                        <div class="muted-2-color em09">剩余免费次数</div>
                    </div>
                    <div class="text-center" style="flex:1;min-width:80px">
                        <div class="font-bold" style="font-size:24px"><?php echo $todayCalls; ?></div>
                        <div class="muted-2-color em09">今日使用</div>
                    </div>
                    <div class="text-center" style="flex:1;min-width:80px">
                        <div class="font-bold" style="font-size:24px"><?php echo $monthCalls; ?></div>
                        <div class="muted-2-color em09">本月使用</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- AI生成的文章 -->
        <?php if (!empty($aiPosts)): ?>
        <div class="zib-widget mt10">
            <div class="title-h-left"><h4>AI生成的文章</h4></div>
            <div class="box-body">
                <?php foreach ($aiPosts as $post): ?>
                <div class="flex ac jsb" style="padding:8px 0;border-bottom:1px solid var(--main-border-color)">
                    <a href="<?php echo esc_url(get_permalink($post->ID)); ?>" style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo esc_html($post->post_title); ?></a>
                    <span class="muted-2-color em09" style="flex-shrink:0;margin-left:8px"><?php echo get_the_time('m-d', $post); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- 最近对话 -->
        <?php if (!empty($lastSessions)): ?>
        <div class="zib-widget mt10">
            <div class="title-h-left"><h4>最近对话</h4></div>
            <div class="box-body">
                <?php foreach ($lastSessions as $s): ?>
                <div class="flex ac jsb" style="padding:6px 0;border-bottom:1px solid var(--main-border-color)">
                    <span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?php echo esc_html($s['title']); ?></span>
                    <span class="muted-2-color em09" style="flex-shrink:0;margin-left:8px"><?php echo esc_html($s['time']); ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- 快捷入口 -->
        <div class="zib-widget mt10">
            <div class="box-body">
                <a href="javascript:;" class="but c-blue" onclick="document.querySelector('.xzd-chat-trigger')?.click()">
                    <i class="fa fa-comments"></i> 打开AI助手
                </a>
            </div>
        </div>
        <?php
    }

    private static function getTodayCalls(int $userId): int
    {
        global $wpdb;
        $table = $wpdb->prefix . 'xzd_ai_operation_log';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) return 0;

        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE user_id = %d AND DATE(created_at) = %s",
            $userId, wp_date('Y-m-d')
        ));
    }

    private static function getMonthCalls(int $userId): int
    {
        global $wpdb;
        $table = $wpdb->prefix . 'xzd_ai_operation_log';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) return 0;

        return (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$table} WHERE user_id = %d AND DATE_FORMAT(created_at, %s) = %s",
            $userId, '%Y-%m', wp_date('Y-m')
        ));
    }

    private static function getRecentSessions(int $userId, int $limit = 5): array
    {
        global $wpdb;
        $table = $wpdb->prefix . 'xzd_ai_chat_sessions';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) return [];

        return $wpdb->get_results($wpdb->prepare(
            "SELECT session_key, title, created_at FROM {$table} WHERE user_id = %d ORDER BY updated_at DESC LIMIT %d",
            $userId, $limit
        ), ARRAY_A) ?: [];
    }

    private static function getAIGeneratedPosts(int $userId, int $limit = 5): array
    {
        // 查询由 AI 生成的用户文章
        return get_posts([
            'post_type'      => 'post',
            'author'         => $userId,
            'posts_per_page' => $limit,
            'meta_key'       => '_xzd_ai_generated',
            'meta_value'     => '1',
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);
    }
}
