<?php
//钱包模块

function charge_modal(){
    return '<div id="charge-modal" class="uk-flex-top" uk-modal="esc: false;bg-close: false;">
            <div class="charge-modal uk-modal-dialog uk-modal-body uk-margin-auto-vertical uk-animation-scale-up uk-animation-fast">
                <button class="uk-modal-close-default" type="button" uk-close></button>
                <div class="charge-inner-html"></div>
            </div>
        </div>';
}

function charge_cash_callback(){
    $uid = get_current_user_id();
    $charge_cash_set = get_op('charge_cash_set');
    if(empty($charge_cash_set)){
        $charge_cash_set = array();
    }

    $pay_icon = PPO_Down::pay_icon('cash');
    $charge_cash_notice = get_op('charge_cash_notice');
    if(empty($charge_cash_notice)){
        $charge_cash_notice = '';
    }

    $max = get_op('charge_cash_max');
    $min = get_op('charge_cash_min');
    $limit = get_op('charge_cash_limit');

    $tips = '最低充值'.$min.'元，最高充值'.$max.'元，每日最多充值'.$limit.'次';
    $charge_cash_set_s = get_op('charge_cash_set_s',false);
    $charge_cash_set_html = '';
    if($charge_cash_set_s){
        foreach($charge_cash_set as $item){
            //判断$item['charge_amount']大于$max的时候则不显示$charge_cash_set_html
            if($item['charge_amount'] > $max){
                continue;
            }
            $tag = $item['tag'];
            $tag_text = '';
            if(!empty($tag)){
                $tag_text = '<div class="charge-cash-set-tag">'.$tag.'</div>';
            }
            
            $pay_cash = $item['charge_amount'];
            $discount = cash_calculate_discount($pay_cash);
            $value = $pay_cash * $discount;
            $formatted = (strpos((string)$value, '.') !== false) ? number_format($value, 2) : number_format($value, 0);
            $discount_value = $discount * 10;
            if(!empty($item['charge_amount'])){

                $charge_cash_set_html .= '<div class="charge-cash-set-item" data-amount="'.$pay_cash.'">
                                            '.$tag_text.'
                                        <div class="charge-cash-set-amount"><span>'.$pay_icon['icon'].'</span>'.$pay_cash.'</div>
                                        <div class="charge-cash-set-discount">'.$discount_value.'折</div>
                                    </div>';
            }
            
        }
    }

    $html = '<div class="charge-cash-box">
                    <div class="title">'.$pay_icon['name'].'充值</div>
                    <div class="charge-value">

                        <div class="charge-input-form">
                        <div class="charge-icon">'.$pay_icon['icon'].'</div>
                            <input type="number" id="charge-cash-amount" name="charge-cash-amount" min="'.$min.'" max="'.$max.'" step="1" placeholder="请输入充值金额" uk-tooltip="title: '.$tips.';pos: top-right">
                        </div>

                        <div class="charge-cash-set">
                            '.$charge_cash_set_html.'
                        </div>
                        <div class="charge-notice">'.$charge_cash_notice.'</div>
                        <div class="charge-pay-box">'.PPO_Pay::dd_pay_btn('cash',$uid,'yecz').'</div>
                    </div>
                </div>';

    wp_send_json(array('success' => 'success', 'data' => $html));

}
add_action('wp_ajax_charge_cash_callback', 'charge_cash_callback');

//折扣计算
function cash_calculate_discount($cash){
    $discound_rules = get_op('cash_discount_range');
    if(empty($discound_rules)){
        $discound_rules = array();
    }
    $discount = 1;
    foreach($discound_rules as $rule){
        if($cash >= $rule['charge_min'] && $cash <= $rule['charge_max']){
            $discount = $rule['discount'];
            //判断折扣大于1的时候直接等于1
            if($discount > 1){
                $discount = 1;
            }
            break;
        }
    }
    return $discount;
}

