<?php

namespace CouponsPlus\App\Coupon\Columns;

use CouponsPlus\App\Conditions\Abilities\ItemsSetFilter;
use CouponsPlus\App\Conditions\ItemsSet;
use CouponsPlus\App\Coupon\CartComponentsSet;
use CouponsPlus\App\Coupon\Column;
use CouponsPlus\App\Coupon\Columns\Meta\ORColumnMeta;
use CouponsPlus\App\Coupon\Meta\ColumnExecutionMode;
use CouponsPlus\App\Coupon\Meta\ColumnMeta;
use CouponsPlus\Original\Collections\Collection;

#[\AllowDynamicProperties]
Class ORColumn extends Column
{
    const TYPE = 'OR';
    /**
     * Legacy by default, also set in ColumnMeta::getDefaultOptions() (and in the dashboard for new coupons)
     */
    protected $executionMode = ColumnExecutionMode::TOP_TO_BOTTOM;

    public static function getColumnMeta() : ColumnMeta
    {
        return new ORColumnMeta;
    }

    public function findOffers(ItemsSet $itemsSet) : CartComponentsSet
    {
        (object) $validItemsSet = new ItemsSet([]);
        (object) $contexts = $this->getContexts();

        foreach ($this->getContexts()->asArray() as $context) {
            (object) $cartComponentsSet = $context->findOffers($itemsSet);

            if ($cartComponentsSet->isValid()) {
                return $cartComponentsSet;
            }
        }

        return $validItemsSet;
    }

    protected function getContexts() : Collection
    {
        if ($this->executionMode === ColumnExecutionMode::BOTTOM_TO_TOP) {
            return $this->contexts->invert();
        }

        return $this->contexts;
    }
}