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

namespace Kufer\Web\KuferTools\Utils\WssField\Teilnehmer;

class WssFieldTeilnehmerFirma extends \Kufer\Web\KuferTools\Utils\WssField\WssField
{
  protected function getFieldBearbeitbar($datamodulWert, $isFormular, string $requestPrefix = '')
  {
    return $this->_buildField($this->datamodulColumn, $datamodulWert, 2, false);
  }

  protected function getValue($datamodulWert, $isFormular = false)
  {
    $firmen = static::getFirmaFromDatamodul($datamodulWert);
    if (!empty($firmen)) {
      if (\count($firmen) == 1) {
        return $this->htmlEncode(\ArrayOperations::firstValue($firmen)->getVarValue('titel_name_vorname'));
      } else {
        return '<ul class="wss_list">' . \implode('', \array_map(function($firma) {
          return '<li>' . $this->htmlEncode($firma->getVarValue('titel_name_vorname')) . '</li>';
        }, $firmen)) . '</ul>';
      }
    }

    return '';
  }

  protected function encodeValue($value)
  {
    
    return $this->dontEncode($value);
  }

  private function getPostName()
  {
    return 'teilnehmer_firmen_hidden';
  }

  public function inPost(string $requestPrefix = ''): bool
  {
    return \PostOperations::isDefined(($requestPrefix === '' ? '' : $requestPrefix . '_') . $this->getPostName());
  }

  public function getValueFromPost(string $requestPrefix = '')
  {
    $jsonBase64 = \PostOperations::getVarValue(($requestPrefix === '' ? '' : $requestPrefix . '_') . $this->getPostName());

    return \JsonOperations::getFromStringBase64InternalEncoding($jsonBase64);
  }

  public function getChangedInfo($columnValues, $changedDm, $changedFields): array
  {
    if ($this->datamodulColumn->accesslevel == 2 && $this->datamodulColumn->canedit == 1) {
      $datamodul = $this->getDatamodulName();
      $fieldname = $this->getFieldName();
      if (isset($columnValues[$datamodul][$fieldname])) {
        $newData = $columnValues[$datamodul][$fieldname];

        $newDataTnrs = \ArrayOperations::mapAttribut($newData, 'id');
        if (isset($changedDm->id) && $changedDm->id !== '') {
          static::updateBeziehungen($changedDm->id, $newDataTnrs);
        }

        $changedDm->firmenauswahl = $newDataTnrs;
        $changedFields[] = 'firmenauswahl';
      }
    }

    return array('changed' => $changedDm, 'changedFields' => $changedFields);
  }

  
  public static function updateBeziehungen($tnrMitarbeiter, $tnrFirmen)
  {
    $currentFirmen = static::getFirmaFromDatamodul($tnrMitarbeiter);
    $currentFirmenTnrs = \ArrayOperations::mapAttribut($currentFirmen, 'id');
    $beziehungenToRemoveTnrs = \array_diff($currentFirmenTnrs, $tnrFirmen);
    $beziehungenToAddTnrs = \array_diff($tnrFirmen, $currentFirmenTnrs);
    $dbwBeziehungen = new \DBWorkBeziehung();
    foreach ($beziehungenToRemoveTnrs as $tnr) {
      $bez = $dbwBeziehungen->getBeziehungFromPerson(
        3,
        'T',
        $tnr,
        'T',
        $tnrMitarbeiter
      );
      \BeziehungAPI::deleteBeziehung($bez->id);
    }
    foreach ($beziehungenToAddTnrs as $tnr) {
      $bez = static::getFirmenMitarbeiterBeziehung($tnrMitarbeiter, $tnr);
      \BeziehungAPI::insertBeziehung($bez);
    }
  }

  public static function getFirmenMitarbeiterBeziehung($mitarbeiterId, $tnrFirma)
  {
    $bezId = static::getHLBeziehungByArt(3);
    $result = new \Beziehung();
    $result->bezId = $bezId;
    $result->typ1 = 'T';
    $result->nr1 = $tnrFirma;
    $result->typ2 = 'T';
    $result->nr2 = $mitarbeiterId;
    $result->gueltig_von = \DateObj::getNow()->getDate();
    $result->gueltig_bis = DEFAULTDATE;

    return $result;
  }

