<?php if (!defined('__TYPECHO_ROOT_DIR__')) exit;
$options = \Typecho\Widget::widget('Widget_Options');
$wallet = Mirai_payGetWallet((int)$this->user->uid);
$balance = isset($wallet['balance']) ? (float)$wallet['balance'] : 0;
$pendingIncome = 0;
if (function_exists('Mirai_payGetAuthorIncome')) {
    $incomeData = Mirai_payGetAuthorIncome((int)$this->user->uid);
    $pendingIncome = isset($incomeData['available']) ? (float)$incomeData['available'] : 0;
}
$logsPage = isset($_GET['logs_page']) ? max(1, (int)$_GET['logs_page']) : 1;
$logsPageSize = 10;
$logsData = Mirai_payUserWalletLogs((int)$this->user->uid, $logsPage, $logsPageSize);
$logs = $logsData['list'];
$logsTotal = $logsData['total'];
$onlineMethods = Mirai_payAvailableOnlineChannels();
$iconBaseUrl = Mirai_getThemeUrl() . '/assets/images/';
$iconMap = ['wechat' => 'wechat-pay.svg', 'alipay' => 'alipay.svg', 'qq' => 'QQ-Pay.svg'];
$methodData = [];
foreach ($onlineMethods as $method) {
    $iconFile = isset($iconMap[$method]) ? $iconMap[$method] : '';
    $methodData[] = [
        'value' => (string)$method,
        'label' => Mirai_payMethodLabel($method),
        'icon' => $iconFile !== '' ? ($iconBaseUrl . $iconFile) : ''
    ];
}
$security = \Widget\Security::alloc();
$token = $security->getToken('api');

$withdrawalsPage = isset($_GET['wpage']) ? max(1, (int)$_GET['wpage']) : 1;
$withdrawalsPageSize = 5;
$withdrawalsData = Mirai_payGetWithdrawals((int)$this->user->uid, $withdrawalsPage, $withdrawalsPageSize);
$withdrawals = $withdrawalsData['list'];
$withdrawalsTotal = $withdrawalsData['total'];
$minWithdraw = (float)Mirai_payGetOption('withdrawMinAmount', '10');
$withdrawFeeRate = (float)Mirai_payGetOption('withdrawFee', '0');
$withdrawFeeHint = $withdrawFeeRate > 0 ? '，手续费' . $withdrawFeeRate . '%' : '';

$uid = (int)$this->user->uid;
$pointsEnabled = false;
$pointsBalance = 0;
$pointsName = '积分';
$pointsVipExchangeEnabled = false;
if (function_exists('Mirai_pointsEnabled') && Mirai_pointsEnabled()) {
    $pointsEnabled = true;
    $pointsBalance = function_exists('Mirai_pointsGetBalance') ? Mirai_pointsGetBalance($uid) : 0;
    $pointsName = function_exists('Mirai_pointsName') ? Mirai_pointsName() : '积分';
    $optionsTmp = Mirai_opt();
    $pointsVipExchangeEnabled = isset($optionsTmp->pointsVipExchangeEnable) && $optionsTmp->pointsVipExchangeEnable === '1' && function_exists('Mirai_vipEnabled') && Mirai_vipEnabled();
}

$pointsPage = isset($_GET['points_page']) ? max(1, (int)$_GET['points_page']) : 1;
$pointsPageSize = 10;
$pointsLogsData = [];
$pointsLogs = [];
$pointsTotal = 0;
if ($pointsEnabled) {
    $pointsLogsData = function_exists('Mirai_pointsGetLogs') ? Mirai_pointsGetLogs($uid, $pointsPage, $pointsPageSize) : ['list' => [], 'total' => 0];
    $pointsLogs = $pointsLogsData['list'];
    $pointsTotal = $pointsLogsData['total'];
}

