<?php

namespace App\Http\Controllers\Frontend\Ranking;

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

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

        $query = FactionRanking::query();

        if ($sortBy === 'pk_count') {
            $query->orderBy('total_pk_count', 'DESC')
                ->orderBy('level', 'DESC');
        } else {
            $query->orderBy('level', 'DESC')
                ->orderBy('member_count', 'DESC');
        }

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

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

        $rankings->getCollection()->transform(function ($item, $index) use ($rankings) {
            $item->rank = ($rankings->currentPage() - 1) * $rankings->perPage() + $index + 1;
            return $item;
        });

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