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


class DataMenuAJAX extends DataMenu
{
  
  public $action;
  
  public $rootNodeName = 'webbasys';
  
  public $urlparameter;

  public function __construct($pUrlparameter)
  {
    $this->action = self::getAction($pUrlparameter);
    $this->urlparameter = $pUrlparameter;
  }

  public static function getAction($pUrlparameter)
  {
    $result = $pUrlparameter->ajaxAction;
    if ($result == null) {
      $result = GetOperations::getVarValue('ajaxAction', '');
    }

    return $result;
  }

  
  public static function getContentType($pUrlparameter)
  {
    
    switch (ucfirst(self::getAction($pUrlparameter))) {
      default:
        return 'Content-Type: text/xml';
      case 'GetKursSuggestions':
      case 'GetStrassenSuggestions':
      case 'GetGebuehrensumme':
      case 'GetMitarbeiter4Firma':
      case 'GetOrtByPlz':
      case 'GetValidatedZahlverfahren':
      case 'SetStammhoererSetting':
        return 'Content-Type: application/json';
    }
  }

  public function mainmenu()
  {
    
    
    if ($this->action != '') {
      $name = 'action' . $this->action;

      if (method_exists($this, $name)) {
        return $this->{$name}();
      }
    }

    return $this->actionGetContent();
  }

  
  public function content()
  {
    $content = $this->mainmenu();
    if (is_a($content, 'XMLNode')) {
      $header = '<?xml version="1.0" encoding="' . CodingOperations::getInternalEncoding() . '" ?>';
      $response = $header . $content->getXMLstring($content);
    } elseif (is_string($content)) {
      $response = $content;
    }

    return $response;
  }

  
  public function actionGetQuickWk()
  {
    
    $response = new XMLNode($this->rootNodeName);
    $response->addChild(new XMLNode('quickwarenkorb', WarenkorbAPI::getQuickView(), '', 'HTML'));

    return $response;
  }

  
  public function actionWKChange()
  {
    $xmlW = new XMLWork();
    $dbWWk = new DBWorkWarenkorbKurseWB();
    $entries = $dbWWk->getEntriesIDSerialized();
    $response = new XMLNode($this->rootNodeName);
    $wk = new XMLNode('warenkorb');

    foreach ($entries as $entrie) {
      $wk->addChild(new XMLNode('entrie', $entrie));
    }
    $response->addChild($wk);
    

    $statusmessager = StatusMessager::getInstance();
    $statusMessages = $statusmessager->getAllMessages();
    $response->addChild(new XMLNode('statusmessages'));
    foreach ($statusMessages as $statusMessage) {
      $xmlW->addDataModul2Node($statusMessage, $response);
    }

    return $response;
  }

  
  public function actionWkCount()
  {
    $dbwWk = new DBWorkWarenkorbKurseWB();
    $response = new XMLNode($this->rootNodeName);
    $response->addChild(new XMLNode('wkcount', $dbwWk->EntryCount()));

    return $response;
  }

  
  public function actionValidate()
  {
    $response = new XMLNode($this->rootNodeName);
    $validator = ValidierungWB::getInstance();
    $validationNode = new XMLNode('validation');
    $varnameMapping = ConstantOperations::getVarnamenMapping();
    $fields = PostOperations::getAll();
    if (isset($fields)) {
      foreach ($fields as $key => $value) {
        if (isset($varnameMapping[$key])) {
          $key = $varnameMapping[$key];
        }
        $field = new XMLNode('field', '', 'name="' . $key . '"');
        $valid = $validator->isValidVar($key, $value);
        if (is_string($valid)) {
          $field->addChild(new XMLNode('message', $valid));
          $valid = 0;
        }
        $field->addChild(new XMLNode('valid', $valid));
        $validationNode->addChild($field);
      }
    }
    $response->addChild($validationNode);

    return $response;
  }

  
  public function actionGetContent()
  {
    $kathauptapi = new KathauptAPI();
    $datamenu = $kathauptapi->getDatamenuByKathaupt($this->urlparameter->kathaupt, $this->urlparameter);
    $datamenu->setOnlyMainMenu(true);
    ob_start();
    echo $datamenu->content();
    $content = ob_get_contents();
    ob_end_clean();

    return $content;
  }

  
  public function actionGetOrtByPLZ()
  {
    $dbwStrassen = new DBWorkStrassen(1, true);
    $strassenObj = $dbwStrassen->getOneByPlz(PostOperations::getVarValue('plz'));

    return JsonOperations::encode($strassenObj);
  }

  
  public function actionGetSuggestions()
  {
    $sources = explode(',', $_REQUEST['sources']);

    $query = $_REQUEST['q'];
    $selectNode = new XMLNode('select');
    foreach ($sources as $source) {
      $source = explode(':', $source);
      $table = $source[0];
      $field = $source[1];

      if ($table == 'dozenten') {
        $dbw = new DBWorkDozentenWB();
        $dbw->newSearch();
        if ($dbw->fromobject->VarExist($field)) {
          $dbw->fromobject->setValue2Var($field, $query);
          $dozenten = $dbw->getDozenten4UebersichtLimit(0, 10, true, '', false, true);
          foreach ($dozenten as $dozent) {
            $selectNode->addChild(new XMLNode('option', $dozent->getVarValue($field)));
          }
        }
      }
      if ($table == 'kurse') {
        $dbwKS = new DBWorkKurseINetAktivFilterUebersicht();
        $dbwKS->newSearch();
        if ($dbwKS->fromobject->VarExist($field)) {
          $toolSettings = ToolSettingsAPI::getToolSettings(4);
          $dbwKS->fromobject->semester = $toolSettings->semlist;
          $dbwKS->fromobject->setValue2Var($field, $query);
          $dbwKS->toobject->semester = '';
          
          $kursids = $dbwKS->getKursebyCategoryLimit(-1, 0, 10);
          $kurse = $kursids;
          $values = array();
          foreach ($kurse as $kurs) {
            $values[] = $kurs->getVarValue($field);
          }
          $uniqueValues = array_unique($values);
          foreach ($uniqueValues as $val) {
            $selectNode->addChild(new XMLNode('option', $val));
          }
        }
      }
    }
    $response = new XMLNode($this->rootNodeName);
    $response->addChild($selectNode);

    return $response;
  }