// 计算充值金额
function charge_cash_calculate_discount(){
    $uid = get_current_user_id();
    $index = isset($_POST['index']) ? $_POST['index'] : '';
    $charge_cash_set = get_op('charge_cash_set');
    if(empty($charge_cash_set)){
        $charge_cash_set = array();
    }
    $item = $charge_cash_set[$index];
    if(empty($item)){
        wp_send_json(array('success' => 'error', 'data' => '充值金额不存在'));
    }
    $pay_cash = $item['charge_amount'];
    $discount = cash_calculate_discount($pay_cash);
    $value = $pay_cash * $discount;
    $formatted = (strpos((string)$value, '.') !== false) ? number_format($value, 2) : number_format($value, 0);
    //$discount_value = $discount * 10;
    wp_send_json(array('success' => 'success', 'data' => $formatted));
}
add_action('wp_ajax_charge_cash_calculate_discount', 'charge_cash_calculate_discount');

// 输入框金额格式化
function charge_cash_input_format(){
    $cash = isset($_POST['cash']) ? $_POST['cash'] : '';
    $max = get_op('charge_cash_max');
    if($cash > $max){
        wp_send_json(array('success' => 'error', 'data' => '充值金额不能大于'.$max.''));
    }

    if(empty($cash)){
        wp_send_json(array('success' => 'error', 'data' => '请输入充值金额'));
    }
    $discount = cash_calculate_discount($cash);
    $value = $cash * $discount;
    $formatted = (strpos((string)$value, '.') !== false) ? number_format($value, 2) : number_format($value, 0);
    wp_send_json(array('success' => 'success', 'data' => $formatted));
}
add_action('wp_ajax_charge_cash_input_format', 'charge_cash_input_format');   

// 积分充值
function charge_credit_callback(){
    $uid = get_current_user_id();
    $charge_credit_set = get_op('charge_credit_set');
    $credit_add_s = get_op('credit_add_s',false);
    if(empty($charge_credit_set)){
        $charge_credit_set = array();
    }

    $pay_icon = PPO_Down::pay_icon('credit');
    $charge_credit_notice = get_op('charge_credit_notice');
    if(empty($charge_credit_notice)){
        $charge_credit_notice = '';
    }

    $max = get_op('charge_cash_max');
    $min = get_op('charge_cash_min');
    $limit = get_op('charge_cash_limit');

    $tips = '最低充值'.$min.'元，最高充值'.$max.'元，每日最多充值'.$limit.'次';
    $credit_add_s = get_op('credit_add_s',false);
    $charge_credit_set_html = '';

    if($credit_add_s){
        foreach($charge_credit_set as $item){
            $credit = calculate_charge_credit($item['charge_amount']);
             $tag = $item['tag'];
             $tag_text = '';
            if(!empty($tag)){
                $tag_text = '<div class="charge-cash-set-tag">'.$tag.'</div>';
            }
            if($item['charge_amount'] > $max){
                continue;
            }
            $charge_credit_set_html .= '<div class="charge-credit-set-item" data-amount="'.$item['charge_amount'].'">
                                        '.$tag_text.'
                                        <div class="charge-credit-set-amount"><span>¥</span>'.$item['charge_amount'].'</div>
                                        <div class="charge-credit-set-add">赠'.$credit['credit_add'].'<span>'.$pay_icon['name'].'</span></div>
                                    </div>';
        }
    }

    //如果 credit_add_s 为false ，则不赠送积分
    if(!$credit_add_s){
        $charge_credit_set_html = '';
    }

    $html = '<div class="charge-credit-box">
                    <div class="title">'.$pay_icon['name'].'充值</div>
                    <div class="charge-value">

                        <div class="charge-input-form">
                        <div class="charge-icon">¥</div>
                            <input type="number" id="charge-credit-amount" name="charge-credit-amount" min="1" max="1000" step="1" placeholder="请输入充值金额" uk-tooltip="title: '.$tips.';pos: top-right">
                        </div>

                        <div class="charge-credit-set">
                            '.$charge_credit_set_html.'
                        </div>
                        <div class="charge-notice">'.$charge_credit_notice.'</div>
                        <div class="charge-pay-box">'.PPO_Pay::dd_pay_btn('cash',$uid,'jfcz').'</div>
                    </div>
                </div>';

    wp_send_json(array('success' => 'success', 'data' => $html));

 
}
add_action('wp_ajax_charge_credit_callback', 'charge_credit_callback');

