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

namespace Kufer\Web\Classes\Dbfilter;

use Kufer\Web\Classes\Db\DBWorkHLAusbildungsSchabloneDet;
use Kufer\Web\Classes\Db\DBWorkTnAusbildungVonSchablone;


class HLAusbildungSchablonenSQLFilter extends AbstractSQLFilter
{
  private const FILTER_OPTION_TN_AUSBILDUNG = 'tn_ausbildung';
  private const FILTER_OTPTION_HL_AUSB_SCHABL_DET = 'hlausbschabldet';

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

    $this->registerDb('Id', 'id', static::TYPE_INTEGER);
    $this->registerDb('Name', 'ausbildung_schablone', static::TYPE_STRING);
    $this->registerDb('Kuerzel', 'kuerzel', static::TYPE_STRING);
    $this->registerDb('Beschreibung', 'beschreibung', static::TYPE_STRING);
    $this->registerDb('Bemerkung', 'bemerkung', static::TYPE_STRING);
  }

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

  public function applyTnAusbildungFilter(TnAusbildungVonSchabloneSQLFilter $filter): self
  {
    $filter->makeImmutable();

    if ($filter->isEmpty()) {
      return $this;
    }

    $this->applyFilterCurrent(self::FILTER_OPTION_TN_AUSBILDUNG, function(\SelectQueryBuilder $builder) use ($filter) {
      $tnAusbildungBuilder = DBWorkTnAusbildungVonSchablone::getDefaultInstance($builder->getDBOperation()->dbnr)->findByFilterQuery($filter)
        ->select(':table:.hlid');

      $var = $builder->uniqueVar();

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

    return $this;
  }

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

    $this->applyFilterCurrent(self::FILTER_OTPTION_HL_AUSB_SCHABL_DET, function(\SelectQueryBuilder $builder) use ($filter) {
      $ausbSchablDetBuilder = DBWorkHLAusbildungsSchabloneDet::getDefaultInstance($builder->getDBOperation()->dbnr)->findByFilterQuery($filter)
        ->select(':table:.ausbildung_schablone_id');

      $var = $builder->uniqueVar();

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

    return $this;
  }

  public function ignoreInvalid(): self
  {
    $this->notAny(static function($filter) {
      $filter->equalsName('-1'); 

      return $filter;
    });

    return $this;
  }
}