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

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

class HonorarAbrechnungAbsendenUseCase extends \Kufer\Web\KuferTools\Basis\UseCase\ToolUseCase
{
  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::isGilchingVhs()) {
      return false;
    }
    if (!$this->isVertragsDruckAllowed()) {
      return false;
    } elseif (!$this->request->isXsrfOk && !$this->request->isRefresh) {
      return false;
    }

    return true;
  }

  private function isVertragsDruckAllowed()
  {
    $vertragUtils = \Kufer\Web\KuferTools\Dozent\KursUebersicht\Detailsreiter\Honorar\Vertrag\Utils\VertragUtilsGilchingVhs::getVertragUtils($this->request->knr);

    return $vertragUtils->isVertragsDruckAllowed();
  }

  public function action()
  {
    $dbwKurseWT = new \DBWorkKurseWT();
    $kurs = $dbwKurseWT->getKurs($this->request->knr);
    $successSaveDok = $successMail = false;

    if (!$this->request->isRefresh) {
      $honorar = new HonorarAbrechnung($this->request, $kurs, \SessionOperations::getCurrentWebToolsDozent());
      $honorarInhalt = $honorar->getFile();

      $successSaveDok = $this->saveDokument($honorarInhalt);
      $successMail = $this->sendMailAnMitarbeiter($successSaveDok, $honorarInhalt, $kurs);
    }

    return $this->getResponse($successSaveDok, $successMail);
  }

  private function saveDokument($honorarInhalt)
  {
    $datDoc = $this->getDatDocAry();
    try {
      \DatDocAPI::sendAllgDokument2DMZ($datDoc, $honorarInhalt);
    } catch (\Exception $e) {
      return false;
    }

    return true;
  }

  private function getDatDocAry()
  {
    $user = $this->getUser();
    $datDoc = new \Dat_doc();
    $datDoc->knr = $this->request->knr;
    $datDoc->lfdnr = '';
    $datDoc->nr = $user->dnr;
    $datDoc->typ = 'V';
    $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->versandtvom = $user->getVarValue('name_vorname_ohne_komma');
    $datDoc->beschreibung = 'Honorarabrechnung';
    $datDoc->info = 'Von Dozent ' . $user->getVarValue('name_vorname_ohne_komma') . ' zum Kurs ' . $this->request->knr;
    $datDoc->typtxt = 'PDF-Ablage';
    $datDoc->freigabe_doz_tools = true;

    
    
    

    return array($datDoc);
  }

  protected function sendMailAnMitarbeiter($pDokumentErfolgreichGespeichert, $pDokumentInhalt, $pKurs)
  {
    $dozent = \SessionOperations::getCurrentWebToolsDozent();
    $senderEmailData = \ToolsAPI::getSenderEmailAddressAndName($dozent);

    $toolSettings = \ToolSettingsAPI::getToolSettings(\ToolsAPI::TOOL_KURSUEBERSICHT_DOZ);
    
    $mailAnMaAry = array('VerwMa' => $toolSettings->stornoBenachrichtigungsMailAnVerwMa,
                         'PlanMa' => $toolSettings->stornoBenachrichtigungsMailAnPlanMa);
    
    $pageIdReiterSeite = \Kufer\Web\KuferTools\Dozent\KursUebersicht\Detailsreiter\FeedbackBogen\FeedbackBogenUseCase::getToolSectionId();
    $mailAdressen = \ToolsAPI::getEmailAdressForKursMA($pKurs, \ToolsAPI::TOOL_KURSUEBERSICHT_DOZ, $pageIdReiterSeite, $mailAnMaAry);

    $emailData = new \stdClass();
    $emailData->kurs = $pKurs;
    $emailData->dateiPerDmzGespeichert = $pDokumentErfolgreichGespeichert;

    $mailPresenter = new HonorarAbrechnungAbsendenMailPresenter($emailData);

    $success = $this->sendMailAnPersonen($mailAdressen, $senderEmailData, $dozent, $pKurs, $mailPresenter, $pDokumentInhalt);

    if ($toolSettings->feedbackBenachrichtigungsMailAnDozent) {
      $validierung = \ValidierungBasis::getInstance();
      if ($validierung->isValidVar('email', $dozent->email_anzeige)) {
        $this->sendMailAnPersonen(array($dozent->email_anzeige), $senderEmailData, $dozent, $pKurs, $mailPresenter, $pDokumentInhalt);
      }
    }

    return $success;
  }

  protected function sendMailAnPersonen($pMailAdressen, $pSenderEmailData, $pDozent, $pKurs, $pMailPresenter, $pDokumentInhalt)
  {
    $success = false;

    foreach ($pMailAdressen as $mailAdresse) {
      $email = new \smtpMailTools();
      $email->setVar2Value('to', $mailAdresse);
      $email->setVar2Value('from', $pSenderEmailData['email']);
      $email->SetVar2Value('sendername', $pSenderEmailData['name']);
      $email->SetVar2Value('reply', $pSenderEmailData['reply']);
      $email->SetVar2Value('replyname', $pSenderEmailData['replyname']);
      $email->SetVar2Value('contenttype', SMTP_CONTENTTYPE_HTML);
      $email->SetVar2Value('doNotSplitHTMLBody', true);
      $email->subject = $pMailPresenter->getSubject();
      $email->body = $pMailPresenter->getBody();
      $email->setFooter('Login KuferTools', $this->getUser());

      $email->addAttachment(new \EMailAttachment('Honorarabrechnung von Dozent ' . $pDozent->getVarValue('name_vorname_ohne_komma') . ' Kurs ' . $pKurs->id, $pDokumentInhalt));

      $success = $success || $email->sendMail();
    }

    return $success;
  }

  protected function getResponse($successSaveDok, $successMail)
  {
    $this->handleResponseStrategies();

    $dbwDozKurs = new \DBWorkDozentenHonorar();
    $this->response->dozKurs = $dbwDozKurs->getHonorarbyKNRDozentNR($this->request->knr, $this->getUser()->dnr);

    if ($successSaveDok || $successMail || $this->request->isRefresh) {
      $this->response->readonly = true;
    }

    $this->response->successSaveDok = $successSaveDok;
    $this->response->successMail = $successMail;
    $this->response->isRefresh = $this->request->isRefresh;

    $this->response->abrechnung_art = $this->request->abrechnung_art;
    $this->response->honsatz_1 = $this->request->honsatz_1;
    $this->response->honsatz_2 = $this->request->honsatz_2;
    $this->response->honsatz_3 = $this->request->honsatz_3;
    $this->response->stdanz_1 = $this->request->stdanz_1;
    $this->response->stdanz_2 = $this->request->stdanz_2;
    $this->response->stdanz_3 = $this->request->stdanz_3;
    $this->response->bemerkung = $this->request->bemerkung;
    $this->response->ergaenzung = $this->request->ergaenzung;
    $this->response->bestaetigung_check = true;
    $this->response->iban = $this->request->iban;
    $this->response->bic = $this->request->bic;
    $this->response->bankbez = $this->request->bank;

    return $this->response;
  }

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

class HonorarAbrechnungAbsendenRequest
{
  public $knr;

  public $iban;
  public $bic;
  public $bank;

  public $honsatz_1;
  public $honsatz_2;
  public $honsatz_3;

  public $stdanz_1;
  public $stdanz_2;
  public $stdanz_3;

  public $honbetrag_1;
  public $honbetrag_2;
  public $honbetrag_3;

  public $hongesamt;
  public $bemerkung;
  public $ergaenzung;
  public $abrechnung_art;
}

class HonorarAbrechnungAbsendenResponse extends \Kufer\Web\KuferTools\Basis\UseCase\ToolResponse
{
  public $dozKurs;
  public $bearbeitbar = false;

  public $successSaveDok;
  public $successMail;

  public $readonly = false;
}