<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function Mirai_api_points_exchange_vip($db, $user) {
    if (!$user->hasLogin()) {
        return ['code' => 401, 'msg' => '请先登录', 'need_login' => true];
    }
    
    if (!function_exists('Mirai_vipEnabled') || !Mirai_vipEnabled()) {
        return ['code' => 1, 'msg' => '会员功能未启用'];
    }
    
    $uid = (int)$user->uid;
    $level = (int)($_POST['level'] ?? 0);
    
    if ($level < 1 || !Mirai_vipIsLevelEnabled($level)) {
        return ['code' => 1, 'msg' => '无效的会员等级'];
    }
    
    if (!function_exists('Mirai_pointsExchangeVip')) {
        return ['code' => 1, 'msg' => '积分兑换功能未加载'];
    }
    
    $result = Mirai_pointsExchangeVip($uid, $level, 30);
    
    if (!$result['success']) {
        return ['code' => 1, 'msg' => $result['msg']];
    }
    
    $newBalance = function_exists('Mirai_pointsGetBalance') ? Mirai_pointsGetBalance($uid) : 0;
    
    return [
        'code' => 0,
        'data' => [
            'points_spent' => $result['points_spent'],
            'level' => $result['level'],
            'balance' => $newBalance
        ],
        'msg' => '兑换成功'
    ];
}

function Mirai_api_points_exchange_vip_products($db, $user) {
    if (!$user->hasLogin()) {
        return ['code' => 401, 'msg' => '请先登录', 'need_login' => true];
    }
    
    if (!function_exists('Mirai_vipEnabled') || !Mirai_vipEnabled()) {
        return ['code' => 1, 'msg' => '会员功能未启用', 'data' => []];
    }
    
    if (!function_exists('Mirai_pointsGetVipProducts')) {
        return ['code' => 1, 'msg' => '积分兑换功能未加载', 'data' => []];
    }
    
    $products = Mirai_pointsGetVipProducts();
    $balance = function_exists('Mirai_pointsGetBalance') ? Mirai_pointsGetBalance((int)$user->uid) : 0;
    
    return [
        'code' => 0,
        'data' => [
            'products' => $products,
            'balance' => $balance,
            'enabled' => !empty($products)
        ]
    ];
}
