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

namespace Kufer\Web\KuferTools\Dozent\Dokumente\DokumenteUpload;

use Kufer\Mail\Sender\EMailSenderFactory;
use Kufer\Mail\Sender\Result\EMailSentResult;
use Kufer\Web\Classes\Mail\Sender\Settings\RecipientEinrichtung\EMailEinrichtungRecipientToolsDozentSettings;

class DokumenteUploadUseCase extends \Kufer\Web\KuferTools\Basis\Dokumente\DokumenteUpload\DokumenteUploadUseCase
{
  public static function getToolId()
  {
    return \ToolsAPI::TOOL_DOKUMENTE_DOZ;
  }

  public static function getToolSectionId()
  {
    return 745;
  }

  protected function isUploadAllowed(): bool
  {
    return $this->isRechtAllowed('744.0.1');
  }

  protected function shouldSendInfoAnEinrichtung(): bool
  {
    return $this->toolSettings->sendInfoMailAnEinrichtung
      || $this->toolSettings->sendInfoMailAnPlanendMa
      || $this->toolSettings->sendInfoMailAnVerwaltendMa;
  }

  protected function shouldSendUploadInfoMailMitAnhang(): bool
  {
    return $this->toolSettings->anhangBeiInfoMailAnEinrichtung;
  }

  protected function getDatDocObj()
  {
    $datDoc = parent::getDatDocObj();
    $user = $this->getUser();
    $datDoc->nr = $user->dnr;
    $datDoc->freigabe_doz_tools = true;

    return $datDoc;
  }

  protected function createInfoMailAnEinrichtungView($viewModel): \Kufer\Web\KuferTools\Basis\Dokumente\DokumenteUpload\InfoMailAnEinrichtungView
  {
    return new InfoMailAnEinrichtungView($viewModel);
  }

  protected function getEMailAddressFromToolSettings(): ?string
  {
    $email = $this->toolSettings->emailAnEinrichtungCustomForUpload ?? '';
    if (trim($email) === '') {
      return null;
    }

    return $email;
  }

  protected function sendInfoMailAnEinrichtung(): EMailSentResult
  {
    if (!in_array('Dozent', \SessionOperations::getCurrentWebToolsUserUserGroups(), true)) {
      return parent::sendInfoMailAnEinrichtung();
    }

    $dozent = \SessionOperations::getCurrentWebToolsDozent();

    $sender = EMailSenderFactory::createForToolsWithCustomAddress($this->getEMailAddressFromToolSettings());
    $recipientSettings = new EMailEinrichtungRecipientToolsDozentSettings($dozent);
    $recipientSettings
      ->setSettingMailToPlanendenMitarbeiter($this->toolSettings->sendInfoMailAnPlanendMa)
      ->setSettingMailToVerwaltendenMitarbeiter($this->toolSettings->sendInfoMailAnVerwaltendMa)
      ->setSettingMailToEinrichtung($this->toolSettings->sendInfoMailAnEinrichtung ? true
        : ($this->toolSettings->sendInfoMailAnPlanendMa || $this->toolSettings->sendInfoMailAnVerwaltendMa ? null : false))
      ->setSettingsVhsEMail($this->getEMailAddressFromToolSettings());

    return $sender->sendFromPersonToEinrichtung(
      $this->createEMail(),
      \SessionOperations::getCurrentWebToolsPerson(),
      $recipientSettings
    );
  }

  protected function getDbTypAndId(): array
  {
    return array('D', $this->getUser()->getDnrIdentifier());
  }
}