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

function Mirai_referralIncomeEnabled() {
    $options = Mirai_opt();
    return isset($options->referralIncomeEnable) && $options->referralIncomeEnable === '1';
}

function Mirai_referralGetIncomeRatio($authorId) {
    if (!Mirai_referralIncomeEnabled()) return 0;

    $options = Mirai_opt();

    if (function_exists('Mirai_vipCheckUserValid')) {
        $vipStatus = Mirai_vipCheckUserValid($authorId);
        if ($vipStatus['is_valid'] && $vipStatus['level'] > 0) {
            $field = 'referralIncomeRatioVip' . $vipStatus['level'];
            if (isset($options->$field) && (float)$options->$field > 0) {
                return (float)$options->$field;
            }
        }
    }

    return isset($options->referralIncomeRatio) ? (float)$options->referralIncomeRatio : 60;
}

function Mirai_referralCalcIncome($authorId, $effectiveAmount) {
    $ratio = Mirai_referralGetIncomeRatio($authorId);
    if ($ratio <= 0) return 0;
    return round($effectiveAmount * $ratio / 100, 2);
}

function Mirai_referralGetUserIncomeData($authorId, $status = 'all') {
    $db = \Typecho\Db::get();
    $orderTable = Mirai_pointsTable('mirai_pay_orders');

    $select = $db->select(['COUNT(*)' => 'cnt', 'SUM(income_price)' => 'total'])->from($orderTable)
        ->where('author_id = ? AND income_price > 0', $authorId);

    if ($status === 'effective') {
        $select = $select->where('income_status = ?', 0);
    } elseif ($status === 'withdrawn') {
        $select = $select->where('income_status = ?', 1);
    }

    $row = $db->fetchRow($select);
    return [
        'count' => (int)($row['cnt'] ?? 0),
        'total' => (float)($row['total'] ?? 0),
    ];
}