$activeTab = isset($_GET['subtab']) ? $_GET['subtab'] : 'balance';
?>
<div class="uc-page">
    <div class="uc-page-header">
        <h2 class="uc-page-title">我的钱包</h2>
    </div>

    <div class="wealth-row-inline">
        <div class="wealth-item-inline wealth-item-balance">
            <span class="wealth-label-inline">余额</span>
            <span class="wealth-value-inline">￥<?php echo number_format($balance, 2); ?></span>
            <span class="wealth-actions-inline">
                <button type="button" class="uc-btn uc-btn-outline uc-btn-sm" onclick="openModal('recharge-modal')">充值</button>
                <button type="button" class="uc-btn uc-btn-outline uc-btn-sm" onclick="openModal('withdraw-modal')">提现</button>
            </span>
            <span class="wealth-hint-inline">待转入 ￥<?php echo number_format($pendingIncome, 2); ?></span>
        </div>

        <?php if ($pointsEnabled): ?>
        <div class="wealth-divider"></div>

        <div class="wealth-item-inline wealth-item-points">
            <span class="wealth-label-inline"><?php echo htmlspecialchars($pointsName); ?></span>
            <span class="wealth-value-inline points-value"><?php echo number_format($pointsBalance, 0); ?></span>
            <span class="wealth-actions-inline">
                <?php if ($pointsVipExchangeEnabled): ?>
                <button type="button" class="uc-btn uc-btn-outline uc-btn-sm uc-btn-vip-exchange" onclick="openModal('exchange-vip-modal')">兑换会员</button>
                <?php endif; ?>
            </span>
            <span class="wealth-hint-inline"><a href="<?php echo \Typecho\Common::url('/user/wallet?subtab=points', $options->index); ?>"><?php echo htmlspecialchars($pointsName); ?>明细</a></span>
        </div>
        <?php endif; ?>
    </div>

    <div class="uc-tabs">
        <button type="button" class="uc-tab-btn <?php echo $activeTab === 'balance' ? 'active' : ''; ?>" onclick="switchWealthTab('balance')">余额记录</button>
        <button type="button" class="uc-tab-btn <?php echo $activeTab === 'withdraw' ? 'active' : ''; ?>" onclick="switchWealthTab('withdraw')">提现记录</button>
        <?php if ($pointsEnabled): ?>
        <button type="button" class="uc-tab-btn <?php echo $activeTab === 'points' ? 'active' : ''; ?>" onclick="switchWealthTab('points')"><?php echo htmlspecialchars($pointsName); ?>记录</button>
        <?php endif; ?>
    </div>

    <div id="tab-balance" class="uc-tab-content" style="<?php echo $activeTab === 'balance' ? '' : 'display:none;' ?>">
        <div class="uc-section-block">
            <h3 class="uc-section-title">余额明细</h3>
            <div class="uc-list">
                <?php if (empty($logs)): ?>
                    <div class="uc-empty"><img src="<?php $this->options->themeUrl('assets/images/no.svg'); ?>" alt="暂无余额记录">暂无余额记录</div>
                <?php else: ?>
                    <?php foreach ($logs as $log): ?>
                        <?php $isIncome = (float)$log['amount'] >= 0; ?>
                        <div class="uc-list-item">
                            <div class="uc-item-body">
                                <div class="uc-item-title"><?php echo htmlspecialchars($log['remark'], ENT_QUOTES, 'UTF-8'); ?></div>
                                <div class="uc-item-meta">
                                    <span><i class="ri-time-line"></i> <?php echo (new \Typecho\Date((int)$log['created']))->format('Y-m-d H:i'); ?></span>
                                    <span class="uc-tag uc-tag-<?php echo $isIncome ? 'success' : 'danger' ?>"><?php echo $isIncome ? '收入' : '支出'; ?></span>
                                    <span><?php echo ($isIncome ? '+' : '') . number_format((float)$log['amount'], 2); ?></span>
                                    <span>余 <?php echo number_format((float)$log['balance_after'], 2); ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <?php if ($logsTotal > $logsPageSize): ?>
                        <?php
                        $lTotalPages = ceil($logsTotal / $logsPageSize);
                        echo Mirai_customPagination($logsPage, $lTotalPages, function($p) use ($options) {
                            return \Typecho\Common::url('/user/wallet?subtab=balance&logs_page=' . $p, $options->index);
                        });
                        ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div id="tab-withdraw" class="uc-tab-content" style="<?php echo $activeTab === 'withdraw' ? '' : 'display:none;' ?>">
        <div class="uc-section-block">
            <h3 class="uc-section-title">提现记录</h3>
            <div class="uc-list">
                <?php if (empty($withdrawals)): ?>
                    <div class="uc-empty"><img src="<?php $this->options->themeUrl('assets/images/no.svg'); ?>" alt="暂无提现记录">暂无提现记录</div>
                <?php else: ?>
                    <?php foreach ($withdrawals as $withdrawal): ?>
                        <?php
                        $statusLabel = Mirai_payWithdrawalStatusLabel((int)$withdrawal['status']);
                        $statusClassMap = [0 => 'warning', 1 => 'success', 2 => 'warning', 3 => 'muted'];
                        $statusClass = isset($statusClassMap[(int)$withdrawal['status']]) ? $statusClassMap[(int)$withdrawal['status']] : 'warning';
                        $accountTypeLabel = [
                            'alipay' => '支付宝-账号', 'alipay_qr' => '支付宝-二维码',
                            'wechat' => '微信-账号', 'wechat_qr' => '微信-二维码', 'bank' => '银行卡'
                        ];
                        $accountTypeText = isset($accountTypeLabel[$withdrawal['account_type']]) ? $accountTypeLabel[$withdrawal['account_type']] : $withdrawal['account_type'];
                        $withdrawTypeLabel = ($withdrawal['withdraw_type'] === 'rebate') ? '佣金提现' : '余额提现';
                        $actualAmount = '';
                        $remark = isset($withdrawal['remark']) ? $withdrawal['remark'] : '';
                        if (preg_match('/实际到账([\d.]+)元/', $remark, $m)) {
                            $actualAmount = (float)$m[1];
                        }
                        ?>
                        <div class="uc-list-item">
                            <div class="uc-item-body">
                                <div class="uc-item-title">
                                    <?php echo htmlspecialchars($withdrawTypeLabel); ?> ￥<?php echo number_format((float)$withdrawal['amount'], 2); ?>
                                    <?php if ($actualAmount > 0 && $actualAmount != (float)$withdrawal['amount']): ?>
                                        <span class="uc-tag uc-tag-info">到账￥<?php echo number_format($actualAmount, 2); ?></span>
                                    <?php endif; ?>
                                    <span class="uc-tag uc-tag-<?php echo $statusClass; ?>"><?php echo htmlspecialchars($statusLabel); ?></span>
                                </div>
                                <div class="uc-item-meta">
                                    <span><i class="ri-time-line"></i> <?php echo $withdrawal['created'] > 0 ? (new \Typecho\Date((int)$withdrawal['created']))->format('Y-m-d H:i') : '-'; ?></span>
                                    <span><?php echo htmlspecialchars($accountTypeText); ?></span>
                                </div>
                                <?php if ($withdrawal['admin_remark']): ?>
                                    <p class="uc-note">备注：<?php echo htmlspecialchars($withdrawal['admin_remark']); ?></p>
                                <?php endif; ?>
                            </div>
                            <?php if ((int)$withdrawal['status'] === 0): ?>
                                <a href="javascript:;" class="uc-text-danger cancel-withdraw" data-id="<?php echo (int)$withdrawal['id']; ?>">取消</a>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                    <?php if ($withdrawalsTotal > $withdrawalsPageSize): ?>
                        <?php
                        $wTotalPages = ceil($withdrawalsTotal / $withdrawalsPageSize);
                        echo Mirai_customPagination($withdrawalsPage, $wTotalPages, function($p) use ($options) {
                            return \Typecho\Common::url('/user/wallet?subtab=withdraw&wpage=' . $p, $options->index);
                        });
                        ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php if ($pointsEnabled): ?>
    <div id="tab-points" class="uc-tab-content" style="<?php echo $activeTab === 'points' ? '' : 'display:none;' ?>">
        <div class="uc-section-block">
            <h3 class="uc-section-title"><?php echo htmlspecialchars($pointsName); ?>明细记录</h3>
            <div class="uc-list">
                <?php if (empty($pointsLogs)): ?>
                    <div class="uc-empty"><img src="<?php $this->options->themeUrl('assets/images/no.svg'); ?>" alt="暂无记录">暂无记录</div>
                <?php else: ?>
                    <?php foreach ($pointsLogs as $log): ?>
                        <?php
                        $isIncome = (int)$log['amount'] > 0;
                        $reasonText = isset($log['remark']) && $log['remark'] !== '' ? $log['remark'] : (isset($log['action']) ? $log['action'] : '');
                        ?>
                        <div class="uc-list-item">
                            <div class="uc-item-body">
                                <div class="uc-item-title"><?php echo htmlspecialchars($reasonText ?? ''); ?></div>
                                <div class="uc-item-meta">
                                    <?php
                                    $created = !empty($log['created']) ? $log['created'] : 0;
                                    ?>
                                    <span><i class="ri-time-line"></i> <?php echo $created > 0 ? (new \Typecho\Date((int)$created))->format('Y-m-d H:i') : '-'; ?></span>
                                    <span class="uc-tag uc-tag-<?php echo $isIncome ? 'success' : 'danger' ?>"><?php echo $isIncome ? '+' . number_format((int)$log['amount']) : '-' . abs((int)$log['amount']); ?></span>
                                    <span>余 <?php echo number_format((int)$log['balance_after']); ?></span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <?php if ($pointsTotal > $pointsPageSize): ?>
                        <?php
                        $totalPages = ceil($pointsTotal / $pointsPageSize);
                        echo Mirai_customPagination($pointsPage, $totalPages, function($p) use ($options) {
                            return \Typecho\Common::url('/user/wallet?subtab=points&points_page=' . $p, $options->index);
                        });
                        ?>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<div id="recharge-modal" class="mirai-pay-method-modal">
    <div class="mirai-pay-method-modal-mask" onclick="closeModal('recharge-modal')"></div>
    <div class="mirai-pay-method-modal-panel">
        <div class="mirai-pay-method-modal-title">余额充值</div>
        <button type="button" class="mirai-pay-method-modal-close" onclick="closeModal('recharge-modal')">&times;</button>
        <form id="rechargeForm" class="mirai-pay-form mirai-pay-form-recharge" method="post" action="<?php echo htmlspecialchars(Mirai_payBuildApiUrl('pay_create_order'), ENT_QUOTES, 'UTF-8'); ?>" data-pay-methods="<?php echo htmlspecialchars(json_encode($methodData), ENT_QUOTES, 'UTF-8'); ?>" data-order-type-label="充值订单" data-order-title="余额充值">
            <input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="order_type" value="recharge">
            <input type="hidden" name="payment_method" id="rechargePaymentMethod" value="<?php echo htmlspecialchars(isset($onlineMethods[0]) ? (string)$onlineMethods[0] : '', ENT_QUOTES, 'UTF-8'); ?>">
            <div class="uc-form-group">
                <label class="uc-label">充值金额</label>
                <input class="uc-input uc-input-lg" type="number" name="amount" id="rechargeAmount" min="0.01" step="0.01" placeholder="输入充值金额" required>
            </div>

            <?php if (empty($onlineMethods)): ?>
                <div class="uc-empty">当前未启用可用在线收款通道，请联系管理员配置。</div>
            <?php endif; ?>
            
            <button type="submit" class="uc-btn uc-btn-primary uc-btn-block <?php echo empty($onlineMethods) ? 'uc-btn-disabled' : ''; ?>" <?php echo empty($onlineMethods) ? 'disabled' : ''; ?>>立即充值</button>
        </form>
    </div>
