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


class DBWorkFachAdr extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'nr, kennz';
    $this->_dataModulFields = array('nr', 'kennz');
  }

  
  public function getNewObject()
  {
    return new FachAdr();
  }

  public function getTableName(): string
  {
    return 'fach_adr';
  }

  public function getAllQuery(): \SelectQueryBuilder
  {
    return $this->getSelectQueryBuilder()
      ->select($this->select)
      ->from($this->getTableName(), 'fa')
      ->paramRaw('table', 'fa');
  }

  
  public function findByKennzQuery($pFachKennzeichen): \SelectQueryBuilder
  {
    return $this->getAllQuery()
      ->and($this->dboperation->dbparser->caseInsensitiveLike('fa.', 'kennz', ':fachKennz:'))
      ->paramStringNoQuotes('fachKennz', $pFachKennzeichen . '%');
  }

  
  public function findByKennz($pFachKennzeichen)
  {
    $builder = $this->findByKennzQuery($pFachKennzeichen);
    $this->dboperation->clear();
    $this->dboperation->query($builder->getSQL());

    return $this->getAllRows();
  }

  
  public function findByKennzBereich($pFachKennzeichenFrom, $pFachKennzeichenTo)
  {
    $cleanKennzFrom = $this->dboperation->getString4Sql($pFachKennzeichenFrom);
    $cleanKennztTo = $this->dboperation->getString4Sql($pFachKennzeichenTo);

    $sql = 'SELECT ' . $this->select . ' FROM ' . $this->getTableName() . ' fa'
           . ' WHERE ' . $this->dboperation->dbparser->caseInsensitiveBetween('fa.', 'kennz', $cleanKennzFrom, $cleanKennztTo);

    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getAllRows();
  }

  public function findByFilterQuery(\Kufer\Web\Classes\Dbfilter\FaecherAdrSQLFilter $filter): \SelectQueryBuilder
  {
    $condition = $filter->createSql($this->dboperation);

    return $this->getAllQuery()
      ->and($condition);
  }

  
  public function findByFilter(\Kufer\Web\Classes\Dbfilter\FaecherAdrSQLFilter $filter): array
  {
    $builder = $this->findByFilterQuery($filter);

    $this->dboperation->clear();
    $this->dboperation->query($builder->getSQL());

    return $this->getAllRows();
  }

  
  public function countByFilter(\Kufer\Web\Classes\Dbfilter\FaecherAdrSQLFilter $filter): int
  {
    $builder = $this->findByFilterQuery($filter)
      ->select('COUNT(*) AS anzahl');

    $this->dboperation->clear();
    $this->dboperation->query($builder->getSQLForInnerQuery());

    $this->dboperation->selectrow(0);

    return $this->getValue('anzahl', \DatamodulVarType::TYPE_INT);
  }

  public function existsByFilter(\Kufer\Web\Classes\Dbfilter\FaecherAdrSQLFilter $filter): bool
  {
    return $this->countByFilter($filter) > 0;
  }
}