<?php

namespace App\Filament\Widgets;

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

class EggProductionChart extends ChartWidget
{
    use HasWidgetShield;

    protected ?string $heading = 'Trend Produksi Telur (30 Hari Terakhir)';

    protected static ?int $sort = 2;

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

        return [
            'datasets' => [
                [
                    'label' => 'Total Telur',
                    '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';
    }
}
