<?php

namespace App\Filters;

use Openguru\OpenCartFramework\CriteriaBuilder\Criterion;
use Openguru\OpenCartFramework\CriteriaBuilder\Rules\BaseRule;
use Openguru\OpenCartFramework\QueryBuilder\Builder;

class ProductManufacturer extends BaseRule
{
    public const NAME = 'RULE_PRODUCT_MANUFACTURER';

    public static function initWithDefaults(): BaseRule
    {
        return new self(static::NAME, [
            'product_manufacturer_ids' => new Criterion(static::CRITERIA_OPTION_PRODUCT_MANUFACTURER, [
                'operator' => static::CRITERIA_OPERATOR_CONTAINS,
                'value' => [],
            ])
        ]);
    }

    public function apply(Builder $builder, $operand): void
    {
        /** @var Criterion $criterion */
        foreach ($this->criteria as $criterion) {
            if ($criterion->type === static::CRITERIA_OPTION_PRODUCT_MANUFACTURER) {
                $operator = $criterion->params['operator'];
                $ids = $criterion->params['value'];

                if ($ids) {
                    $builder->whereIn(
                        'products.manufacturer_id',
                        $ids,
                        $operator === static::CRITERIA_OPERATOR_NOT_CONTAINS
                    );
                } else {
                    $builder->where(
                        'products.manufacturer_id',
                        '=',
                        0,
                        $operator === static::CRITERIA_OPERATOR_NOT_CONTAINS
                    );
                }
            }
        }
    }
}
