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

if (!defined('BASEDIR')) {
  include_once '..' . DIRECTORY_SEPARATOR . 'constants.php';
}


class DBWorkMwst extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'id, schluessel, text, prozente, anteil';
    $this->_dataModulFields = array('text', 'schluessel', 'prozente', 'anteil', 'id');
  }

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

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

  public function getAllCached()
  {
    static $cache = null;
    if (is_null($cache)) {
      $cache = ArrayOperations::setAttributAsKey($this->getAll(), 'schluessel');
    }

    return $cache;
  }

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

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

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

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

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

    return $this->getAllRows();
  }

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

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

    return $this->getFirstRowOrNull();
  }

  
  public function countByFilter(\Kufer\Web\Classes\Dbfilter\MwstSQLFilter $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);
  }
}