<?php

namespace App\Traits\Order;

use App\Models\OrderItem;

trait WithManageItem
{
    /**
     * Adds a new order item or updates the quantity if it already exists in the order.
     *
     * @param  mixed  $model  The model instance (Perfume, Bottle, or Product)
     * @param  int  $quantity  The quantity to add
     */
    protected function addOrUpdateOrderItem($model, int $quantity)
    {
        $existing = $this->items->firstWhere(fn ($i) => $i->orderable_type === get_class($model) && $i->orderable_id === $model->id);

        if ($existing) {
            $existing->increment('quantity', $quantity);
            $existing->refresh();
        } else {
            $existing = OrderItem::create([
                'user_id' => auth()->id(),
                'orderable_id' => $model->id,
                'orderable_type' => get_class($model),
                'cogs' => $model->cost_price ?? 0,
                'quantity' => $quantity,
                'unit_price' => $model->sale_price ?? 0,
            ]);

            $this->items->push($existing);
        }

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

        $this->subtotal = $this->getSubtotal();
        $this->total = $this->getTotal();
    }

    public function deleteItem(OrderItem $item)
    {
        $this->items = $this->items->reject(fn ($i) => $i->id === $item->id);

        $item->delete();

        // Recalculate totals
        $this->subtotal = $this->getSubTotal();
        $this->total = $this->getTotal();

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