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

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


class DBWorkWebGeodbDist extends DBWorkGenerated
{
  public function __construct($pDBTyp = 1, $pNewInstance = false)
  {
    parent::__construct($pDBTyp, $pNewInstance);
    $this->select = 'plz1, plz2, distance';
    $this->_dataModulFields = array('plz1', 'plz2', 'distance');
  }

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

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

  
  public function getNeighbourPlzWithinRadius($pCenterPlz, $pRadius)
  {
    $cleanPlz = $this->dboperation->getString4Sql($pCenterPlz);
    if (CleanOperations::isFloatMitPunkt($pRadius)) {
      $cleanRadius = CleanOperations::cleanFloatMitPunkt($pRadius);
    } elseif (CleanOperations::isFloatMitKomma($pRadius)) {
      $cleanRadius = MathOperations::stringToFloat(CleanOperations::cleanFloatMitKomma($pRadius));
    } else {
      throw new InvalidArgumentException('$pRadius (' . $pRadius . ') ist not a valid float');
    }
    $sql = 'select ' . $this->select . ' from ' . $this->getTableName() . " where (plz1 = '$cleanPlz' or plz2 = '$cleanPlz') and distance < $cleanRadius";
    $this->dboperation->clear();
    $this->dboperation->query($sql);

    $result = array();
    $numrows = $this->dboperation->rowcount();
    for ($i = 0; $i < $numrows; $i++) {
      $this->dboperation->selectrow($i);
      $plz1 = $this->dboperation->fieldbyname('plz1');
      
      if ($plz1 === $cleanPlz) {
        $result[] = $this->dboperation->fieldbyname('plz2');
      } else {
        $result[] = $plz1;
      }
    }

    return array_unique($result);
  }
}