// 积分赠送换算
function calculate_charge_credit($cash) {
    $base_ratio = get_op('credit_rate','10');
    $credit_add_range = get_op('credit_add_range');
    $credit_add_s = get_op('credit_add_s',false);
    if(empty($credit_add_range)){
        $credit_add_range = array();
    }

    // 按min从大到小排序
    usort($credit_add_range, function($a, $b) {
        return floatval($b['min']) - floatval($a['min']);
    });
    //我这里$bonus_percent是25之类的数，没带百分比%，需要除以100才能得到正确的积分赠送
    $bonus_percent = 0;
    foreach($credit_add_range as $rule){
        if($cash >= floatval($rule['min'])){
            $bonus_percent = floatval($rule['bonus_percent'] / 100);
            break;
        }
    }

    //如果 credit_add_s 为false ，则不赠送积分
    if(!$credit_add_s){
        $bonus_percent = 0;
    }

    $total_add = $cash * $base_ratio * $bonus_percent;
    $base_credit = $cash * $base_ratio;
    $total_credit = $base_credit + $total_add;

    return array(
        'base_ratio' => $base_ratio,
        'bonus_percent' => $bonus_percent,
        'charge_cash' => $cash,
        'credit_add' => $total_add,
        'total_credit' => $total_credit,
        'base_credit' => $base_credit,
        );
    
}

function charge_credit_calculate(){
    $pay_icon = PPO_Down::pay_icon('credit');
    $index = isset($_POST['index']) ? $_POST['index'] : '';
    $charge_credit_set = get_op('charge_credit_set');
    if(empty($charge_credit_set)){
        $charge_credit_set = array();
    }

    $item = $charge_credit_set[$index];
    if(empty($item)){
        wp_send_json(array('success' => 'error', 'data' => '充值金额不存在','index'=>$index));
    }
    $pay_cash = $item['charge_amount'];
    $charge_data = calculate_charge_credit($pay_cash);

    wp_send_json(array(
        'success' => 'success', 
        'charge_cash' => intval($charge_data['charge_cash']),
        'credit_add' => $charge_data['credit_add'],
        'total_credit' => $charge_data['total_credit'],
        'base_credit' => $charge_data['base_credit'],
        'credit_name' => $pay_icon['name'],
    ));
  
    
}
add_action('wp_ajax_charge_credit_calculate', 'charge_credit_calculate');

function charge_credit_input_format(){
    $cash = isset($_POST['cash']) ? $_POST['cash'] : '';
    $pay_icon = PPO_Down::pay_icon('credit');
    $max = get_op('charge_cash_max');
    if($cash > $max){
        wp_send_json(array('success' => 'error', 'data' => '充值金额不能大于'.$max.''));
    }

    if(empty($cash)){
        wp_send_json(array('success' => 'error', 'data' => '请输入充值金额'));
    }

    $cash = floatval($cash);
    $charge_data = calculate_charge_credit($cash);
    wp_send_json(array(
        'success' => 'success', 
        'charge_cash' => intval($charge_data['charge_cash']),
        'credit_add' => $charge_data['credit_add'],
        'total_credit' => $charge_data['total_credit'],
        'base_credit' => $charge_data['base_credit'],
        'credit_name' => $pay_icon['name'],
    ));
}
add_action('wp_ajax_charge_credit_input_format', 'charge_credit_input_format');

// 获取支付数据
function get_charge_pay_data($mode,$pay_value){
    $pay_value = pix_normalize_charge_amount($pay_value);
    if($mode == 'jfcz'){
        $total_amount = $pay_value;
        $extra = calculate_charge_credit($pay_value)['total_credit'];
    } else if($mode == 'yecz'){
        $discount = cash_calculate_discount($pay_value);
        $total_value = $pay_value * $discount;
        $total_amount = pix_normalize_charge_amount($total_value);
        $extra = $pay_value;
    }

    $cash_name = PPO_Down::pay_icon('cash')['name'];
    $credit_name = PPO_Down::pay_icon('credit')['name'];

    return array(
        'subject' => $mode == 'jfcz' ? '购买' . $credit_name : $cash_name . '充值',
        'total_amount' => $total_amount,
        'order_extra' => $extra,
    );
    
}

