<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\KuferTools\Utils\KursHandler;

use Kufer\KuferTools\Basis\BenachrichtigungNachBearbeiten\BenachrichtigungUtils;
use Kufer\KuferTools\Utils\StatusMessages\StatusMessage;

class KursUpdaterWss extends KursUpdater
{
  protected $wssHandler;
  protected $columnValues;

  
  public function __construct($pKnr, $pToolId, $pToolSectionId, $pWssHandler, $pColumnValues)
  {
    parent::__construct($pKnr, $pToolId, $pToolSectionId);
    $this->wssHandler = $pWssHandler;
    $this->columnValues = $pColumnValues;
  }

  public function doUpdate($pUser): bool
  {
    if ($this->validateFields()) {
      return parent::doUpdate($pUser);
    } else {
      \Logger::logg('Bearbeiten eines Kurses: - Validierung fehlgeschlagen', 200);
      $this->setStatusMessageFailureValidationContent($this->getWrongFields());

      return false;
    }
  }

  protected function validateFields()
  {
    $wrongFields = $this->getWrongFields();

    return count($wrongFields) == 0;
  }

  protected function setStatusMessageFailureValidationContent($pWrongFields)
  {
    $message = \Kufer\KuferTools\Utils\WssHandler::getErrorMessage($pWrongFields);
    $this->statusMessageContainer->addStatusMessageObj(StatusMessage::getErrorMessageObj($message));
  }

  protected function getWrongFields()
  {
    static $cache = null;
    if (is_null($cache)) {
      $cache = $this->wssHandler->checkColumnValues($this->columnValues);
    }

    return $cache;
  }

  protected function getChangedKurs()
  {
    $origKurs = $this->getOrigKurs();
    $changedKurs = $this->wssHandler->getChangedDm($origKurs, $this->columnValues);

    if (\DBWorkBASysSettings::isSalzburgBildungswerk()) {
      $changedKurs->abschluss = 'Y';
    }

    return $changedKurs;
  }

  protected function getChangedFields()
  {
    $origKurs = $this->getOrigKurs();
    $changedFields = $this->wssHandler->getChangedFieldnames($origKurs, $this->columnValues);

    if (\DBWorkBASysSettings::isSalzburgBildungswerk()) {
      $changedFields[] = 'abschluss';
    }

    return $changedFields;
  }

  
  protected function sendeBenachrichtigung($pOrigKurs, $pChangedKurs, $pChangedFields, $pUser)
  {
    $changedFieldsLabels = $this->wssHandler->getFieldsInReadableFormat($pChangedFields);
    $footerText = 'Kurs Bearbeiten';

    $columns = $this->wssHandler->getColumnsCached();
    BenachrichtigungUtils::sendeBenachrichtigungEmailKursdaten(
      $columns,
      $pOrigKurs,
      $pChangedKurs,
      $pChangedFields,
      $changedFieldsLabels,
      $footerText,
      $pUser,
      $this->toolId,
      $this->toolSectionId
    );
  }
}