<?php

namespace RTMCustomMails\ConditionProcessor;

use RTMCustomMails\SupportedObjectTypes;
use RTMMailComposer\ConditionProcessor\ConditionFunctionInterface;
use WC_Abstract_Order;
use WC_Order_Item;
use WC_Order_Item_Product;

class OrderHasProductCondition implements ConditionFunctionInterface
{

    public function __construct()
    {
    }

    public function getName(): string
    {
        return 'order_has_product';
    }

    public function getParameters(): array
    {
        $products = array_map(fn($product) => [
            'label' => "#{$product->get_id()} - {$product->get_name()}",
            'value' => $product->get_id()
        ], wc_get_products([
            'status' => ['draft', 'pending', 'private', 'publish', 'archive'],
            'limit' => -1,
        ]));

        return [
            'product' => [
                'title' => 'Product ID',
                'type' => 'number',
                'required' => true,
                'enum' => array_map(fn($p) => $p['value'], $products),
                'enumNames' => array_map(fn($p) => "#{$p['value']} - {$p['label']}", $products)
            ]
        ];
    }

    public function evaluate(array $context): bool
    {
        $product = (int)$context['product'] ?? 0;

        /** @var WC_Abstract_Order|null $order */
        $order = $context['order'] ?? null;
        if ($order) {
            /** @var WC_Order_Item|null $item */
            foreach ($order->get_items() as $item) {
                if (!$item instanceof WC_Order_Item_Product) {
                    continue;
                }
                $itemProductId = $item->get_product_id();
                if ($itemProductId === $product) {
                    return true;
                }
            }
        }
        return false;
    }

    public function getObjectType(): string
    {
        return SupportedObjectTypes::ORDER->value;
    }
}