<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Dbfilter;


class KursZahlplaeneSQLFilter extends BasicSQLFilter
{
  private const FILTER_OPTION_KURSGEBUEHR = 'kursgebuehr';

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

    $this->registerDb('Id', 'id', static::TYPE_INTEGER);
    $this->registerDb('KursId', 'knr', static::TYPE_STRING);
    $this->registerDb('Beschreibung', 'beschreibung', static::TYPE_STRING);
    $this->registerDb('Filter', 'filter', static::TYPE_STRING);
    $this->registerDb('TeilnehmerVon', 'tn_von', static::TYPE_INTEGER);
    $this->registerDb('TeilnehmerBis', 'tn_bis', static::TYPE_INTEGER);
    $this->registerDb('Zusatz', 'zusatz', static::TYPE_STRING);
    $this->registerDb('ShowInProgrammheft', 'progheftdarst', static::TYPE_BOOLEAN_W_F);
    $this->registerDb('ShowInWeb', 'webdarst', static::TYPE_BOOLEAN_W_F, true);
    $this->registerDb('Sort', 'sort', static::TYPE_INTEGER);
  }

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

  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 applyKursgebuehrenFilter(KursgebuehrenSQLFilter $filter)
  {
    $filter->makeImmutable();
    if ($filter->isEmpty()) {
      return $this;
    }

    $this->applyFilterCurrent(static::FILTER_OPTION_KURSGEBUEHR, function(\SelectQueryBuilder $builder) use ($filter) {
      $kursgebuehrBuilder = \DBWorkKursgebuehr::getDefaultInstance($builder->getDBOperation()->dbnr)
        ->findByFilterQuery($filter)
        ->select(':table:.knr');

      $var = $builder->uniqueVar();

      $dbparser = $builder->getDBOperation()->dbparser;

      return $builder
        ->and($dbparser->concat(array(
            $dbparser->rpad('knr', ':table:', 10, ' '),
            ':table:.id'
          )) . " IN (:$var:)")
        ->paramSelectQuery($var, $kursgebuehrBuilder);
    });

    return $this;
  }
}