<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Dbfilter;


class KurseKategorienSQLFilter extends BasicSQLFilter
{
  protected const FILTER_OPTION_KURSE = 'kurse';

  protected function __construct()
  {
    parent::__construct();

    $this->registerDb('Id', 'id', static::TYPE_INTEGER);
    $this->registerDb('KursId', 'knr', static::TYPE_STRING);
    $this->registerDb('KategorieId', 'kategorie_id', static::TYPE_INTEGER);
  }

  
  public function getTablePraeffix(): string
  {
    return 'kk';
  }

  public function equalsId($id): IFilter
  {
    $this->applyFilterCurrent(
      static::FILTER_OPTION_ID,
      SQLFilterUtils::filterEqualsIdInt('id', $id)
    );

    return $this;
  }

  public function inId(iterable $ids): IFilter
  {
    $this->applyFilterCurrent(
      static::FILTER_OPTION_ID,
      SQLFilterUtils::filterInIdInt('id', $ids)
    );

    return $this;
  }

  public function applyKurseFilter(KurseSQLFilter $filter): self
  {
    $filter->makeImmutable();
    if ($filter->isEmpty()) {
      return $this;
    }

    $this->applyFilterCurrent(static::FILTER_OPTION_KURSE, static function(\SelectQueryBuilder $builder) use ($filter): \SelectQueryBuilder {
      $dbwKurse = \DBWorkKurseBase::getDefaultInstance($builder->getDBOperation()->dbnr);
      $kurseQuery = $dbwKurse->findByFilterQuery($filter)
        ->select(':table:.nr');

      $var = $builder->uniqueVar();

      return $builder
        ->and(":table:.knr IN (:$var:)")
        ->paramSelectQuery($var, $kurseQuery);
    });

    return $this;
  }
}