<?php

namespace CouponsPlus\App\Conditions;

use CouponsPlus\Original\Collections\Collection;
use WC_Order_Item_Product;

/**
 * Adapter class to make WC_Order_Item_Product work with the existing CartItem-based system.
 * This allows the coupon engine to work with both cart items and order items.
 */
#[\AllowDynamicProperties]
class OrderItem extends CartItem
{
    protected WC_Order_Item_Product $orderItem;

    /**
     * Creates an OrderItem from a WC_Order_Item_Product
     */
    public static function createFromOrderItem(WC_Order_Item_Product $orderItem): self
    {
        $product = $orderItem->get_product();

        if (!$product) {
            throw new \InvalidArgumentException('OrderItem requires a valid product');
        }

        // Build cart-item-like array structure
        $cartItemData = [
            'key' => (string) $orderItem->get_id(),
            'product_id' => $orderItem->get_product_id(),
            'variation_id' => $orderItem->get_variation_id(),
            'quantity' => $orderItem->get_quantity(),
            'data' => $product,
            'line_subtotal' => $orderItem->get_subtotal(),
            'line_subtotal_tax' => $orderItem->get_subtotal_tax(),
            'line_total' => $orderItem->get_total(),
            'line_tax' => $orderItem->get_total_tax(),
        ];

        $instance = new self($cartItemData);
        $instance->orderItem = $orderItem;

        return $instance;
    }

    protected function getStateCollection(): Collection
    {
        return $this->getOriginalState();
    }

    /**
     * Get the underlying WC_Order_Item_Product
     */
    public function getOrderItem(): WC_Order_Item_Product
    {
        return $this->orderItem;
    }

    /**
     * Check if this is an order item (vs cart item)
     */
    public function isOrderItem(): bool
    {
        return true;
    }
}
