<?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 OrderHasProductWithAttributeCondition implements ConditionFunctionInterface
{

    public function __construct()
    {
    }

    /**
     * @inheritDoc
     */
    public function getName(): string
    {
        return 'order_has_product_with_attribute';
    }

    /**
     * @inheritDoc
     */
    public function getParameters(): array
    {
        $attributeTaxonomies = wc_get_attribute_taxonomies();
        $labels = array_reduce($attributeTaxonomies, function ($carry, $item) {
            $carry['pa_' . $item->attribute_name] = $item->attribute_label;
            return $carry;
        }, []);

        $terms = $attributeTaxonomies ? get_terms([
            'taxonomy' => array_keys($labels),
            'hide_empty' => false,
            'number' => ''
        ]) : [];

        $oneOf = array_map(fn($term) => [
            'const' => $term->term_id,
            'title' => $labels[$term->taxonomy] . ': ' . $term->name
        ], $terms);

        return [
            'attribute' => [
                'title' => 'Attribute ID',
                'type' => 'integer',
                'required' => true,
                'oneOf' => $oneOf
            ]
        ];
    }


    public function evaluate(array $context): bool
    {
        $attributeId = $context['attribute'] ?? -1;
        /** @var WC_Abstract_Order|null $order */
        $order = $context['order'] ?? null;
        if (!$order) {
            return false;
        }
        /** @var WC_Order_Item|null $item */
        foreach ($order->get_items() as $item) {
            if (!$item instanceof WC_Order_Item_Product) {
                continue;
            }
            $product = $item->get_product();
            if ($product) {
                $attributes = $product->get_attributes();
                foreach ($attributes as $attribute) {
                    if (in_array($attributeId, $attribute->get_options())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

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