</div>

<div id="withdraw-modal" class="mirai-pay-method-modal">
    <div class="mirai-pay-method-modal-mask" onclick="closeModal('withdraw-modal')"></div>
    <div class="mirai-pay-method-modal-panel">
        <div class="mirai-pay-method-modal-title">申请提现</div>
        <button type="button" class="mirai-pay-method-modal-close" onclick="closeModal('withdraw-modal')">&times;</button>
        <?php if ($balance < $minWithdraw): ?>
            <div class="uc-alert uc-alert-warning">余额不足最低提现额度（￥<?php echo number_format($minWithdraw, 2); ?>），暂无法申请提现。</div>
        <?php else: ?>
            <form class="uc-form" id="withdrawForm" method="post">
                <input type="hidden" name="token" value="<?php echo htmlspecialchars($token, ENT_QUOTES, 'UTF-8'); ?>">
                <div class="uc-form-group">
                    <label class="uc-label">提现金额</label>
                    <input type="number" name="amount" id="withdrawAmount" min="<?php echo $minWithdraw; ?>" max="<?php echo $balance; ?>" step="0.01" placeholder="最低￥<?php echo number_format($minWithdraw, 2); ?>" required class="uc-input">
                    <p class="uc-hint">可提现：￥<?php echo number_format($balance, 2); ?><?php echo $withdrawFeeHint; ?></p>
                </div>
                <div class="uc-form-group">
                    <label class="uc-label">收款方式</label>
                    <select name="account_type" id="withdrawAccountType" required class="uc-select">
                        <option value="">请选择</option>
                        <option value="alipay">支付宝-账号</option>
                        <option value="alipay_qr">支付宝-二维码</option>
                        <option value="wechat">微信-账号</option>
                        <option value="wechat_qr">微信-二维码</option>
                        <option value="bank">银行卡</option>
                    </select>
                </div>
                <div class="uc-form-group" id="accountNoRow">
                    <label class="uc-label">收款账号</label>
                    <input type="text" name="account_no" id="withdrawAccountNo" placeholder="请输入收款账号" required class="uc-input">
                </div>
                <div class="uc-form-group" id="qrCodeRow" style="display:none;">
                    <label class="uc-label">收款码</label>
                    <input type="file" name="qr_code" id="qrCodeInput" accept="image/*" required class="uc-file-input">
                    <p class="uc-hint">请上传微信或支付宝收款码图片</p>
                    <div class="uc-qr-preview" id="qrCodePreview"></div>
                </div>
                <div class="uc-form-group">
                    <label class="uc-label">收款账户名</label>
                    <input type="text" name="account_name" id="withdrawAccountName" placeholder="请输入收款账户真实姓名" required class="uc-input">
                </div>
                <button type="submit" class="uc-btn uc-btn-primary uc-btn-block">提交申请</button>
            </form>
        <?php endif; ?>
    </div>
