<?php

namespace XZD\AI\V5\Theme\Integrations;

/**
 * Zibll 支付系统集成 — VIP购买赠送额度、签到奖励、积分规则
 */
class ZibllPaymentIntegration
{
    public static function register(): void
    {
        // VIP购买后赠送 AI 额度
        add_action('payment_order_success', [self::class, 'onPaymentSuccess'], 10, 1);

        // 每日签到赠送 AI 次数
        add_action('user_checkined', [self::class, 'onCheckin'], 10, 2);

        // AI使用积分规则
        add_filter('integral_add_options', [self::class, 'addIntegralOptions']);
    }

    /**
     * VIP购买成功后赠送 AI 使用额度
     */
    public static function onPaymentSuccess($order): void
    {
        $order = is_object($order) ? $order : (object) $order;
        $orderId = $order->id ?? ($order->order_num ?? 0);
        $orderType = $order->order_type ?? '';
        $userId = (int) ($order->user_id ?? 0);

        if (!$userId || !$orderId) return;

        // 防止重复处理
        $metaKey = '_xzd_ai_credit_granted_' . md5((string) $orderId);
        if (get_user_meta($userId, $metaKey, true)) return;

        // 根据订单类型赠送额度（Zibll 可能传 int 或 string，统一转 string 匹配）
        $freeQuota = match ((string) $orderType) {
            '5', '6', 'vip' => 100,    // VIP购买: 100次
            '1', '2'      => 20,       // 普通付费: 20次
            default       => 0,
        };

        if ($freeQuota <= 0) return;

        // 写入免费额度
        $current = (int) get_user_meta($userId, '_xzd_ai_free_quota', true);
        update_user_meta($userId, '_xzd_ai_free_quota', $current + $freeQuota);
        update_user_meta($userId, $metaKey, current_time('mysql'));

        // 发送通知
        if (class_exists('ZibMsg') && function_exists('zib_msg_is_allow_receive')) {
            if (zib_msg_is_allow_receive($userId, 'system')) {
                \ZibMsg::add([
                    'send_user'    => 'admin',
                    'receive_user' => $userId,
                    'title'        => 'AI额度到账通知',
                    'content'      => "恭喜！您已获得 <strong>{$freeQuota}</strong> 次免费AI使用额度。打开AI助手即可使用。",
                    'type'         => 'system',
                    'create_time'  => current_time('mysql'),
                ]);
            }
        }

        // 记录日志
        if (function_exists('\XZD\AI\V5\Core\Logger::info')) {
            \XZD\AI\V5\Core\Logger::info('zibll_payment_ai_credit', [
                'user_id' => $userId,
                'order_id' => $orderId,
                'quota' => $freeQuota,
            ]);
        }
    }

    /**
     * 每日签到赠送 AI 使用次数
     */
    public static function onCheckin($userId, $theData): void
    {
        $userId = (int) $userId;
        if (!$userId) return;

        // 基础奖励
        $baseQuota = 2;

        // 连续签到额外奖励
        $continuousDays = 0;
        if (function_exists('zib_get_user_checkin_continuous_day')) {
            $continuousDays = (int) zib_get_user_checkin_continuous_day($userId);
        }

        $bonusQuota = 0;
        if ($continuousDays >= 30) $bonusQuota = 10;
        elseif ($continuousDays >= 14) $bonusQuota = 5;
        elseif ($continuousDays >= 7) $bonusQuota = 3;

        $totalQuota = $baseQuota + $bonusQuota;

        $current = (int) get_user_meta($userId, '_xzd_ai_free_quota', true);
        update_user_meta($userId, '_xzd_ai_free_quota', $current + $totalQuota);

        // 发送通知
        if (class_exists('ZibMsg') && function_exists('zib_msg_is_allow_receive')) {
            if (zib_msg_is_allow_receive($userId, 'system')) {
                $bonusMsg = $bonusQuota > 0 ? "（含连续{$continuousDays}天签到奖励 +{$bonusQuota}次）" : '';
                \ZibMsg::add([
                    'send_user'    => 'admin',
                    'receive_user' => $userId,
                    'title'        => '签到获得AI额度',
                    'content'      => "签到成功！获得 <strong>{$totalQuota}</strong> 次免费AI使用额度{$bonusMsg}。",
                    'type'         => 'system',
                    'create_time'  => current_time('mysql'),
                ]);
            }
        }
    }

    /**
     * AI使用经验值积分规则
     */
    public static function addIntegralOptions($options): array
    {
        if (!is_array($options)) return $options;

        // Zibll 要求格式: [0 => 标题, 1 => 默认积分值, 2 => 描述, 3 => 分组]
        // WP 6.7+: 不使用插件文本域，避免 _load_textdomain_just_in_time 警告
        $options['ai_chat'] = array(
            'AI对话',
            1,
            '每次AI对话奖励经验',
            'AI',
        );
        $options['ai_write'] = array(
            'AI写作',
            3,
            '使用AI生成文章奖励经验',
            'AI',
        );
        $options['ai_seo'] = array(
            'AI SEO优化',
            2,
            '使用AI优化SEO奖励经验',
            'AI',
        );

        return $options;
    }
}
