<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function Mirai_api_referral_stats($db, $user) {
    if (!$user->hasLogin()) {
        return ['code' => 401, 'msg' => '请先登录', 'need_login' => true];
    }
    $uid = (int)$user->uid;

    $allRebate = Mirai_referralGetUserRebateData($uid, 'all');
    $effectiveRebate = Mirai_referralGetUserRebateData($uid, 'effective');
    $withdrawnRebate = Mirai_referralGetUserRebateData($uid, 'withdrawn');

    $db2 = \Typecho\Db::get();
    $refTable = Mirai_pointsTable('mirai_referrals');
    $refCount = $db2->fetchRow($db2->select(['COUNT(*)' => 'cnt'])->from($refTable)->where('referrer_uid = ?', $uid));

    return ['code' => 0, 'data' => [
        'total_rebate' => $allRebate['total'],
        'total_count' => $allRebate['count'],
        'effective_rebate' => $effectiveRebate['total'],
        'effective_count' => $effectiveRebate['count'],
        'withdrawn_rebate' => $withdrawnRebate['total'],
        'withdrawn_count' => $withdrawnRebate['count'],
        'referral_count' => (int)($refCount['cnt'] ?? 0),
    ]];
}
