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

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

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        return ['code' => -1, 'msg' => '非法请求'];
    }

    $uid = (int)$user->uid;
    $amount = (float)($_POST['amount'] ?? 0);
    $accountType = trim((string)($_POST['account_type'] ?? ''));
    $accountName = trim((string)($_POST['account_name'] ?? ''));
    $accountNo = trim((string)($_POST['account_no'] ?? ''));
    $qrCodeUrl = trim((string)($_POST['qr_code'] ?? ''));

    $validAccountTypes = ['alipay', 'wechat', 'bank', 'alipay_qr', 'wechat_qr'];
    if (!in_array($accountType, $validAccountTypes, true)) {
        return ['code' => 1, 'msg' => '账户类型无效'];
    }

    if ($accountName === '') {
        return ['code' => 1, 'msg' => '请填写收款账户名'];
    }

    $isQrCode = in_array($accountType, ['alipay_qr', 'wechat_qr'], true);
    if (!$isQrCode && $accountNo === '') {
        return ['code' => 1, 'msg' => '请填写收款账号'];
    }

    $result = Mirai_referralApplyWithdraw($uid, $amount, $accountType, $accountName, $accountNo, $qrCodeUrl);
    if (!$result['success']) {
        return ['code' => 1, 'msg' => $result['msg']];
    }

    return ['code' => 0, 'data' => $result];
}
