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

include_once_ex('extern/composer/vendor/autoload.php');

class SoapNusoap
{
  protected $wsdl = '';

  protected $useCurl = false;
  protected $proxyHost = '';
  protected $proxyPort = '';
  protected $proxyUsername = '';
  protected $proxyPassword = '';

  protected $username = '';
  protected $password = '';

  
  protected $useExceptions = true;

  public function __construct(string $wsdl)
  {
    $this->wsdl = $wsdl;
  }

  protected function getWsdl()
  {
    return $this->wsdl;
  }

  
  public function setProxy($pUseCurl, $pProxyConfig)
  {
    $this->useCurl = $pUseCurl;
    $this->proxyHost = $pProxyConfig->getServer();
    $this->proxyPort = $pProxyConfig->getPort();
    $this->proxyUsername = $pProxyConfig->getUser();
    $this->proxyPassword = $pProxyConfig->getPassword();
  }

  public function setCredentials($username, $password): void
  {
    $this->username = $username;
    $this->password = $password;
  }

  protected function pathToWsdlFolder()
  {
    return BASEDIR . 'classes' . DIRECTORY_SEPARATOR . 'soap' . DIRECTORY_SEPARATOR . 'wsdl' . DIRECTORY_SEPARATOR;
  }

  protected function getSoapClient()
  {
    $client = new nusoap_client(
      $this->getWsdl(),
      'wsdl',
      $this->proxyHost,
      $this->proxyPort,
      $this->proxyUsername,
      $this->proxyPassword
    );
    $client->setUseCURL($this->useCurl);

    if ($this->username != null && $this->password != null) {
      $client->setCredentials($this->username, $this->password);
    }

    $err = $client->getError();
    if ($err) {
      $message = 'Nusoap: Fehler beim Erzeugen eines Nusoap-Klienten mit nusoap_client: ' . $err;
      Logger::logg($message, 350);
      if ($this->useExceptions) {
        throw new Exception($message);
      }
    }

    return $client;
  }

  public function soapCall($operation, $params = array())
  {
    $client = $this->getSoapClient();
    $result = $client->call($operation, $params);
    

    if ($err = $client->getError()) {
      Logger::logg('Soap-Call Error:' . $client->getError(), 351);
      if ($this->useExceptions) {
        throw new Exception($err);
      }
    }

    return $result;
  }
}