<?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' => ['private', 'publish'],
            'limit' => 400,
        ]));

        $oneOf = array_map(fn($product) => [
            'const' => $product['value'],
            'title' => $product['label']
        ], $products);

        return [
            'product' => [
                'title' => 'Product ID',
                'type' => 'number',
                'required' => true,
                'oneOf' => $oneOf
            ]
        ];
    }


    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;
    }
}
