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

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


class DBWorkHLZimmertyp extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'id, typ, bezeichnung, bettanz, preis, preiserm, gueltig_ab';
    $this->_dataModulFields = array('typ', 'bezeichnung', 'bettanz', 'preis', 'preiserm', 'id', 'gueltig_ab');
  }

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

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

  public function getSearchSQL($praeffix)
  {
    $result = '';
    if (isset($this->fromobject, $this->toobject)) {
      if (isset($this->fromobject->gueltig_ab) && !DateTimeOperations::isDateTimeEmptyOrDefault(trim($this->fromobject->gueltig_ab)) && $this->datetimeop->isValidDate($this->fromobject->gueltig_ab)) {
        $result .= ' AND (' . $praeffix . $this->dboperation->dbparser->isNull('gueltig_ab', $this->datetimeop->getFormatDate4Server(DEFAULTDATE)) . '>=' . $this->getSQLValue('gueltig_ab', $this->fromobject) . ')';
      }
      if (isset($this->toobject->gueltig_ab) && !DateTimeOperations::isDateTimeEmptyOrDefault(trim($this->toobject->gueltig_ab)) && $this->datetimeop->isValidDate($this->toobject->gueltig_ab)) {
        
        $gueltigab = $this->datetimeop->getFormatDateTime4Server(DateTimeOperations::getValidDateTimeString($this->toobject->getVarValue('gueltig_ab')));
        $result .= ' AND (' . $praeffix . $this->dboperation->dbparser->isNull('gueltig_ab', $this->datetimeop->getFormatDate4Server(DEFAULTDATE)) . '<=' . $gueltigab . ')';
      }
    }

    return $result;
  }

  
  public function getPricesValidAtDate($pDate)
  {
    $this->newSearch();
    $this->toobject->gueltig_ab = $pDate;
    $this->orderby = 'typ';
    $this->orderby2 = 'gueltig_ab';
    $this->orderbyasc2 = false;
    $zts = $this->getAll();
    $result = array();
    $currentTyp = '';
    foreach ($zts as $zt) {
      $ztUCTyp = \StringOperations::strtoupper($zt->typ);
      if ($currentTyp === $ztUCTyp) {
        continue;
      } else {
        $result[] = $zt;
        $currentTyp = $ztUCTyp;
      }
    }
    usort($result, function($a, $b) {
      $preisA = MathOperations::stringToFloat($a->preis);
      $preisB = MathOperations::stringToFloat($b->preis);
      if ($preisA == $preisB) {
        return 0;
      }

      return ($preisA < $preisB) ? 1 : -1;
    });

    return $result;
  }
}