<?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
     * @param  string|null  $quality  The quality of the item
     */
    protected function addOrUpdateOrderItem($model, int $quantity, ?string $quality = null): void
    {
        // If the item is a Perfume, we generally want separate entries (especially for custom sizes or distinct refills)
        // Adjust logic: Only search for existing if it's NOT a Perfume.
        // Or if user specifically wants Bottles/Products to merge but Perfumes to split:

        $existing = null;

        // Check instance type to decide whether to merge
        // "if item is perfume, then do not increment quantity"
        // "if item is bottle or product, then increment quantity"
        $isPerfume = $model instanceof \App\Models\Perfume;

        if (! $isPerfume) {
            $existing = $this->items->firstWhere(
                fn ($i) => $i->orderable_type === get_class($model) &&
                    $i->orderable_id === $model->id &&
                    $i->quality === $quality
            );
        }

        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),
                'quality' => $quality,
                '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): void
    {
        $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.');
    }
}
