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


class DBWorkAltersklasse extends DBWork
{
  
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'id, kennz, text, von, bis ';
    $this->orderby = 'kennz';
  }

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

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

  
  public function getCurrentRow($pRefreshCache = false)
  {
    $tmp = $this->getNewObject();
    $tmp->id = $this->getDatamodulValue('id');
    $tmp->kennz = $this->getDatamodulValue('kennz');
    $tmp->text = $this->getDatamodulValue('text');
    $tmp->von = $this->getDatamodulValue('von');
    $tmp->bis = $this->getDatamodulValue('bis');

    return $tmp;
  }

  
  public function getAllQuery(): \SelectQueryBuilder
  {
    return $this->getSelectQueryBuilder()
        ->select($this->select)
        ->from('alterskl', 'a')
        ->orderByAsc('a.kennz');
  }

  
  public function getAltersklasseByJahr($pJahr)
  {
    if ($pJahr < 1000 || $pJahr > 9999) {
      return $this->getNewObject();
    }
    $alter = date('Y') - $pJahr;
    $this->dboperation->clear();
    $this->dboperation->query('SELECT ' . $this->select
      . ' FROM alterskl a WHERE a.von <= ' . $alter
      . ' and a.bis >= ' . $alter
      . ' order by a.' . $this->orderby);

    return $this->getFirstRow();
  }

  
  public function getAltersklassen()
  {
    $this->dboperation->clear();
    $this->dboperation->query('SELECT ' . $this->select
      . ' FROM alterskl a order by a.' . $this->orderby);

    return $this->getAllRows();
  }

  
  public function getAltersklasseByKennz($pKennz)
  {
    $builder = $this->getAllQuery()
        ->and('a.kennz = :kennz:')
        ->paramInt('kennz', $pKennz);

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

    return $this->getFirstRow();
  }
}