<?php

declare(strict_types=1);

namespace App\Filters;

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

class ProductModel extends BaseRule
{
    public const NAME = 'RULE_PRODUCT_MODEL';

    public static function initWithDefaults(): BaseRule
    {
        return new self(static::NAME, [
            'product_model' => new Criterion(static::CRITERIA_OPTION_PRODUCT_MODEL, [
                '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_MODEL) {
                $operator = $criterion->params['operator'];
                $models = $criterion->params['value'] ?? [];

                if ($models) {
                    $builder->whereIn(
                        'products.model',
                        $models,
                        $operator === static::CRITERIA_OPERATOR_NOT_CONTAINS
                    );
                } else {
                    $builder->whereRaw('TRUE = FALSE');
                }
            }
        }
    }
}
