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

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

use Kufer\Web\KuferTools\Dozent\Anwesenheiten\Utils\KurstageUtils;
use Kufer\Web\KuferTools\Dozent\KursUebersicht\Detailsreiter\Honorar\HonorarUseCase;
use Kufer\Web\KuferTools\Utils\ResponseStrategies\ResponseMitRahmen;
use Kufer\Mail\Attachment\EMailAttachmentPDF;
use Kufer\Mail\EMail\EMailHTML;
use Kufer\Mail\Sender\EMailSenderFactory;
use Kufer\Web\Classes\api\TerminAPI;
use Kufer\Web\Classes\Mail\Sender\Settings\RecipientEinrichtung\EMailEinrichtungRecipientToolsKursSettings;
use Kufer\Web\KuferTools\Dozent\KursUebersicht\Detailsreiter\Honorar\RavensbergHalle\HonorarPdf\HonorarAbrechnungEmailPresenter;
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 HonorarAbrechnungAbsendenResponse());
  }

  public static function getToolId()
  {
    return HonorarUseCase::getToolId();
  }

  public static function getToolSectionId()
  {
    return HonorarUseCase::getToolSectionId();
  }

  private $cacheKurs;

  
  private function findKurs()
  {
    if (is_null($this->cacheKurs)) {
      $this->cacheKurs = $this->getKurs($this->getKursId());
    }

    return $this->cacheKurs;
  }

  private $cacheKurstage;

  private function findKurstage()
  {
    if (is_null($this->cacheKurstage)) {
      $this->cacheKurstage = \DBWorkKurseTage::getDefaultInstance()->getKurstageByKursNrAndDozentNr(
        $this->getKursId(),
        $this->getUser()->getDnrIdentifier(),
        array('A', 'X')
      );
    }

    return $this->cacheKurstage;
  }

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

    $kurs = $this->findKurs();
    $kurstage = $this->findKurstage();

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

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

    return true;
  }

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

    $dozent = \SessionOperations::getCurrentWebToolsDozent();
    $kurs = $this->findKurs();
    $this->response->kurs = $kurs;
    $kurstage = $this->findKurstage();
    $this->response->kurstage = $kurstage;
    $this->response->entfernung = $this->request->entfernung;
    $this->response->iban = trim($this->request->iban);
    $this->response->bic = trim($this->request->bic);
    $this->response->bankbez = $this->request->bankbez;

    $oldIban = $dozent->iban;
    $oldBic = $dozent->bic;
    if (($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;
    }

    $pdf = new \Kufer\Web\Classes\Pdf\ExtFPDITcPDF(
      'P',
      'mm',
      'A4',
      true,
      \CodingOperations::getInternalEncoding(),
      false,
      false
    );
    $pdf->SetFont('OpenSans', '', 12);

    $pdf->AddPage();

    $viewModelPdf = new TerminAbrechnenPdfViewModel();
    $viewModelPdf->kurs = $kurs;
    $viewModelPdf->kurstage = $kurstage;
    $viewModelPdf->entfernung = $this->request->entfernung;
    $viewModelPdf->iban = $this->request->iban;
    $viewModelPdf->bic = $this->request->bic;
    $viewModelPdf->bankbez = $this->request->bankbez;
    $viewModelPdf->dozent = $dozent;

    $viewPdf = new TerminAbrechnenPdfView($viewModelPdf);
    $pdf->writeHTML($viewPdf->show());

    $anwesenheitsliste = new HildenVHSAnwesenheitsliste(
      $this->getKursId(),
      $this->getToolId(),
      $this->response->kurstage
    );
    $anwesenheitsliste->loadSettings();
    $anwesenheitslistePdf = $anwesenheitsliste->create(true);

    $count = $pdf->setSourceFile(
      \setasign\Fpdi\PdfParser\StreamReader::createByString($anwesenheitslistePdf, 40 * 1024 * 1024)
    );
    for ($i = 1; $i <= $count; $i++) {
      $template = $pdf->importPage($i);
      $size = $pdf->getTemplateSize($template);
      $pdf->AddPage($size['orientation'], array($size['width'], $size['height']));
      $pdf->useTemplate($template);
    }

    $rawpdf = $pdf->Output('', 'S');
    $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($this->response->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 ResponseMitRahmen($this)
    );
  }

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

    $datDoc->pfaddok = '';
    $datDoc->pfadvorlage = $datDoc->pfaddok;
    $datDoc->datnamdok = '';
    $datDoc->datnamvorlage = '';
    $datDoc->name = 'honorarabrechnung-abgabe-' . \CodingOperations::convertSingleFileNameSpecialChars($this->response->kurs->getVarValue('nr_anzeige')) . '.pdf';
    $datDoc->versandtam = \DateTimeOperations::getDateTimeNow();

    $datDoc->beschreibung = 'Abgabe Honorarabrechnung von ' . $user->getVarValue('name_vorname_ohne_komma');

    $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;
  }
}