<?php

namespace App\Http\Controllers\Frontend\Ranking;

use App\Http\Controllers\Controller;
use App\Models\PlayerRanking;
use Illuminate\Http\Request;
use Inertia\Inertia;

class PvpRankingController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search', '');
        $perPage = $request->input('per_page', 10);

        $query = PlayerRanking::query()
            ->orderBy('pk_count', 'DESC')
            ->orderBy('reputation', 'DESC');

        if (!empty($search)) {
            $query->where('role_name', 'like', "%{$search}%");
        }

        $rankings = $query->paginate($perPage);

        $rankings->getCollection()->transform(function ($item, $index) use ($rankings) {
            $item->rank = ($rankings->currentPage() - 1) * $rankings->perPage() + $index + 1;
            $item->class_name = config('game.classes')[$item->cls] ?? 'Unknown';
            return $item;
        });

        return Inertia::render('frontend/ranking/pvp/index', [
            'rankings' => $rankings,
            'filters' => [
                'search' => $search,
                'per_page' => $perPage,
            ],
        ]);
    }
}