function pix_normalize_charge_amount($amount) {
    return round(floatval($amount), 2);
}

function pix_validate_charge_amount($mode, $pay_value, $user_id = 0) {
    $mode = sanitize_key($mode);
    $pay_value = pix_normalize_charge_amount($pay_value);

    if (!in_array($mode, array('jfcz', 'yecz'), true)) {
        return new WP_Error('invalid_charge_mode', '未知的充值类型');
    }

    if ($pay_value <= 0) {
        return new WP_Error('invalid_charge_amount', '充值金额必须大于 0');
    }

    $min = pix_normalize_charge_amount(get_op('charge_cash_min', 1));
    $max = pix_normalize_charge_amount(get_op('charge_cash_max', 1000));

    if ($min > 0 && $pay_value < $min) {
        return new WP_Error('charge_amount_too_low', '充值金额不能低于' . $min . '元');
    }

    if ($max > 0 && $pay_value > $max) {
        return new WP_Error('charge_amount_too_high', '充值金额不能大于' . $max . '元');
    }

    $limit = intval(get_op('charge_cash_limit', 0));
    $user_id = $user_id ? intval($user_id) : get_current_user_id();
    if ($limit > 0 && $user_id > 0) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'ppo_pay_order';
        $today_start = date('Y-m-d 00:00:00', current_time('timestamp'));
        $today_end = date('Y-m-d 23:59:59', current_time('timestamp'));
        $paid_count = intval($wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE user_id = %d AND order_type = %s AND status = 1 AND pay_time BETWEEN %s AND %s",
            $user_id,
            $mode,
            $today_start,
            $today_end
        )));

        if ($paid_count >= $limit) {
            return new WP_Error('charge_daily_limit', '今日充值次数已达上限');
        }
    }

    return array(
        'amount' => $pay_value,
    );
}

// 更新充值回调
function update_charge_callback($order_data){
    $uid = $order_data['user_id'];
    $price = $order_data['total_price'];
    $type = $order_data['order_type'];
    $ppo_credit = get_user_meta($uid, 'ppo_credit', true);
    $ledger_context = array(
        'change_type' => $type == 'jfcz' ? 'recharge_credit' : 'recharge_cash',
        'order_id' => isset($order_data['order_id']) ? $order_data['order_id'] : '',
        'trade_no' => isset($order_data['pay_trade_no']) ? $order_data['pay_trade_no'] : '',
        'note' => $type == 'jfcz' ? PPO_Down::pay_icon('credit')['name'] . '充值' : PPO_Down::pay_icon('cash')['name'] . '充值',
    );
    if($type == 'jfcz'){
        $total_credit =  calculate_charge_credit($price)['total_credit'];
        Credit::credit_change($uid,$total_credit,$ledger_context);
    } else if($type == 'yecz'){
        $charge_cash = $order_data['order_extra'];
        Credit::cash_change($uid,$charge_cash,$ledger_context);
    }
}

/**
 * 获取用户积分获取记录（任务+充值）
 * @param int $user_id 用户ID
 * @param int $page 页码，默认1
 * @param int $per_page 每页数量，默认20
 * @return array
 */
