<?php

namespace App\Filament\Widgets;

use App\Models\SiteActivity;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\DB;

class TrafficSourcesChart extends ChartWidget
{
    public function getHeading(): ?string
    {
        return 'Traffic Sources (Leads)';
    }
    protected static ?int $sort = 2;

    protected function getData(): array
    {
        $data = SiteActivity::select('utm_source', DB::raw('count(*) as total'))
            ->whereNotNull('utm_source')
            ->groupBy('utm_source')
            ->orderByDesc('total')
            ->limit(5)
            ->get();

        return [
            'datasets' => [
                [
                    'label' => 'Source Distribution',
                    'data' => $data->pluck('total')->toArray(),
                    'backgroundColor' => [
                        '#2563EB', // blue
                        '#059669', // green
                        '#D946EF', // pink
                        '#F59E0B', // amber
                        '#64748B', // slate
                    ],
                ],
            ],
            'labels' => $data->pluck('utm_source')->map(fn($s) => ucfirst($s))->toArray(),
        ];
    }

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