</div>


<?php if ($pointsVipExchangeEnabled): ?>
<div id="exchange-vip-modal" class="mirai-pay-method-modal">
    <div class="mirai-pay-method-modal-mask" onclick="closeModal('exchange-vip-modal')"></div>
    <div class="mirai-pay-method-modal-panel">
        <div class="mirai-pay-method-modal-title"><?php echo htmlspecialchars($pointsName); ?>兑换会员</div>
        <button type="button" class="mirai-pay-method-modal-close" onclick="closeModal('exchange-vip-modal')">&times;</button>
        <div id="exchange-vip-loading" style="text-align:center;padding:30px;">
            <i class="ri-loader-4-line spin-icon"></i> 加载中...
        </div>
        <div id="exchange-vip-content" style="display:none;">
            <div class="exchange-vip-balance">
                当前<?php echo htmlspecialchars($pointsName); ?>：<strong id="exchange-vip-balance-value"><?php echo number_format($pointsBalance, 0); ?></strong>
            </div>
            <div id="exchange-vip-products" class="exchange-vip-products"></div>
            <div id="exchange-vip-result" class="exchange-vip-result" style="display:none;"></div>
        </div>
        <div id="exchange-vip-empty" style="display:none;text-align:center;padding:30px;">
            <i class="ri-error-warning-line"></i> 暂无可兑换的会员套餐
        </div>
    </div>
</div>
<?php endif; ?>