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

namespace Kufer\Web\Classes\Db;

use Kufer\Web\Classes\Datamodul\HLBuchungskreisInt;
use Kufer\Web\Classes\Dbfilter\HLBuchungskreiseIntSQLFilter;


class DBWorkHLBuchungskreisInt extends \DBWorkGenerated
{
  public function __construct($pDBnr = 1, $pNewInstance = false)
  {
    parent::__construct($pDBnr, $pNewInstance);

    $this->_dataModulFields = array('id', 'bezeichnung', 'von', 'bis', 'bemerkung');
    $this->select = implode(',', $this->_dataModulFields);
  }

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

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

  
  public function findMatchingBuchungskreisForNumber(string $number): ?HLBuchungskreisInt
  {
    if ($number === '') { 
      return null;
    }

    $filter = HLBuchungskreiseIntSQLFilter::create();

    
    $filter->notAny(static function(HLBuchungskreiseIntSQLFilter $filter): void {
      $filter->equalsVon('');
      $filter->equalsBis('');
    });

    $filter->lessEqualsVon($number);
    $filter->greaterEqualsBis($number);

    return $this->findOneByFilter($filter);
  }

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

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

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

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

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

    return $this->getAllRows();
  }

  
  public function findOneByFilter(\Kufer\Web\Classes\Dbfilter\HLBuchungskreiseIntSQLFilter $filter): ?\Kufer\Web\Classes\Datamodul\HLBuchungskreisInt
  {
    $builder = $this->findByFilterQuery($filter);

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

    return $this->getFirstRowOrNull();
  }

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

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

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

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