<?php

/**
 * 文件功能：用户金币/积分流水日志查询
 * 对应超级管理员级别的查询页面。可以按用户、增减、货币类型等筛选所有的账目流动。
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers\Admin;

use App\Enums\CurrencySource;
use App\Http\Controllers\Controller;
use App\Models\UserCurrencyLog;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CurrencyLogController extends Controller
{
    /**
     * 显示流水日志列表
     * 支持多条件检索，仅 superlevel 以及上可以访问此页面
     */
    public function index(Request $request): View
    {
        $query = UserCurrencyLog::query()->with('user');

        // 查询条件过滤
        if ($request->filled('username')) {
            $query->where('username', 'like', '%'.$request->input('username').'%');
        }

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

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

        if ($request->filled('remark')) {
            $query->where('remark', 'like', '%'.$request->input('remark').'%');
        }

        if ($request->filled('direction')) {
            if ($request->input('direction') === 'in') {
                $query->where('amount', '>', 0);
            } elseif ($request->input('direction') === 'out') {
                $query->where('amount', '<', 0);
            }
        }

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

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

        // 默认按时间倒序
        $logs = $query->latest('id')->paginate(50)->withQueryString();

        $allSources = CurrencySource::cases();

        return view('admin.currency-logs.index', compact('logs', 'allSources'));
    }
}