function ppo_get_credit_records($page = 1, $per_page = 10) {
    global $wpdb;
    
    $user_id = get_current_user_id();
    $page = max(1, intval($page));
    $per_page = max(1, intval($per_page));
    $offset = ($page - 1) * $per_page;
    
    // 任务记录
    $task_table = $wpdb->prefix . 'ppo_task_log';
    $task_sql = "SELECT 
        id,
        user_id,
        task_key,
        xp,
        point,
        reward_time,
        note,
        'task' as source
    FROM $task_table 
    WHERE user_id = %d AND point > 0";
    
    // 充值记录（仅成功的订单）
    $order_table = $wpdb->prefix . 'ppo_pay_order';
    $order_sql = "SELECT 
        ID as id,
        user_id,
        order_id,
        order_type,
        pay_type_info,
        total_price,
        pay_time,
        order_title,
        order_extra,
        'recharge' as source
    FROM $order_table 
    WHERE user_id = %d AND status = 1 AND order_type = 'jfcz'";
    
    // 获取记录
    $task_records = $wpdb->get_results($wpdb->prepare($task_sql, $user_id), ARRAY_A);
    $order_records = $wpdb->get_results($wpdb->prepare($order_sql, $user_id), ARRAY_A);
    
    // 格式化充值记录
    foreach ($order_records as &$record) {
        if (!empty($record['pay_type_info']) && $record['pay_type_info'] === 'card_credit') {
            $record['point'] = intval($record['order_extra']);
        } else {
            $credit_info = calculate_charge_credit(floatval($record['total_price']));
            $record['point'] = $credit_info['total_credit'];
        }
        $record['xp'] = 0;
        $record['task_key'] = 'recharge';
        $record['note'] = !empty($record['order_title']) ? $record['order_title'] : '充值' . $record['total_price'] . '元';
        $record['reward_time'] = $record['pay_time'];
        $record['after_amount'] = pix_wallet_get_ledger_after_amount($record['order_id'], 'credit', $user_id);
    }
    unset($record);
    
    // 合并记录
    $all_records = array_merge($task_records, $order_records);
    
    // 按时间排序（最新优先）
    usort($all_records, function($a, $b) {
        return strtotime($b['reward_time']) - strtotime($a['reward_time']);
    });
    
    // 计算总数
    $total = count($all_records);
    $total_pages = ceil($total / $per_page);
    
    // 分页
    $records = array_slice($all_records, $offset, $per_page);
    
    // 格式化返回
    $formatted = array();
    foreach ($records as $record) {
        $formatted[] = array(
            'id' => $record['id'],
            'source' => $record['source'],
            'type' => isset($record['task_key']) ? $record['task_key'] : 'recharge',
            'point' => intval($record['point']),
            'xp' => intval($record['xp']),
            'time' => $record['reward_time'],
            'note' => $record['note'],
            'after_amount' => isset($record['after_amount'])
                ? $record['after_amount']
                : pix_wallet_find_credit_ledger_after_amount($user_id, $record['point'], $record['reward_time'], $record['task_key'] ?? ''),
        );
    }
    
    return array(
        'records' => $formatted,
        'total' => $total,
        'total_pages' => $total_pages,
        'current_page' => $page,
        'per_page' => $per_page,
    );
}

/**
 * 获取用户积分记录总数
 * @param int $user_id 用户ID
 * @return int
 */
function ppo_get_credit_records_count() {
    global $wpdb;
    
    $user_id = get_current_user_id();
    $task_table = $wpdb->prefix . 'ppo_task_log';
    $order_table = $wpdb->prefix . 'ppo_pay_order';
    
    // 任务记录数
    $task_count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $task_table WHERE user_id = %d AND point > 0",
        $user_id
    ));
    
    // 充值记录数
    $order_count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $order_table WHERE user_id = %d AND status = 1 AND order_type = 'jfcz'",
        $user_id
    ));
    
    return intval($task_count) + intval($order_count);
}

