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

namespace Kufer\Web\Classes\Dbfilter;

use Kufer\Web\Classes\Db\DBWorkHLAusbildungsSchablone;


class HLAusbildungSchablonenDetSQLFilter extends AbstractSQLFilter
{
  private const FILTER_OPTION_HL_AUSB_SCHABL = 'hlausbschabl';
  private const FILTER_OPTION_KURSE_FAECHER = 'kursefaecher';

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

    $this->registerDb('Id', 'id', static::TYPE_INTEGER);
    $this->registerDb('AusbildungSchabloneId', 'ausbildung_schablone_id', static::TYPE_INTEGER);
    $this->registerDb('FachId', 'fach', static::TYPE_INTEGER);
  }

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

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

    $this->applyFilterCurrent(self::FILTER_OPTION_HL_AUSB_SCHABL, static function(\SelectQueryBuilder $builder) use ($filter) {
      $ausbSchablBuilder = DBWorkHLAusbildungsSchablone::getDefaultInstance($builder->getDBOperation()->dbnr)->findByFilterQuery($filter)
        ->select(':table:.id');

      $var = $builder->uniqueVar();

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

    return $this;
  }

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

    $this->applyFilterCurrent(self::FILTER_OPTION_KURSE_FAECHER, static function(\SelectQueryBuilder $builder) use ($filter) {
      $kurseFaecherBuilder = \DBWorkKursFach::getDefaultInstance($builder->getDBOperation()->dbnr)->findByFilterQuery($filter)
        ->select(':table:.fach_nr');

      $var = $builder->uniqueVar();

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

    return $this;
  }
}