<?php

namespace App\Traits\Order;

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

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

    #[On('modal:open')]
    public function openModal(OrderItem $item)
    {
        $this->modalTitle = $item->orderable->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 = OrderItem::find($this->form->item_id);

        if (! $item) {
            $this->toast('Item tidak ditemukan. Silakan coba lagi.', 'Gagal', 'danger');

            return;
        }

        $item->update(['quantity' => replaceCurrency($this->form->quantity_edit)]);

        $item->refresh();

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

        $this->subtotal = $this->getSubTotal();

        $this->total = $this->getTotal();

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

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