<?php

namespace App\Traits\Purchase;

use App\Models\PurchaseItem;
use Flux\Flux;
use Livewire\Attributes\On;

trait WithUpdateItem
{
    public string $modalTitle = 'Ubah Item';

    #[On('modal:open')]
    public function openModal(PurchaseItem $item)
    {
        $this->modalTitle = $item->purchasable->name;

        $this->form->item_id = $item->id;

        $this->form->quantity_edit = currency($item->quantity);
    }

    public function closeModal()
    {
        $this->reset('form.item_id');
    }

    public function updateItem()
    {
        $item = PurchaseItem::find($this->form->item_id);

        $item->update([
            'quantity' => replaceCurrency($this->form->quantity_edit),
            'total_price' => (int) $item->purchasable->cost_price * (int) replaceCurrency($this->form->quantity_edit),
        ]);

        $item->refresh();

        $this->purchaseItems = $this->purchaseItems->map(fn ($i) => $i->id === $item->id ? $item : $i);

        $this->form->total = currency($this->purchaseItems->sum('total_price'));

        $this->toast('Item berhasil diperbarui.');

        Flux::modals('form-modal')->close();
    }
}
