<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\DB;

class TopCustomersChart extends ChartWidget
{
    use HasWidgetShield;

    protected ?string $heading = 'Top 5 Pelanggan (Berdasarkan Total Order)';

    protected static ?int $sort = 6;

    protected function getData(): array
    {
        $data = Order::with('customer')
            ->select('customer_id', DB::raw('SUM(total_amount) as total_spent'))
            ->groupBy('customer_id')
            ->orderByDesc('total_spent')
            ->limit(5)
            ->get();

        return [
            'datasets' => [
                [
                    'label' => 'Total Pembelian (Rp)',
                    'data' => $data->pluck('total_spent')->toArray(),
                    'backgroundColor' => [
                        '#fbbf24',
                        '#f59e0b',
                        '#d97706',
                        '#b45309',
                        '#92400e',
                    ],
                ],
            ],
            'labels' => $data->map(fn ($item) => $item->customer?->name ?? 'Umum')->toArray(),
        ];
    }

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

    protected function getOptions(): array
    {
        return [
            'indexAxis' => 'y',
        ];
    }
}
