<?php

/**
 * 文件功能：银行控制器
 *
 * 提供存款、取款、余额查询三个接口，金币在流通账户（jjb）
 * 与银行账户（bank_jjb）之间互转，所有操作记录到 bank_logs。
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers;

use App\Models\BankLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class BankController extends Controller
{
    /**
     * 查询银行余额及最近20条流水记录
     */
    public function info(): JsonResponse
    {
        $user = Auth::user();
        $logs = BankLog::where('user_id', $user->id)
            ->latest()
            ->limit(20)
            ->get(['type', 'amount', 'balance_after', 'created_at']);

        return response()->json([
            'status' => 'success',
            'jjb' => $user->jjb ?? 0,
            'bank_jjb' => $user->bank_jjb ?? 0,
            'logs' => $logs,
        ]);
    }

    /**
     * 查询银行存款排行榜 (分页显示)
     */
    public function ranking(Request $request): JsonResponse
    {
        $direction = strtolower($request->query('sort', 'desc')) === 'asc' ? 'asc' : 'desc';

        $users = \App\Models\User::where('bank_jjb', '>', 0)
            ->orderBy('bank_jjb', $direction)
            ->paginate(20, ['id', 'username', 'bank_jjb', 'sex', 'usersf', 'user_level']);

        return response()->json([
            'status' => 'success',
            'ranking' => $users->map(function ($u) {
                // 提供必要的前端展示字段
                return [
                    'id' => $u->id,
                    'username' => $u->username,
                    'bank_jjb' => $u->bank_jjb,
                    'sex' => $u->sex,
                    'usersf' => $u->usersf,
                    'user_level' => $u->user_level,
                    'headfaceUrl' => $u->headfaceUrl,
                ];
            }),
            'pagination' => [
                'current_page' => $users->currentPage(),
                'last_page' => $users->lastPage(),
                'total' => $users->total(),
            ],
        ]);
    }

    /**
     * 存款：从流通金币（jjb）转入银行（bank_jjb）
     *
     * 请求参数：amount（正整数）
     */
    public function deposit(Request $request): JsonResponse
    {
        $request->validate([
            'amount' => 'required|integer|min:1|max:9999999',
        ]);

        $amount = $request->integer('amount');
        $user = Auth::user();

        if (($user->jjb ?? 0) < $amount) {
            return response()->json([
                'status' => 'error',
                'message' => '流通金币不足！当前余额 '.($user->jjb ?? 0)." 枚，无法存入 {$amount} 枚。",
            ]);
        }

        DB::transaction(function () use ($user, $amount): void {
            $user->decrement('jjb', $amount);
            $user->increment('bank_jjb', $amount);

            BankLog::create([
                'user_id' => $user->id,
                'type' => 'deposit',
                'amount' => $amount,
                'balance_after' => $user->fresh()->bank_jjb,
            ]);
        });

        $fresh = $user->fresh();

        return response()->json([
            'status' => 'success',
            'message' => "成功存入 {$amount} 枚金币！",
            'jjb' => $fresh->jjb,
            'bank_jjb' => $fresh->bank_jjb,
        ]);
    }

    /**
     * 取款：从银行（bank_jjb）转回流通金币（jjb）
     *
     * 请求参数：amount（正整数）
     */
    public function withdraw(Request $request): JsonResponse
    {
        $request->validate([
            'amount' => 'required|integer|min:1|max:9999999',
        ]);

        $amount = $request->integer('amount');
        $user = Auth::user();

        if (($user->bank_jjb ?? 0) < $amount) {
            return response()->json([
                'status' => 'error',
                'message' => '银行余额不足！当前存款 '.($user->bank_jjb ?? 0)." 枚，无法取出 {$amount} 枚。",
            ]);
        }

        DB::transaction(function () use ($user, $amount): void {
            $user->decrement('bank_jjb', $amount);
            $user->increment('jjb', $amount);

            BankLog::create([
                'user_id' => $user->id,
                'type' => 'withdraw',
                'amount' => $amount,
                'balance_after' => $user->fresh()->bank_jjb,
            ]);
        });

        $fresh = $user->fresh();

        return response()->json([
            'status' => 'success',
            'message' => "成功取出 {$amount} 枚金币！",
            'jjb' => $fresh->jjb,
            'bank_jjb' => $fresh->bank_jjb,
        ]);
    }
}