  public function actionIsDubletteGebdat()
  {
    $response = new XMLNode($this->rootNodeName);

    $datamenu = new DataMenuZsaRegistrierung($this->urlparameter);

    if (!$datamenu->isInputForDublettenCheckOk()) {
      $response->addChild(new XMLNode('invalidInput', '1'));
    } else {
      try {
        $isDublette = $datamenu->isDublette();
        $response->addChild(new XMLNode('isDublette', $isDublette));
      } catch (AbgleichApiException $exception) {
        $response->addChild(new XMLNode('keineVerbindung', '1'));
      }
    }

    return $response;
  }

  
  public function actionGetKursSuggestions()
  {
    $query = RequestOperations::getVarValue('term');

    $suggester = new Kufer\Web\Classes\Search\KursSuggestions();
    $suggestions = $suggester->getSuggestions($query);

    return JsonOperations::encode($suggestions);
  }

  public function actionGetGutscheinGueltigkeitUndDetails()
  {
    $nummer = \PostOperations::getVarValue('nr');
    $code = \PostOperations::getVarValue('code');
    $gutscheinNode = \Kufer\Web\Classes\api\helpers\GutscheinEinloesenHelper::getGutscheinXMLNode($nummer, $code);
    try {
      if (\Kufer\Web\Classes\api\helpers\GutscheinEinloesenHelper::istGutscheinFormatValid(
        $nummer,
        $code
      )) {
        return \Kufer\Web\Classes\api\helpers\GutscheinEinloesenHelper::getGutscheinGueltigkeitVonBASDMZ($gutscheinNode);
      }
    } catch (\Exception $e) {
      Logger::logg('folgende Exception ist aufgetreten: ' . $e->getMessage() . ' [' . $e->getTraceAsString() . ']', 200);
    }

    return '';
  }

