<?php

namespace App\Filament\Widgets;

use Filament\Widgets\ChartWidget;
use Functional\Users\Models\User;
use Illuminate\Support\Carbon;

/**
 * Croissance cumulée des utilisateurs inscrits (ligne).
 */
class UsersGrowthChart extends ChartWidget
{
    protected static ?int $sort = 3;

    protected int|string|array $columnSpan = 1;

    public function getHeading(): string
    {
        return 'Croissance des utilisateurs';
    }

    protected function getData(): array
    {
        $countsByDay = User::query()
            ->selectRaw('DATE(created_at) as day, COUNT(*) as total')
            ->groupBy('day')
            ->orderBy('day')
            ->pluck('total', 'day');

        $labels = [];
        $data = [];
        $cumulative = 0;

        foreach ($countsByDay as $day => $total) {
            $cumulative += (int) $total;
            $labels[] = Carbon::parse($day)->format('d/m/Y');
            $data[] = $cumulative;
        }

        return [
            'datasets' => [
                [
                    'label' => 'Utilisateurs inscrits (cumulé)',
                    'data' => $data,
                    'borderColor' => '#f59e0b',
                    'backgroundColor' => 'rgba(245, 158, 11, 0.15)',
                    'fill' => true,
                ],
            ],
            'labels' => $labels,
        ];
    }

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