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

namespace Kufer\Web\KuferTools\Basis\Kursdetails\Detailsreiter\Termine\TerminDialog;

use Kufer\Web\KuferTools\Firma\KursUebersicht\Detailsreiter\Termine\TerminStornierenDialog\TerminStornierenUtils;
use Kufer\Web\KuferTools\Utils\StatusMessages\PlainStatusMessage;
use Kufer\Mail\Address\EMailAddress;
use Kufer\Mail\Sender\IEMailSender;
use Kufer\Mail\EMail\IEMail;
use Kufer\Mail\Sender\Result\EMailSentResult;
use Kufer\Web\KuferTools\Utils\StatusMessages\StatusMessageContainer;

abstract class TerminAbsendenEMailUseCase extends \Kufer\Web\KuferTools\Ausgaben\SammelEMail\AnTeilnehmer\SendSammelEMailUseCase
{
  
  protected $statusMessageContainer;

  public function __construct($request, $response)
  {
    parent::__construct($request, $response);
    $this->statusMessageContainer = StatusMessageContainer::getSharedInstance();
  }

  protected function createEMail(): IEMail
  {
    return $this->createPresenter($this->response);
  }

  public function action()
  {
    $response = $this->getResponseForEMail();

    $this->request->belegungNummern = $this->getKursTeilnehmerBelegungsIds(
      $this->request->knr
    );

    $response = parent::action();

    if (!empty($response->errorMessage)) {
      $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj($response->errorMessage));
    }

    return $response;
  }

  abstract protected function createPresenter($response): IEMail;

  
  protected function shouldSendMail2Firmenservice(): bool
  {
    return true;
  }

  protected function sendEMail(IEMailSender $sender, IEMail $mail): EMailSentResult
  {
    $result = parent::sendEMail($sender, $mail);
    foreach ($result->getUniqueSuccessMessages() as $msg) {
      $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getSuccessMessageObj($msg));
    }
    foreach ($result->getUniqueWarningMessages() as $msg) {
      $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getWarningMessageObj($msg));
    }
    foreach ($result->getUniqueErrorMessages() as $msg) {
      $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj($msg));
    }

    if (\DBWorkBASysSettings::isInlinguaMuenchen()) {
      $firmenToolSettings = \ToolSettingsAPI::getToolSettings(\ToolsAPI::TOOL_KURSUEBERSICHT_FA);
      $emailPlanung = $firmenToolSettings->terminStonierenEMailPlanung;
      if ($emailPlanung !== '') {
        $resultEmailKursplanung = $sender->send($mail, $this->getUser(), array(new EMailAddress('Kursplanung', $emailPlanung)), 'Kursplanung');
        $result = $result->merge($resultEmailKursplanung);
        $recipient = \ArrayOperations::firstValue($resultEmailKursplanung->getRecipients());
        if ($resultEmailKursplanung->hasError()) {
          $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj($recipient->getReadableMessage()));
        } else {
          $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getSuccessMessageObj($recipient->getReadableMessage()));
        }
      }

      if ($this->shouldSendMail2Firmenservice()) {
        $emailFirmendienst = $firmenToolSettings->terminStonierenEMailFirmendienst;
        if ($emailFirmendienst !== '') {
          $resultEmailFirmenservice = $sender->send($mail, $this->getUser(), array(new EMailAddress('Firmendienst', $emailFirmendienst)), 'Firmendienst');
          $result = $result->merge($resultEmailFirmenservice);

          $recipient = \ArrayOperations::firstValue($resultEmailFirmenservice->getRecipients());
          if ($resultEmailFirmenservice->hasError()) {
            $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj($recipient->getReadableMessage()));
          } else {
            $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getSuccessMessageObj($recipient->getReadableMessage()));
          }
        }
      }
    }

    $dozenten = $this->getDozenten();
    if (count($dozenten) > 0) {
      $resultEmailDozent = $sender->send($mail, $this->getUser(), $dozenten, 'DozentInnen');
      $result = $result->merge($resultEmailDozent);
      foreach ($resultEmailDozent->getUniqueSuccessMessages() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getSuccessMessageObj($msg));
      }
      foreach ($resultEmailDozent->getUniqueWarningMessages() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getWarningMessageObj($msg));
      }
      foreach ($resultEmailDozent->getUniqueErrorMessages() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj($msg));
      }
    }

    $user = $this->getUser();
    if ($user->tnr > 0) {
      $firmenTnr = TerminStornierenUtils::getTnrFirma($user, $this->getToolId(), $this->request->knr);
      $dbwAnsprechpartner = new \DBWorkAdrPers();
      $ansprechpartner = $dbwAnsprechpartner->getAdrPersByTnNr($firmenTnr);
      $resultEmailAnsprechpartner = $sender->send($mail, $user, $ansprechpartner, 'Ansprechpartner');
      $result = $result->merge($resultEmailAnsprechpartner);
      foreach ($resultEmailAnsprechpartner->getSuccessMessagesWithNames() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getSuccessMessageObj($msg));
      }
      foreach ($resultEmailAnsprechpartner->getWarningMessagesWithNames() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getWarningMessageObj($msg));
      }
      foreach ($resultEmailAnsprechpartner->getErrorMessagesWithNames() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj($msg));
      }
    }

    return $result;
  }

  abstract protected function getDozenten(): array;

  
  protected function getTeilnehmer(): array
  {
    
    $dbwTeilnehmer = new \DBWorkTeilnehmer();
    $result = $dbwTeilnehmer->getTeilnehmerByBelegAry($this->sendPreparer->getBelegungenIds($this->request->knr, $this->request->belegungNummern, $this->toolSettings->tnstatus));

    $user = $this->getUser();

    return \array_filter($result, function($kontakt) use ($user) {
      if (!($kontakt instanceof \Teilnehmer)) {
        return true;
      }

      return $kontakt->id != $user->tnr;
    });
  }

  
  protected function getKursTeilnehmerBelegungsIds(string $knr): array
  {
    $dbwBelegungen = new \DBWorkBelegung();

    return $dbwBelegungen->getBelegungenIdsbyKursNR($knr);
  }

  public function getResponseForEMail()
  {
    return $this->response;
  }

  protected function doSendKopieAnAbsender(): bool
  {
    return true;
  }

  protected function getSenderPerson(): \Personn
  {
    return \SessionOperations::getCurrentWebToolsTeilnehmer();
  }

  protected function getSenderPosition(): string
  {
    return 'Teilnehmer';
  }
}