function user_credit_get_info($page = 1, $per_page = 10){
   $data = ppo_get_credit_records($page, $per_page);
   $html = '';
   $pay_icon = PPO_Down::pay_icon('credit');
   $total_count = $data['total'];

    if(empty($data['records'])){
        echo '<div class="xp-detail-empty">暂无积分获取记录</div>';
        exit;
    }

    $nav = ppo_htmx_pager([
        'base_url'    => '/wp-json/ppo/v1/user-credit-records',
        'user_id'     => '',
        'total_pages' => ceil($total_count / $per_page),
        'current'     => $page,
        'target'      => '.wallet_record_list',
        'push_url'    => true,
        'push_url_base' => user_dashboard_url('wallet'),
        'query_args'  => ['tab' => 'credit'],
        'skeleton' => 'normal-list',
        'wpnonce' => true,
    ]);

   foreach($data['records'] as $record){
       $record['time'] = date('Y-m-d H:i:s', strtotime($record['time']));
       $after_html = $record['after_amount'] !== null ? '<div class="wallet-record-total">当前：' . number_format_i18n(intval($record['after_amount'])) . '</div>' : '';
       $html .= '<div class="user_credit_record">';
       $html .= '<div class="left"><div class="object">' . $record['note'] . '</div><div class="time">' . $record['time'] . '</div></div>';
       $html .= '<div class="right wallet-record-change"><div>' . $pay_icon['icon'] . ' +' . $record['point'] . '</div>' . $after_html . '</div>';
       $html .= '</div>';
   }

   
   return $html.'<div class="wallet-pagination">'.$nav.'</div>';
}

function ppo_get_user_credit_records($request) {
    $page = $request->get_param('page') ? intval($request->get_param('page')) : 1;
    $per_page = $request->get_param('per_page') ? intval($request->get_param('per_page')) : 10;
    $html = user_credit_get_info($page, $per_page);
    echo $html;
    exit;
}

// 获取余额记录

/**
 * 获取用户余额记录
 * @param int $page 页码，默认1
 * @param int $per_page 每页数量，默认20
 * @return array
 */
function ppo_get_balance_records($page = 1, $per_page = 10) {
    global $wpdb;

    $user_id = get_current_user_id();
    $page = max(1, intval($page));
    $per_page = max(1, intval($per_page));
    $offset = ($page - 1) * $per_page;

    $order_table = $wpdb->prefix . 'ppo_pay_order';
    $sql = "SELECT
        ID as id,
        user_id,
        order_id,
        order_type,
        pay_type_info,
        total_price,
        pay_time,
        order_title,
        order_extra
    FROM $order_table
    WHERE user_id = %d AND status = 1 AND order_type = 'yecz'
    ORDER BY pay_time DESC";

    $count_sql = "SELECT COUNT(*) FROM $order_table WHERE user_id = %d AND status = 1 AND order_type = 'yecz'";

    $total = intval($wpdb->get_var($wpdb->prepare($count_sql, $user_id)));
    $total_pages = ceil($total / $per_page);

    $records = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT ID as id, user_id, order_id, order_type, pay_type_info, total_price, pay_time, order_title, order_extra
             FROM $order_table
             WHERE user_id = %d AND status = 1 AND order_type = 'yecz'
             ORDER BY pay_time DESC
             LIMIT $per_page OFFSET $offset",
            $user_id
        ),
        ARRAY_A
    );

    $formatted = array();
    foreach ($records as $record) {
        $formatted[] = array(
            'id' => $record['id'],
            'type' => 'yecz',
            'cash' => floatval($record['total_price']),
            'extra' => $record['order_extra'],
            'time' => $record['pay_time'],
            'note' => !empty($record['order_title']) ? $record['order_title'] : '余额充值',
            'after_amount' => pix_wallet_get_ledger_after_amount($record['order_id'], 'cash', $user_id),
        );
    }

    return array(
        'records' => $formatted,
        'total' => $total,
        'total_pages' => $total_pages,
        'current_page' => $page,
        'per_page' => $per_page,
    );
}

/**
 * 获取用户余额记录总数
 * @return int
 */
function ppo_get_balance_records_count() {
    global $wpdb;

    $user_id = get_current_user_id();
    $order_table = $wpdb->prefix . 'ppo_pay_order';

    return intval($wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $order_table WHERE user_id = %d AND status = 1 AND order_type = 'yecz'",
        $user_id
    )));
}

/**
 * 渲染余额记录HTML
 * @param int $page 页码
 * @param int $per_page 每页数量
 * @return string HTML
 */
