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

class EPayNotifyHandlerDirekt extends EPayNotifyHandler
{
  public function verarbeiteNotify(int $payonline, EPayInfo $epayInfo, EmailXML $emailxml, array $emailxmlKurse) {
    $this->dbwWes->clearOldEntries();
    $tid = $epayInfo->tid;
    $stateChange = $this->hasPaymentStateChanged($epayInfo);
    if($stateChange == self::STATE_SAME) {
      return true;
    }

    $success = $this->uebermittlePaymentState($payonline, $epayInfo, $emailxml, $emailxmlKurse);
    if(!$success && $stateChange == self::STATE_NEW) {
      EpayLogger::logg("Neues E-Pay-Notify konnte nicht übermittelt werden.", 600);
      return false;
    } elseif(!$success && $stateChange == self::STATE_CHANGED) {
      EpayLogger::logg("E-Pay-Notify konnte nicht übermittelt werden.", 600);
      
      
      return false;
    } 
    return true;

  }

  protected function hasPaymentStateChanged(EPayInfo $epayInfo) {
    $notifyInDb = DBWorkEpayNotify::getDefaultInstance()->getEpayNotifyByMtId($epayInfo->tidMerchant);
    if($notifyInDb->isEmpty()) {
      EpayLogger::logg('Neuer E-Pay-Status muss angelegt werden', 50);
      return self::STATE_NEW;
    }
    
    if(strtolower($notifyInDb->epay_state) == strtolower($epayInfo->paymentState)) {
      EpayLogger::logg('E-Pay-Status muss nicht verändert werden', 50);
      return self::STATE_SAME;
    } else {
      EpayLogger::logg('E-Pay-Status muss verändert werden', 50);
      return self::STATE_CHANGED;
    }
  }
}