<?php

namespace App\Filament\Widgets;

use App\Models\Round;
use App\Models\Participant;
use Illuminate\Support\Facades\DB;
use EightyNine\FilamentAdvancedWidget\AdvancedChartWidget;

class ParticipantRankChartWidget extends AdvancedChartWidget
{
    protected static ?string $heading = 'Quantidade de laçadas';
    protected static ?string $icon = 'heroicon-o-chart-bar';
    protected static ?string $iconColor = 'info';
    protected static ?string $label = 'Ranking participantes';


    protected static ?string $badgeColor = 'success';
    protected static ?string $badgeIcon = 'heroicon-o-check-circle';
    protected static ?string $badgeIconPosition = 'after';
    protected static ?string $badgeSize = 'xs';

    protected function getData(): array
    {

        $ranking = Round::select('participant_id', DB::raw('COUNT(*) as acertos'))
            ->where('value', 'acerto')
            ->groupBy('participant_id')
            ->orderBy('acertos', 'DESC')
            ->get();

        $labels = [];
        $acertos = [];

        if (!empty($ranking)) {
            foreach ($ranking as $item) {
                $participant = Participant::where('id', $item->participant_id)->first();

                $labels[] = $participant->name ?? '';
                $acertos[] = $item->acertos ?? '';
            }
        }

        return [
            'datasets' => [
                [
                    'label' => 'Participantes com acertos',
                    'data' => $acertos,
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getType(): string
    {
        return 'bar';
    }
}