function user_balance_get_info($page = 1, $per_page = 10) {
    $data = ppo_get_balance_records($page, $per_page);
    $html = '';
    $cash_icon = PPO_Down::pay_icon('cash')['icon'];
    $total_count = $data['total'];

    if (empty($data['records'])) {
        return '<div class="xp-detail-empty">暂无余额记录</div>';
    }

    $nav = ppo_htmx_pager([
        'base_url'    => '/wp-json/ppo/v1/user-balance-records',
        'user_id'     => '',
        'total_pages' => ceil($total_count / $per_page),
        'current'     => $page,
        'target'      => '.wallet_record_list',
        'push_url'    => true,
        'push_url_base' => user_dashboard_url('wallet'),
        'query_args'  => ['tab' => 'balance'],
        'skeleton' => 'normal-list',
        'wpnonce' => true,
    ]);

    foreach ($data['records'] as $record) {
        $record['time'] = date('Y-m-d H:i:s', strtotime($record['time']));
        $after_html = $record['after_amount'] !== null ? '<div class="wallet-record-total">当前：¥' . number_format(floatval($record['after_amount']), 2) . '</div>' : '';
        $html .= '<div class="user_balance_record">';
        $html .= '<div class="left"><div class="object">' . esc_html($record['note']) . '</div><div class="time">' . $record['time'] . '</div></div>';
        $html .= '<div class="right wallet-record-change"><div>' . $cash_icon . ' +' . $record['extra'] . '</div>' . $after_html . '</div>';
        $html .= '</div>';
    }

    return $html . '<div class="wallet-pagination">' . $nav . '</div>';
}

function pix_wallet_get_ledger_after_amount($order_id, $asset_type, $user_id) {
    global $wpdb;

    if (empty($order_id)) {
        return null;
    }

    $table = $wpdb->prefix . 'ppo_wallet_ledger';
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
        return null;
    }

    $after = $wpdb->get_var($wpdb->prepare(
        "SELECT after_amount FROM $table WHERE user_id = %d AND asset_type = %s AND order_id = %s ORDER BY ID DESC LIMIT 1",
        intval($user_id),
        sanitize_key($asset_type),
        sanitize_text_field($order_id)
    ));

    return $after === null ? null : floatval($after);
}

function pix_wallet_find_credit_ledger_after_amount($user_id, $point, $reward_time, $task_key = '') {
    global $wpdb;

    $point = intval($point);
    if ($point <= 0 || empty($reward_time)) {
        return null;
    }

    $table = $wpdb->prefix . 'ppo_wallet_ledger';
    if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) {
        return null;
    }

    $reward_ts = strtotime($reward_time);
    if (!$reward_ts) {
        return null;
    }

    $start = date('Y-m-d H:i:s', $reward_ts - 5);
    $end = date('Y-m-d H:i:s', $reward_ts + 5);
    $change_types = array('task_reward', 'new_user_reward', 'checkin', sanitize_key($task_key));
    $change_types = array_values(array_unique(array_filter($change_types)));
    $placeholders = implode(',', array_fill(0, count($change_types), '%s'));

    $sql = "SELECT after_amount FROM $table
        WHERE user_id = %d
          AND asset_type = 'credit'
          AND change_amount = %f
          AND created_at BETWEEN %s AND %s
          AND change_type IN ($placeholders)
        ORDER BY ABS(TIMESTAMPDIFF(SECOND, created_at, %s)) ASC, ID DESC
        LIMIT 1";

    $args = array_merge(array(intval($user_id), floatval($point), $start, $end), $change_types, array(date('Y-m-d H:i:s', $reward_ts)));
    $after = $wpdb->get_var($wpdb->prepare($sql, $args));

    return $after === null ? null : floatval($after);
}

/**
 * REST API: 获取余额记录
 */
function ppo_get_user_balance_records($request) {
    $page = $request->get_param('page') ? intval($request->get_param('page')) : 1;
    $per_page = $request->get_param('per_page') ? intval($request->get_param('per_page')) : 10;
    $html = user_balance_get_info($page, $per_page);
    echo $html;
    exit;
}


