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


class DBWorkHLGemeinde extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'id, gemeinde, stadtteil, bezirk, bundesland';
    $this->_dataModulFields = array('id', 'gemeinde', 'stadtteil', 'bezirk', 'bundesland');
    $this->orderby = 'gemeinde';
  }

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

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

  public function getGemeinden()
  {
    $sql = 'SELECT DISTINCT gemeinde FROM ' . $this->getTableName() . ' WHERE NOT ' . $this->dboperation->dbparser->emptyStringComparison('gemeinde') . ' ';
    if ($this->orderby != '') {
      $sql .= $this->getCompleteOrderByDefault($this->orderby);
    }
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    return $this->getAllRows();
  }

  public function getBezirke()
  {
    $query = $this->getSelectQueryBuilder();
    $query->select('DISTINCT bezirk')
          ->from($this->getTableName())
          ->where('NOT ' . $this->dboperation->dbparser->isStringEmptyOrNull('bezirk'));

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

    $bezirke = array();
    $rowcount = $this->dboperation->rowcount();
    for ($i = 0; $i < $rowcount; $i++) {
      $this->dboperation->selectrow($i);
      $bezirke[] = $this->dboperation->fieldbyname('bezirk');
    }

    return $bezirke;
  }

  public function getBezirkemitKursen(): array
  {
    $query = $this->getSelectQueryBuilder();
    $dbworkkurse = new DBWorkKurseINetAktiv();
    $dbworkkurse->newSearch();
    $query->select('DISTINCT bezirk')
      ->from($this->getTableName())
      ->where('NOT ' . $this->dboperation->dbparser->isStringEmptyOrNull('bezirk'))
      ->and('bezirk IN (SELECT DISTINCT ko.bezirk FROM kursorte ko WHERE ko.bez IN (SELECT k.ort FROM kurse k WHERE 1=1 ' . $dbworkkurse->getSearchSQL('k.') . ') )');

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

    $bezirke = array();
    $rowcount = $this->dboperation->rowcount();
    for ($i = 0; $i < $rowcount; $i++) {
      $this->dboperation->selectrow($i);
      $bezirke[] = $this->dboperation->fieldbyname('bezirk');
    }

    return $bezirke;
  }

  public function wandleBezirkeInDatamoduleUm($bezirke)
  {
    return array_map(function($bezirk) {
      $datamodul = new class() extends Datamodul {
        public $bezirk;
      };

      $datamodul->bezirk = $bezirk;

      return $datamodul;
    }, $bezirke);
  }
}