<?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\EditRecord;

class EditEggCollection extends EditRecord
{
    use HasEggs;

    protected static string $resource = EggCollectionResource::class;

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

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

    public function mount($record): void
    {
        parent::mount($record);

        $this->eggs = $this->record->items()
            ->pluck('eggs_count', 'chicken_id')
            ->map(fn ($count) => (int) $count)
            ->toArray();
    }

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

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

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

        return $data;
    }

    protected function afterSave(): void
    {
        EggCollectionItem::where('egg_collection_id', $this->record->id)->delete();

        foreach ($this->eggs as $chickenId => $eggsCount) {
            if ($eggsCount <= 0) {
                continue;
            }

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