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

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

class WssFieldKursNaechsterKurstag extends \Kufer\Web\KuferTools\Utils\WssField\WssField
{
  protected function getValue($datamodulWert, $isFormular = false)
  {
    $nextKurstag = $this->getNextKurstagDate($datamodulWert);
    if (!is_null($nextKurstag)) {
      return
        '<abbr title="' . \CleanOperations::cleanStringForHtml(\DateTimeOperations::getWeekDay($nextKurstag)) . '">'
        . \CleanOperations::cleanStringForHtml(\DateTimeOperations::getWeekDayShort($nextKurstag))
        . '</abbr>, '
        . \CleanOperations::cleanStringForHtml($nextKurstag);
    }

    return '';
  }

  protected function encodeValue($value)
  {
    return $value;
  }

  private function getNextKurstagDate($datamodulWert): ?string
  {
    $jetzt = \DateTimeObj::getNow();

    if (\DBWorkBASysSettings::isInlinguaUeberlingen()) {
      
      $jetzt->addMinutes(-15);
    }

    $kursnr = $datamodulWert->getVarValueEx('id', 'kurs');
    $dbwKurstage = new \DBWorkKurseTageWT(1, true);
    $dbwKurstage->newSearch();
    $dbwKurstage->fromobject->datum = $jetzt->getDate();
    $dbwKurstage->fromobject->ausfall = $this->getKtStatusErlaubt();
    
    $kurstage = $dbwKurstage->getKurstagebyKursNR($kursnr);
    foreach ($kurstage as $kurstag) {
      $datumKurstag = new \DateTimeObj($kurstag->datum . ' ' . $kurstag->zeit_beg);
      if ($jetzt->isBeforeDateTime($datumKurstag)) {
        return $kurstag->datum;
      }
    }

    return null;
  }

  private function getKtStatusErlaubt()
  {
    $alleStatus = \ConstantOperations::getKurstagStatus4EinschraenkungAufKTStatus();
    unset($alleStatus['A']);
    $kuerzel = \array_keys($alleStatus);

    return \implode('', $kuerzel);
  }
}