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

namespace Kufer\KuferTools\Teilnehmer\Punkte\HandleCheckCode4Ajax;

class HandleCheckCode4AjaxUseCase extends \Kufer\KuferTools\Basis\UseCase\ToolUseCase
{
  public function __construct($request)
  {
    parent::__construct($request, new HandleCheckCode4AjaxResponse());
  }

  public static function getToolId()
  {
    return \ToolsAPI::TOOL_PUNKTE_TN;
  }

  public static function getToolSectionId()
  {
    return 357;
  }

  public function action()
  {
    $this->checkCode();

    return $this->response;
  }

  protected function checkCode()
  {
    $user = $this->getUser();
    $this->response->angefragteKursnummer = $this->request->knr;
    $this->response->belegId = $this->request->belegId;
    $this->response->code = $this->request->code;
    $this->response->status = 'nok';

    if ($this->response->angefragteKursnummer == '' && $this->response->belegId != '' && $this->response->belegId != 'undefined') {
      $dbwBelegung = \DBWorkBelegung::getDefaultInstance();
      $knrs = $dbwBelegung->getKursNrFromBelegungNrAry(array($this->response->belegId));
      $this->response->angefragteKursnummer = $knrs[0];
    }

    if (\SessionOperations::isDmzBetrieb()) {
      try {
        $dmzResult = \BelegungAPI::codeStatus($this->response->code);
        if (\StringOperations::strpos($dmzResult->reason, '{-}') !== false) { 
          $this->response->status = 'ok';
          $answer = explode('{-}', $dmzResult->reason);
          
          
          $this->response->knr = \StringOperations::utf8_decode($answer[0]);
          $this->response->ktitel = \StringOperations::utf8_decode($answer[1]);
          if ($this->response->belegId == '') {
            $dbwBelegung = \DBWorkBelegung::getDefaultInstance();
            $belegungen = $dbwBelegung->getBelegungenbyKursTeilnehmerNR($this->response->knr, $user->tnr);
            if (count($belegungen) > 0) {
              $this->response->belegId = $belegungen[0]->id;
            }
          }
        }
      } catch (\Exception $ex) {
        \Logger::logg('HandleCheckCode4Ajax: ' . $ex->getMessage(), 200);
        if ($ex instanceof \AbgleichApiException && $ex->errorType == -1) {
          $this->response->technischerFehler = true;
        }
        
      }
    }
  }
}

class HandleCheckCode4AjaxRequest
{
  public $code;
  public $knr;
  public $belegId;
}

class HandleCheckCode4AjaxResponse extends \Kufer\KuferTools\Basis\UseCase\ToolResponse
{
  public $knr = '';
  public $ktitel = '';
  public $status;
  public $angefragteKursnummer;
  public $belegId;
  public $code;
  public $technischerFehler = false;
}