<?php

/**
 * 文件功能：后台会员购买日志控制器
 * 负责展示聊天室 VIP 在线支付订单列表，并支持按用户、状态、订单号和日期筛选
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\VipPaymentOrder;
use Illuminate\Http\Request;
use Illuminate\View\View;

class VipPaymentLogController extends Controller
{
    /**
     * 显示会员购买日志列表
     *
     * @param  Request  $request  当前查询请求
     */
    public function index(Request $request): View
    {
        $query = VipPaymentOrder::query()->with(['user:id,username', 'vipLevel:id,name,color,icon']);

        if ($request->filled('username')) {
            $username = (string) $request->input('username');

            // 通过用户关联模糊匹配用户名，便于后台快速定位某个会员订单。
            $query->whereHas('user', function ($builder) use ($username): void {
                $builder->where('username', 'like', '%'.$username.'%');
            });
        }

        if ($request->filled('status')) {
            $query->where('status', (string) $request->input('status'));
        }

        if ($request->filled('order_no')) {
            $keyword = (string) $request->input('order_no');
            $query->where(function ($builder) use ($keyword): void {
                $builder->where('order_no', 'like', '%'.$keyword.'%')
                    ->orWhere('merchant_order_no', 'like', '%'.$keyword.'%')
                    ->orWhere('payment_order_no', 'like', '%'.$keyword.'%')
                    ->orWhere('provider_trade_no', 'like', '%'.$keyword.'%');
            });
        }

        if ($request->filled('date_start')) {
            $query->whereDate('created_at', '>=', (string) $request->input('date_start'));
        }

        if ($request->filled('date_end')) {
            $query->whereDate('created_at', '<=', (string) $request->input('date_end'));
        }

        $logs = $query->latest('id')->paginate(30)->withQueryString();

        return view('admin.vip-payment-logs.index', [
            'logs' => $logs,
            'statusOptions' => [
                'created' => '待创建',
                'pending' => '待支付',
                'paid' => '已支付',
                'closed' => '已关闭',
                'failed' => '失败',
            ],
        ]);
    }
}
