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

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


class DBWorkArtikelPorto extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'id, porto, von, bis, typ, prio, region';
    $this->orderby = 'prio';
    $this->orderbyasc = true;
    $this->_dataModulFields = array('typ', 'von', 'bis', 'prio', 'region', 'porto', 'id');
  }

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

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

  public function getSearchSQL($pPrefix)
  {
    $prefix = $this->stringop->ensureTrailing($pPrefix, '.');
    $result = '';

    if (isset($this->fromobject, $this->toobject)) {
      if (isset($this->fromobject->region) && $this->fromobject->region !== '') {
        $result .= ' AND ' . $this->dboperation->dbparser->isNull($prefix . 'region', 0) . ' = ' . $this->dboperation->getInt4Sql($this->fromobject->region);
      }
    }

    return $result;
  }

  
  public function getPorto($pGewicht, $pSumme, $pRegion)
  {
    $gewicht = $this->dboperation->getInt4Sql(ceil($pGewicht));
    $summe = (float)$pSumme; 
    
    
    $summe = str_replace(',', '.', $summe);
    $region = $this->dboperation->getInt4Sql($pRegion);
    $sql = "SELECT porto from artikel_porto where (($gewicht >= von and ($gewicht <= bis or 0 = bis) and typ = 'G') "
           . "or ($summe >= von and ($summe <= bis or 0 = bis) and typ = 'P')) and region = $region order by prio asc";
    $this->dboperation->clear();
    $this->dboperation->query($sql);
    if ($this->dboperation->rowcount() === 0) {
      return '0,00';
    } else {
      $this->dboperation->selectrow(0);
      $porto = $this->dboperation->fieldbyname('porto');

      return MathOperations::floatToString($porto);
    }
  }

  
  public function getPauschalPorto($pRegion)
  {
    $region = $this->dboperation->getInt4Sql($pRegion);
    $queryBuilder = $this->getSelectQueryBuilder();
    $queryBuilder->select($this->select)
            ->from($this->getTableName())
            ->where('region = :region: and typ = :typ:')
            ->paramInt('region', $region)
            ->paramString('typ', ConstantOperations::getVersandTypPauschal());

    return $this->queryGetFirstRow($queryBuilder->getSQL());
  }
}