<?php

namespace App\Filament\Widgets;

use App\Models\User;
use Filament\Widgets\ChartWidget;

class SignupsChart extends ChartWidget
{
    protected ?string $heading = 'New members, last 30 days';

    protected int|string|array $columnSpan = 1;

    protected static ?int $sort = -4;

    protected function getData(): array
    {
        $days = collect(range(29, 0))->map(fn (int $d) => now()->subDays($d)->startOfDay());

        $counts = User::where('created_at', '>=', now()->subDays(30)->startOfDay())
            ->get(['created_at'])
            ->groupBy(fn ($u) => $u->created_at->format('Y-m-d'))
            ->map->count();

        return [
            'datasets' => [[
                'label' => 'New members',
                'data' => $days->map(fn ($d) => $counts[$d->format('Y-m-d')] ?? 0)->values()->all(),
                'backgroundColor' => 'rgba(28, 43, 95, 0.55)',
                'borderColor' => '#1c2b5f',
                'borderRadius' => 4,
            ]],
            'labels' => $days->map(fn ($d) => $d->format('j M'))->values()->all(),
        ];
    }

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