  public function actionGetStrassenSuggestions()
  {
    $strasse = RequestOperations::getVarValue('strasse');
    $plz = RequestOperations::getVarValue('plz');
    if ($plz == trim('')) {
      return '{}';
    }
    $strassen = DBWorkStrassen::getDefaultInstance()->getStrassenSuggestions($strasse, $plz);

    return JsonOperations::encode($strassen);
  }

  public function actionGetGebuehrensumme()
  {
    $warenkorbKontextLoader = new WarenkorbBerechnungsKontextLaderFromPost();
    $wkKontext = $warenkorbKontextLoader->load();
    $loader = new KursgebuehrBerechnungsKontextLaderFromPost();
    $kGebBerKontexte = $loader->load();
    $berechnung = GebuehrenBerechnungsFassade::setupGebuehrenBerechnung($kGebBerKontexte, $wkKontext);
    $sumErmaessigt = $berechnung->berechneGebuehrenSumme();

    $kGebBerKontexte = KursgebuehrBerechnungsKontextUtils::setNichtErmaessigtForAll($kGebBerKontexte);
    $berechnung->setBerechnungsKontexte($kGebBerKontexte, $wkKontext);
    $sumNichtErmaessigt = $berechnung->berechneGebuehrenSumme();

    $loaderImmerErmaessigt = new KursgebuehrBerechnungsKontextLaderFromPost(array(new ZahlplanValidator(), new ErmaessigungsValidatorWeitereTn()));
    $kGebBerKontexteImmerErmaessigt = $loaderImmerErmaessigt->load();
    $berechnungImmerErmaessigt = GebuehrenBerechnungsFassade::setupGebuehrenBerechnung($kGebBerKontexteImmerErmaessigt, $wkKontext);
    $sumImmerErmaessigt = $berechnungImmerErmaessigt->berechneGebuehrenSumme();

    $result = new stdClass();
    $result->sum = $sumErmaessigt;
    $result->sumNichtErmaessigt = $sumNichtErmaessigt;
    $result->sumImmerErmaessigt = $sumImmerErmaessigt;

    return JsonOperations::encode($result);
  }

  public function actionGetMitarbeiter4Firma()
  {
    $firmennr = SessionOperations::getCurrentStammhoererTnr();
    if ($firmennr == '') {
      return JsonOperations::encode(array());
    }

    $dbworkbeziehung = new DBWorkBeziehung();
    $tnrs = $dbworkbeziehung->getMitarbeiterTnrZuFirma($firmennr);
    $dbworkteiln = new DBWorkTeilnehmer();
    $teilnehmerary = $dbworkteiln->getTeilnehmByIdArray($tnrs);

    $result = array();
    foreach ($teilnehmerary as $einzelnerTn) {
      $teilnehmerPflicht = $einzelnerTn->copyAsTeilnehmerPflicht();
      $teilnehmerPflicht->gleicheMehrfacheInfosAb();
      $result[] = $teilnehmerPflicht;
    }

    return JsonOperations::encode($result);
  }

  public function actionSetStammhoererSetting()
  {
    $key = RequestOperations::getVarValue('key');
    
    $value = RequestOperations::getVarValue('value') ? 'W' : 'F';
    DBWorkWBLoginsSettings::getDefaultInstance()->setSetting($key, $value);

    return '';
  }

  public function actionGetValidatedZahlverfahren()
  {
    $anmart = PostOperations::getVarValue('anmart');

    if ($anmart == ANMELDEART_URL_FIRMAHOTEL){
      ePaymentApi::$currentAnmeldeart = ANMELDEART_URL_FIRMAHOTEL;
    } elseif ($anmart == ANMELDEART_URL_WEBSHOP) {
      ePaymentApi::$currentAnmeldeart = ANMELDEART_URL_WEBSHOP;
    }
    $zahlartValidator = new ZahlartValidator();
    $kursgebuehren = MathOperations::stringToFloat(ePaymentApi::getEPayAmount());
    
    return JsonOperations::encode($zahlartValidator::getZahlverfahrenForSichten($kursgebuehren));
  }
}