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

namespace Kufer\KuferTools\Basis\Kursdetails\DetailsReiter\Termine\TerminDialog;

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

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

  
  public function __construct($request, $response)
  {
    parent::__construct($request, $response ?? new TerminAbsendenEMailRequest());
    $this->statusMessageContainer = \Kufer\KuferTools\Utils\StatusMessages\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(\Kufer\KuferTools\Utils\StatusMessages\StatusMessage::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(StatusMessage::getSuccessMessageObj($msg));
    }
    foreach ($result->getUniqueWarningMessages() as $msg) {
      $this->statusMessageContainer->addStatusMessageObj(StatusMessage::getWarningMessageObj($msg));
    }
    foreach ($result->getUniqueErrorMessages() as $msg) {
      $this->statusMessageContainer->addStatusMessageObj(StatusMessage::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(StatusMessage::getErrorMessageObj($recipient->getReadableMessage()));
        } else {
          $this->statusMessageContainer->addStatusMessageObj(StatusMessage::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(StatusMessage::getErrorMessageObj($recipient->getReadableMessage()));
          } else {
            $this->statusMessageContainer->addStatusMessageObj(StatusMessage::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(StatusMessage::getSuccessMessageObj($msg));
      }
      foreach ($resultEmailDozent->getUniqueWarningMessages() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(StatusMessage::getWarningMessageObj($msg));
      }
      foreach ($resultEmailDozent->getUniqueErrorMessages() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(StatusMessage::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(StatusMessage::getSuccessMessageObj($msg));
      }
      foreach ($resultEmailAnsprechpartner->getWarningMessagesWithNames() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(StatusMessage::getWarningMessageObj($msg));
      }
      foreach ($resultEmailAnsprechpartner->getErrorMessagesWithNames() as $msg) {
        $this->statusMessageContainer->addStatusMessageObj(StatusMessage::getErrorMessageObj($msg));
      }
    }

    return $result;
  }

  abstract protected function getDozenten(): array;

  protected function getTeilnehmer()
  {
    
    $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($knr): array
  {
    $dbwBelegungen = new \DBWorkBelegung();

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

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

  protected function doSendKopieAnAbsender()
  {
    return true;
  }

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

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

class TerminAbsendenEMailRequest extends \Kufer\KuferTools\Ausgaben\SammelEMail\AnTeilnehmer\SendSammelEMailRequest
{
  
  public $knr;

  
  public $kurstag;
}

class TerminAbsendenEMailResponse extends \Kufer\KuferTools\Ausgaben\SammelEMail\AnTeilnehmer\SendSammelEMailResponse
{
  
  public $knr;

  
  public $kurstag;

  
  public $successMessage;
}