You've already forked Atomcms-edit
87 lines
2.6 KiB
PHP
Executable File
87 lines
2.6 KiB
PHP
Executable File
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Http\Controllers\Community;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\User;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class RadioLeaderboardController extends Controller
|
|
{
|
|
public function __invoke(Request $request)
|
|
{
|
|
$period = $request->get('period', 'all');
|
|
|
|
$users = match ($period) {
|
|
'weekly' => $this->getWeeklyLeaderboard(),
|
|
'monthly' => $this->getMonthlyLeaderboard(),
|
|
default => $this->getAllTimeLeaderboard(),
|
|
};
|
|
|
|
// Extract top 3 from already-fetched data
|
|
$topUserData = array_slice($users, 0, 3);
|
|
$topUserIds = array_column($topUserData, 'id');
|
|
$topUsers = User::whereIn('id', $topUserIds)
|
|
->get()
|
|
->keyBy('id');
|
|
|
|
return view('community.radio.leaderboard', ['users' => $users, 'topUsers' => $topUsers, 'period' => $period]);
|
|
}
|
|
|
|
private function getAllTimeLeaderboard(): array
|
|
{
|
|
return User::where('radio_points', '>', 0)
|
|
->orderBy('radio_points', 'desc')
|
|
->limit(100)
|
|
->get()
|
|
->map(fn ($user, $index) => [
|
|
'rank' => $index + 1,
|
|
'id' => $user->id,
|
|
'username' => $user->username,
|
|
'avatar' => $user->avatar ?? null,
|
|
'points' => $user->radio_points,
|
|
])
|
|
->toArray();
|
|
}
|
|
|
|
private function getWeeklyLeaderboard(): array
|
|
{
|
|
return $this->getPointsLeaderboard(now()->subWeek());
|
|
}
|
|
|
|
private function getMonthlyLeaderboard(): array
|
|
{
|
|
return $this->getPointsLeaderboard(now()->subMonth());
|
|
}
|
|
|
|
private function getPointsLeaderboard(Carbon $since): array
|
|
{
|
|
$points = DB::table('radio_listener_points')
|
|
->where('earned_at', '>=', $since)
|
|
->select('user_id', DB::raw('SUM(points) as total_points'))
|
|
->groupBy('user_id')
|
|
->orderBy('total_points', 'desc')
|
|
->limit(100)
|
|
->get();
|
|
|
|
$userIds = $points->pluck('user_id')->toArray();
|
|
$users = User::whereIn('id', $userIds)->get()->keyBy('id');
|
|
|
|
return $points->map(function ($item, $index) use ($users) {
|
|
$user = $users->get($item->user_id);
|
|
|
|
return [
|
|
'rank' => $index + 1,
|
|
'id' => $item->user_id,
|
|
'username' => $user?->username ?? 'Onbekend',
|
|
'avatar' => $user?->avatar ?? null,
|
|
'points' => (int) $item->total_points,
|
|
];
|
|
})->toArray();
|
|
}
|
|
}
|