  protected function isMandatoryValueEmpty($value): bool
  {
    return \count($value) === 0;
  }

  private function _buildField($field, $datamodulWert, $privileg, $pPrintversion)
  {
    $canedit = ($privileg == 2 && !$pPrintversion && $field->canedit);

    $htmlField = $this->_getArea($datamodulWert, $pPrintversion, $field, $canedit);
    if ($canedit) {
      $htmlField .= '<div class="firmenauswahl_buttons" style="position: absolute; right: 25px; top: 5px; font-size: 2em;">';

      $htmlField
        .= '<div style="resize: none;">'
          . '<button class="button_new_firmenauwahl_test no-button-style" type="button" title="Firmen auswählen">'
            . '<i class="fa fa-address-book-o hinterlegung-button-icon"></i>'
          . '</button>'
        . '</div>';

      $htmlField
        .= '<div style="resize: none;">'
          . '<button class="button_delete_firmenauwahl no-button-style" type="button" title="Firmen entfernen">'
            . '<i class="fa fa-trash hinterlegung-button-icon"></i>'
          . '</button>'
        . '</div>';

      $htmlField .= '</div>';
    }

    if (!$pPrintversion) {
      
      static $callInit = true;
      if ($callInit) {
        $htmlField .= $this->initJS();
        $callInit = false;
      }
    }

    return $htmlField;
  }

  private function initJS()
  {
    return '';
  }

  private function _getArea($datamodulWert, $pPrintversion, $field, $pEditable)
  {
    $fieldname = $this->_getFieldname($field);
    
    $firmenJs = \array_map(function(\Teilnehmer $tn) {
      $result = new \stdClass();
      $result->id = $tn->id;
      $result->vorname = $tn->vorname;
      $result->name = $tn->name;

      return $result;
    }, static::getFirmaFromDatamodul($datamodulWert));

    $tablespaceproperties = ($pPrintversion) ? 'cellpadding="2" cellspacing="2"' : '';

    $readonly = (!$pEditable) ? ' disabled' : '';
    $str = '<div id="' . $fieldname . '" class="recht_' . $field->privileg_key . ' ' . $fieldname . ' form-control" style="min-height: 177px; overflow: auto;".' . $readonly . '>' . "\n"
              . '<table class="mnlisttable" border="1" ' . $tablespaceproperties . ' rules="all" style="font-size:12px; width: 95%;">' . "\n"
                . '<thead></thead>' . "\n"
                . '<tbody>' . "\n";
    $str .= '</tbody>' . "\n"
           . '</table>' . "\n"
           . '<input id="' . $fieldname . '_hidden" class="mnlist_hidden" name="' . $fieldname . '_hidden" type="hidden" value="' . \JsonOperations::encodeBase64($firmenJs) . '">' . "\n"
        . '</div>' . "\n";

    return $str;
  }

  
  public static function getFirmaFromDatamodul($datamodulWert)
  {
    $tnr = \is_int($datamodulWert) ? $datamodulWert : $datamodulWert->getVarValueEx('id', 'teilnehmer');
    if ($tnr === '') {
      return array();
    }

    $dbwBeziehungen = new \DBWorkBeziehung();
    $firmenBez = $dbwBeziehungen->getBeziehungMitarbeiterZuFirma($tnr);
    $dbwTeilnehmer = new \DBWorkTeilnehmer();

    return \array_map(function(\Beziehung $bez) use ($dbwTeilnehmer) {
      return $dbwTeilnehmer->getTeilnehm($bez->nr1);
    }, $firmenBez);
  }

  public static function getHLBeziehungByArt(int $pArt)
  {
    $dbwBeziehung = new \DBWorkBeziehung();

    return $dbwBeziehung->getHlBezId4BeziehungsArt($pArt);
  }
}