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

namespace Kufer\KuferTools\Basis\DozentenInfo\SammelEMail;

use Kufer\Mail\Sender\Result\EMailSentStatusCode;

abstract class SendSammelEMailUseCase extends \Kufer\KuferTools\Basis\UseCase\ToolUseCase
{
  public const EMAILVERSAND_SUCCESS = 0;
  public const EMAILVERSAND_FEHLER_BEIM_VERSENDEN = 1;
  public const EMAILVERSAND_UNGUELTIGE_ODER_LEERE_EMAIL = 2;
  public const EMAILVERSAND_STANDBY = 3;

  public function __construct($request, $response = null)
  {
    parent::__construct($request, $response ?? new SendSammelEMailResponse());
  }

  public function hasAccess($pToolSectionId = null)
  {
    
    
    if (!parent::hasAccess()) {
      return false;
    }

    
    
    if (!$this->request->isXsrfOk && !$this->request->isRefresh) {
      return false;
    }

    return true;
  }

  
  public function getDozenten(): array
  {
    
    

    
    if (is_array($this->request->dozNummern) && count($this->request->dozNummern) > 0 && count($this->request->dozNummern) == 1) {
      
      $dbwDoz = new \DBWorkDozenten();

      return $dbwDoz->getDozentenByIDArray($this->request->dozNummern);
    } else {
      \Logger::logg(' Fehler im EmailSender: DozentenNummern nicht besetzt. ', 41);

      throw new \Exception('Fehler beim Versenden der EMail an die Dozenten');
    }
  }

  public function setStatusFromMailSentResult(\Kufer\Mail\Sender\Result\EMailSentResult $sentResult)
  {
    foreach ($sentResult->getRecipients() as $recipient) {
      if (!($recipient->getRecipient() instanceof \Dozent)) {
        continue;
      }

      switch ($recipient->getStatusCode()) {
        case EMailSentStatusCode::SUCCESSFULL:
        case EMailSentStatusCode::WARNING_EMAIL_SENDER_NOT_FOUND:
          $status = self::EMAILVERSAND_SUCCESS;
          break;
        case EMailSentStatusCode::FAILURE_EMAIL_NOT_FOUND:
          $status = self::EMAILVERSAND_UNGUELTIGE_ODER_LEERE_EMAIL;
          break;
        default:
          $status = self::EMAILVERSAND_FEHLER_BEIM_VERSENDEN;
          break;
      }

      $this->response->sendMailStatus[$recipient->getRecipient()->id] = $status;
    }
  }

  protected function hasUploadError(): bool
  {
    return false;
  }

  public function action()
  {
    $errorMessage = '';
    $sendToDozenten = array();
    try {
      
      $sendToDozenten = $this->getDozenten();

      
      if ($this->hasUploadError()) {
        $this->response->uploadFailed = true;
      }
      
      elseif ($this->request->isRefresh) {
        $this->response->doppeltSenden = true;
      }
      
      else {
        $sentResult = $this->sendMail($this->createEMail(), $sendToDozenten);
        $this->setStatusFromMailSentResult($sentResult);
      }
    } catch (\Exception $e) {
      $errorMessage = $e->getMessage();
      \Logger::logg(' Fehler beim Versenden der Sammel E-Mail. ' . $errorMessage, 41);
    }

    return $this->getResponse($errorMessage, $sendToDozenten);
  }

  
  protected function getResponse($pErrorMessage, $dozenten)
  {
    $this->handleResponseStrategies();
    $this->response->errorMessage = $pErrorMessage;
    $this->response->dozenten = $dozenten;
    $this->response->backLink = \Kufer\KuferTools\Utils\Referrer::getReferrerFromSession($this->getToolId(), 'index.php?tool_id=' . $this->getToolId(), 'sammel_email');
    $this->response->backButtonLabel = \Kufer\KuferTools\Utils\Referrer::getReferrerLabelFromSession($this->getToolId(), 'Zurück', 'sammel_email');

    return $this->response;
  }

  protected function getResponseStrategies()
  {
    return array(
        new \Kufer\KuferTools\Utils\ResponseStrategies\ResponseMitRahmen($this)
    );
  }

  protected function createEMail(): \Kufer\Mail\EMail\IEMail
  {
    return new \Kufer\Mail\EMail\EMailPlaintext($this->request->emailBetreff, $this->request->emailBody);
  }

  abstract protected function sendMail(\Kufer\Mail\EMail\IEMail $email, array $dozenten): \Kufer\Mail\Sender\Result\EMailSentResult;
}

class SendSammelEMailRequest
{
  public $emailBetreff;
  public $emailBody;
  public $isRefresh;
  public $isXsrfOk;
  public $dozNummern = array();
  public $anhangTnList;
}

class SendSammelEMailResponse extends \Kufer\KuferTools\Basis\UseCase\ToolResponse
{
  public $dozenten;
  public $user;
  public $menuBar;
  public $errorMessage;
  public $sendMailStatus = array();
  public $uploadFailed = false;
  public $doppeltSenden = false;

  public $backLink;
  public $backButtonLabel;
}