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

namespace Kufer\Web\KuferTools\Dozent\KursUebersicht\Detailsreiter\Honorar\BurghausenVhs\HonorarPdf;

use Kufer\Mail\Attachment\EMailAttachmentPDF;
use Kufer\Mail\EMail\EMailHTML;
use Kufer\Mail\Sender\EMailSenderFactory;
use Kufer\Web\Classes\Mail\Sender\Settings\RecipientEinrichtung\EMailEinrichtungRecipientToolsKursSettings;
use Kufer\Web\KuferTools\Dozent\Anwesenheiten\Utils\KurstageUtils;
use Kufer\Web\KuferTools\Utils\StatusMessages\PlainStatusMessage;
use Kufer\Web\KuferTools\Utils\StatusMessages\StatusMessageContainer;

class HonorarAbrechnungAbsendenUseCase extends \Kufer\Web\KuferTools\Basis\UseCase\EinzelKursUseCase
{
  public function __construct($request)
  {
    parent::__construct($request, new HonorarAbrechnungDialogResponse());
  }

  public static function getToolId()
  {
    return \ToolsAPI::TOOL_KURSUEBERSICHT_DOZ;
  }

  public static function getToolSectionId()
  {
    return 320;
  }

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

    if (!\DBWorkBASysSettings::isBurghausenVhs()) {
      return false;
    }

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

    $kurs = $this->getKurs($this->getKursId());
    $kurstage = \DBWorkKurseTage::getDefaultInstance()->getKurstageByKursNrAndDozentNr(
      $this->getKursId(),
      $this->getUser()->getDnrIdentifier(),
      array('A', 'X')
    );

    $today = \DateTimeOperations::getDateNow();
    if (!KurstageUtils::areAllKurstageBefore($kurstage, $today)) {
      return false;
    }

    if (!$this->response->redirect) {
      if (!KurstageUtils::hasFilledAllAnwesenheiten($kurs, $kurstage, false)) {
        return false;
      }
    }

    return true;
  }

  public function action()
  {
    $this->handleResponseStrategies();

    $dozent = \SessionOperations::getCurrentWebToolsDozent();
    $dbwDozKurs = new \DBWorkDozentenHonorar();
    $dozKurs = $dbwDozKurs->getHonorarbyKNRDozentNR($this->getKursId(), $dozent->id);

    $this->response->dozKurs = $dozKurs;
    $this->response->bestaetigungChecked = $this->request->bestaetigungChecked;

    if (!$this->response->bestaetigungChecked) {
      $this->response->error = true;
      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(
        PlainStatusMessage::getErrorMessageObj('Zustimmung zur ordnungsgemäßen Durchführung und Richtigkeit der Angaben fehlt')
      );
    }

    $iban = trim($this->request->iban);
    $bic = trim($this->request->bic);
    if ($bic === '') {
      $bic = \BankDatenOperations::getBicFromIban($iban);
    }
    $bankbez = $this->request->bankbez;
    if (trim($bankbez) === '') {
      $bankbez = \BankDatenOperations::getBankbezeichnungAnhandBic($bic);
    }

    $this->response->iban = $iban;
    $this->response->bic = $bic;
    $this->response->bankbez = $bankbez;
    $this->response->kontoinhaber = $this->request->kontoinhaber;

    $oldIban = $dozent->iban;
    $oldBic = $dozent->bic;
    if (trim($this->response->kontoinhaber) === ''
      || (($oldIban !== $this->response->iban || $oldBic !== $this->response->bic)
        && !\ValidationAPI::areIBANAndBicValid($this->response->iban, $this->response->bic))) {
      $this->response->error = true;
      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
        'Die Bankdaten sind nicht korrekt'
      ));
    }

    if ($this->request->isRefresh || !$this->request->isXsrfOk) {
      $this->response->error = true;
      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(
        PlainStatusMessage::getErrorMessageObj('Formular erneut abgesendet')
      );
    }

    if ($this->response->error) {
      return $this->response;
    }

    $honorar = new HonorarAbrechnung($this->request, $dozKurs->kurs, \SessionOperations::getCurrentWebToolsDozent());
    $rawpdf = $honorar->getFile();

    $this->response->rawpdf = $rawpdf;

    if (!$this->response->error) {
      $datDoc = $this->getDatDocObj();
      try {
        \DatDocAPI::sendAllgDokument2DMZ(array($datDoc), $rawpdf);
      } catch (\AbgleichApiException $ex) {
        \Logger::loggException($ex, 500);

        $this->response->error = true;
        StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
          'Ein technischer Fehler ist aufgetreten. '
          . 'Versuchen Sie es erneuet oder kontaktieren Sie Ihren Administrator.'
        ));
      }
    }

    if (!$this->response->error) {
      
      $recipientSettings = new EMailEinrichtungRecipientToolsKursSettings($dozKurs->kurs);
      $recipientSettings
        ->setSettingMailToPlanendenMitarbeiter($this->toolSettings->vertragEMailAnPlanendenMa)
        ->setSettingMailToVerwaltendenMitarbeiter($this->toolSettings->vertragEMailAnVerwaltendenMa)
        ->setSettingMailToVerantwortendenMitarbeiter($this->toolSettings->vertragEMailAnVerantwortendenMa)
        ->setSettingMailToEinrichtung($this->toolSettings->vertragEMailAnEinrichtung ? true : null)
        ->setSettingsVhsEMail($this->toolSettings->vertragEMailEinrichtungAlternative);

      $mail = new HonorarAbrechnungEmailPresenter($this->response);
      $mail = new EMailHTML($mail->getSubject(), $mail->getContent(), array(new EMailAttachmentPDF($datDoc->name, $rawpdf)));
      $sender = EMailSenderFactory::create();
      $sender->sendFromDozentToEinrichtung($mail, $dozent, $recipientSettings);
      $sender->sendFromEinrichtungToDozent($mail, array($dozent));

      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(
        PlainStatusMessage::getSuccessMessageObj('Honorarabrechnung erfolgreich gesendet')
      );
    }

    return $this->response;
  }

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

  protected function getDatDocObj()
  {
    $user = $this->getUser();
    $datDoc = new \Dat_doc();
    $datDoc->datum = \DateTimeOperations::getDateNow();
    $datDoc->lfdnr = '';
    $datDoc->typ = 'V';
    $datDoc->typtxt = 'PDF-Ablage';

    $datDoc->pfaddok = '';
    $datDoc->pfadvorlage = $datDoc->pfaddok;
    $datDoc->datnamdok = '';
    $datDoc->datnamvorlage = '';
    $filename = 'Honorarabrechnung_' . $this->request->knr . '_' . $user->getVarValue('name_vorname_ohne_komma') . '.pdf';
    $datDoc->name = \CodingOperations::convertSingleFileNameSpecialChars($filename);
    $datDoc->versandtam = \DateTimeOperations::getDateTimeNow();

    $datDoc->beschreibung = 'Abgabe Honorarabrechnung';

    $username = $user->getVarValue('name_vorname_ohne_komma');
    $datDoc->versandtvom = $username;
    $datDoc->info = 'Von ' . $username . ' erstellt';

    $datDoc->nr = $user->dnr;
    $datDoc->knr = $this->getKursId();
    $datDoc->freigabe_doz_tools = true;

    return $datDoc;
  }
}