<?php

namespace App\Filament\Widgets;

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

class OrderTrendChart extends ChartWidget
{
    use HasWidgetShield;

    protected ?string $heading = 'Trend Jumlah Pesanan (30 Hari Terakhir)';

    protected static ?int $sort = 4;

    protected function getData(): array
    {
        $data = Order::where('order_date', '>=', now()->subDays(30))
            ->orderBy('order_date')
            ->get()
            ->groupBy(fn ($item) => Carbon::parse($item->order_date)->translatedFormat('Y-m-d'))
            ->map(fn ($items) => $items->count());

        return [
            'datasets' => [
                [
                    'label' => 'Jumlah Pesanan',
                    'data' => $data->values()->toArray(),
                    'fill' => 'start',
                    'tension' => 0.4,
                ],
            ],
            'labels' => $data->keys()->map(fn ($date) => Carbon::parse($date)->translatedFormat('d M'))->toArray(),
        ];
    }

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