<?php

namespace CouponsPlus\App\Conditions\BuiltIn\Filters;

use CouponsPlus\App\Conditions\CartItem;
use CouponsPlus\App\Conditions\Filter;
use CouponsPlus\App\Conditions\IntersectionFilter;
use CouponsPlus\App\Conditions\ItemsSet;
use CouponsPlus\App\Validators\InclusionValueValidator;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\Original\Collections\Mapper\Types;

#[\AllowDynamicProperties]
Class OnSale extends Filter
{
    const TYPE = 'OnSale';
    const SET = IntersectionFilter::class;

    public static function getName() : string
    {
        return __('On Sale?', 'coupons-plus-for-woocommerce');
    }

    public static function getDescription() : string
    {
        return __("Add this filter to pick or exclude items that are on sale. Remove this filter to include any.", 'coupons-plus-for-woocommerce');
    }

    public static function getOptions() : Collection
    {
        return new Collection([
            'type' => Types::STRING()->withDefault('exclude')
                ->allowed([
                    __('Regular Price Only', 'coupons-plus-for-woocommerce') => 'exclude',
                    __('On Sale Only', 'coupons-plus-for-woocommerce') => 'include',
                ])->meta(
                        [
                            'alternativeLabels' => [
                                'include' => __('Discounted', 'coupons-plus-for-woocommerce'),
                                'exclude' => __('Not discounted', 'coupons-plus-for-woocommerce'),
                            ],
                        ]
                    )
        ]);
    }

    public function filterSet(ItemsSet $itemsSet) : ItemsSet
    {
        return new ItemsSet($itemsSet->getItems()->filter(function(CartItem $cartItem) : bool {
            (boolean) $isOnSale = $cartItem->getProduct()->is_on_sale($context = 'edit');

            if ($this->options->type->is('include')) {
                return $isOnSale;
            }

            return !$isOnSale;
        })->asArray());
    }
}