<?php

namespace App\Filament\Resources\Manage\EggCollections\Pages;

use App\Filament\Actions\BackAction;
use App\Filament\Resources\Manage\EggCollections\EggCollectionResource;
use App\Filament\Resources\Manage\EggCollections\Traits\HasEggs;
use App\Models\EggCollectionItem;
use Filament\Resources\Pages\CreateRecord;

class CreateEggCollection extends CreateRecord
{
    use HasEggs;

    protected static string $resource = EggCollectionResource::class;

    protected ?string $heading = 'Tambah Produksi Telur';

    protected static ?string $title = 'Tambah Produksi Telur';

    protected function getHeaderActions(): array
    {
        return [
            BackAction::make()
                ->url(ListEggCollections::getUrl()),
        ];
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $data['total_eggs'] = array_sum($this->eggs ?? []);
        $data['production_date'] = now();

        return $data;
    }

    protected function afterCreate(): void
    {
        foreach ($this->eggs as $chickenId => $eggsCount) {
            if ($eggsCount <= 0) {
                continue;
            }

            EggCollectionItem::create([
                'egg_collection_id' => $this->record->id,
                'chicken_id' => $chickenId,
                'eggs_count' => $eggsCount,
            ]);
        }

        $this->eggs = [];
    }
}
