<?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): void
    {
        $this->modalTitle = $item->purchasable->name;

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

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

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

    public function updateItem(): void
    {
        $quantity = parseRupiahToInt($this->form->quantity_edit);

        if ($quantity <= 0) {
            $this->toast('Jumlah item tidak valid.', 'Gagal', 'danger');

            return;
        }

        $item = PurchaseItem::find($this->form->item_id);

        if (! $item) {
            $this->toast('Item tidak found.', 'Gagal', 'danger');

            return;
        }

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

        $item->refresh();

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

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

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

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