<?php

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

trait HasEggs
{
    /**
     * [chicken_id => eggs_count]
     */
    public array $eggs = [];

    public function addEgg(int $chickenId): void
    {
        $current = $this->eggs[$chickenId] ?? 0;
        $this->eggs[$chickenId] = $current + 1;

        $this->syncTotalEggsFromState();
    }

    public function decreaseEgg(int $chickenId): void
    {
        $current = $this->eggs[$chickenId] ?? 0;
        if ($current <= 0) {
            return;
        }

        $new = $current - 1;
        if ($new > 0) {
            $this->eggs[$chickenId] = $new;
        } else {
            unset($this->eggs[$chickenId]);
        }

        $this->syncTotalEggsFromState();
    }

    protected function syncTotalEggsFromState(): void
    {
        $total = array_sum($this->eggs);

        $this->form->fill([
            ...$this->form->getState(),
            'total_eggs' => $total,
        ]);
    }
}
