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

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

use Kufer\Web\KuferTools\Dozent\KursUebersicht\Detailsreiter\Honorar\HonorarUseCase;
use Kufer\Web\KuferTools\Utils\StatusMessages\PlainStatusMessage;
use Kufer\Web\KuferTools\Utils\StatusMessages\StatusMessageContainer;
use Kufer\Mail\Attachment\EMailAttachmentPDF;
use Kufer\Mail\EMail\EMailHTML;
use Kufer\Mail\Sender\EMailSenderFactory;
use Kufer\Web\Classes\Api\ImageApi;
use Kufer\Web\Classes\Fileupload\FileUploadAPI;
use Kufer\Web\Classes\Mail\Sender\Settings\RecipientEinrichtung\EMailEinrichtungRecipientToolsKursSettings;

class HonorarAbrechnungDialogAbsendenUseCase extends \Kufer\Web\KuferTools\Basis\UseCase\EinzelKursUseCase
{
  public function __construct($request, $response = null)
  {
    parent::__construct($request, $response ?? new HonorarAbrechnungDialogAbsendenResponse());
  }

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

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

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

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

    if (!\SessionOperations::isDmzBetrieb()) {
      return false;
    }

    if ($this->getUser()->getDnrIdentifier()->isEmpty()) {
      return false;
    }

    if (trim($this->request->signatureImage) === '') {
      return false;
    }

    $this->request->signatureImage = base64_decode($this->request->signatureImage);
    if ($this->request->signatureImage === false) {
      return false;
    }

    if (!extension_loaded('fileinfo') && !extension_loaded('gd')) {
      \Logger::logg('Die PHP-Extensions fileinfo oder gd müssen installiert sein für die Honorarabrechnung', 40);

      return false;
    }

    return true;
  }

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

    $this->response->signaturePath = FileUploadAPI::uploadWithContents($this->request->signatureImage, 'img');
    unset($this->request->signatureImage);
    if ($this->response->signaturePath === false) {
      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
        'Ein technischer Fehler ist aufgetreten.'
      ));

      $this->response->error = true;

      return;
    }

    if (extension_loaded('fileinfo') && mime_content_type($this->response->signaturePath) !== 'image/png') {
      $this->response->error = true;
      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
        'Ein technischer Fehler ist aufgetreten.'
      ));

      return;
    }

    if (extension_loaded('gd')) {
      list(0 => $width, 1 => $height, 2 => $type, 'bits' => $bits, 'mime' => $mimetype) = getimagesize($this->response->signaturePath);
      if ($width !== 300 || $height !== 150 || $mimetype !== 'image/png' || $bits !== 8 || $type !== 3) {
        StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
          'Ein technischer Fehler ist aufgetreten.'
        ));

        return;
      }

      
      $img = imagecreatefrompng($this->response->signaturePath);
      $diffFactor = ImageApi::diffToWhite($img, $width, $height);
      if ($diffFactor < 0.006 || $diffFactor > 0.13) {
        $this->response->error = true;
        StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
          'Die Signature ist leer oder zu verschmiert.'
        ));
      }

      imagedestroy($img);

      unset($width, $height, $type, $bits, $mimetype, $img);
    }
  }

  public function action()
  {
    if (!$this->request->isXsrfOk) {
      $this->response->error = true;

      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
        'Das Formular wurde bereits abgesendet'
      ));
    }

    $this->setSignature();

    $this->response->bemerkungen = $this->request->bemerkungen;
    $this->response->kurstage = $this->request->kurstage;
    $this->response->fahrkosten = $this->request->fahrkosten;
    $this->response->spesen = $this->request->spesen;
    if (!$this->response->error && empty($this->response->kurstage)) {
      $this->response->error = true;

      StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
        'Es muss mindestens ein Kurstag angegeben werden'
      ));
    } else {
      $invalidForm = \ArrayOperations::any($this->response->kurstage, static function(KurstagForm $form): bool {
        return !$form->isValid();
      });

      if ($invalidForm) {
        $this->response->error = true;
        StatusMessageContainer::getSharedInstance()->addStatusMessageObj(PlainStatusMessage::getErrorMessageObj(
          'Alle Felder müssen korrekt ausgefüllt worden sein'
        ));
      }
    }

    if (!$this->response->error) {
      $dozent = \SessionOperations::getCurrentWebToolsDozent();
      $kurs = $this->getKurs($this->getKursId());
      $dbwDozHon = new \DBWorkDozentenHonorar();
      $dozHon = $dbwDozHon->getHonorarbyKNRDozentNR($kurs->id, $dozent->id);
      
      $pdf = new \Kufer\Web\Classes\Pdf\ExtFPDITcPDF(
        'P',
        'mm',
        'A4',
        true,
        \CodingOperations::getInternalEncoding(),
        false,
        false
      );
      $pdf->SetFont('OpenSans', '', 14);

      $pdf->AddPage();
      Veranstaltungsplan::createTable(
        $pdf,
        $kurs,
        $dozent,
        $dozHon,
        $this->response->kurstage,
        $this->response->signaturePath,
        $this->response->fahrkosten,
        $this->response->spesen,
        $this->response->bemerkungen
      )->render();

      $this->response->pdf = $pdf;
      $this->response->kurs = $kurs;

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

    if (!is_null($this->response->signaturePath) && $this->response->signaturePath !== false) {
      @unlink($this->response->signaturePath);
    }

    return $this->response;
  }

  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;

    $datDoc->honabrechnung_tools = true;

    return $datDoc;
  }
}