<?php

namespace App\Traits\Restock;

use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use App\Models\RestockItem;
use App\Models\Warehouse;
use Livewire\Attributes\On;

trait WithRestockUpdateItem
{
    public string $modalTitle = '';

    public function updateItem(): void
    {
        $this->canOrAbort('create restock');

        if (! $this->form->warehouse_id) {
            $this->toast('Silakan pilih gudang terlebih dahulu.', 'Gagal', 'warning');

            return;
        }

        $warehouse = Warehouse::find($this->form->warehouse_id);

        if (! $warehouse) {
            $this->toast('Gudang tidak ditemukan.', 'Gagal', 'danger');

            return;
        }

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

        if ($item) {
            $newQuantity = parseRupiahToInt($this->form->quantity_edit);

            if ($newQuantity <= 0) {
                $this->toast('Jumlah harus lebih dari 0.', 'Gagal', 'danger');

                return;
            }

            $relationName = match ($item->restockable_type) {
                Perfume::class => 'perfumes',
                Product::class => 'products',
                Bottle::class => 'bottles',
                default => null,
            };

            if ($relationName) {
                $warehouseStock = $warehouse->{$relationName}()
                    ->where($item->restockable_type::make()->getTable().'.id', $item->restockable_id)
                    ->first()
                    ?->pivot
                    ?->stock ?? 0;

                if ($newQuantity > $warehouseStock) {
                    $this->toast("Stok tidak mencukupi (Update). Stok di gudang: {$warehouseStock}.", 'Gagal', 'danger');

                    return;
                }
            }

            $item->update([
                'quantity' => $newQuantity,
            ]);
        }

        $this->restockItems = $this->loadRestockItems();
        $this->toast('Item berhasil diperbarui.');
        $this->dispatch('modal:close', 'form-modal');
    }

    #[On('modal:open')]
    public function openModal($item): void
    {
        $item = RestockItem::find($item['item']);
        $this->form->item_id = $item->id;
        $this->form->quantity_edit = formatCurrencyNumber($item->quantity, '');
        $this->modalTitle = $item->restockable->name;
    }
}
