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

class KurstagAPI
{
  
  public static function getSammelAenderungFormular($pKurstag, $pKtIds, $pFelder, $pToolId, $pAction)
  {
    $sprachSettings = SettingsFactory::getSettings('SprachSettingsObject');

    
    
    if (isset($pFelder['datum']) && ToolsAPI::rechteOR($pFelder['datum'], $pToolId, true)) {
      $options = array();
      for ($i = 1; $i < 7; $i++) {
        $options[] = "<option value=\"$i\">$i</option>";
      }
      $options[] = "<option value=\"$i\" selected>$i</option>";
      for ($i = -1; $i > -8; $i--) {
        $options[] = "<option value=\"$i\">$i</option>";
      }
      $datumSelect = HTMLOperations::CreateSelectTag($options, 'wt_kt_changeDate_val', '', 'wt_kt_changeDate_val');
      $datum = '<tr>'
        . HTMLOperations::CreateTdTag(
          HTMLOperations::CreateInputTag('wt_kt_changeDate', 'checkbox', 'wt_kt_changeDate', 'wt_kt_checkbox', '1')
        )
        . HTMLOperations::CreateTdTag(
          '<label for="wt_kt_changeDate">' . 'Datum:' . '</label>'
        )
        . HTMLOperations::CreateTdTag(CleanOperations::cleanStringForHtml($sprachSettings->Kurstag['Plural']['Akkusativ']) . ' um ' . $datumSelect . ' Tage verschieben', '', '', '', false, 4) . '</tr>';
    } else {
      $datum = '';
    }
    
    $showBeginn = isset($pFelder['beginn']) && ToolsAPI::rechteOR($pFelder['beginn'], $pToolId, true);
    $showEnde = isset($pFelder['ende']) && ToolsAPI::rechteOR($pFelder['ende'], $pToolId, true);
    $hlUhrzeitButton = '';
    if ($showBeginn && $showEnde) {
      $hlUhrzeitButton = ToolsAPI::hlGetUhrzeitHinterlegungsButton(\HLDispatcher::HL_UHRZEITEN, 'wt_kt_changeBeginn_val:wt_kt_changeEnde_val', true);
    }
    if ($showBeginn) {
      $beginn = '<tr>'
        . HTMLOperations::CreateTdTag(
          HTMLOperations::CreateInputTag('wt_kt_changeBeginn', 'checkbox', 'wt_kt_changeBeginn', 'wt_kt_checkbox', '1')
        );
      $colsForBeginn = 4;
      $showUe = false;
      if (isset($pFelder['ue']) && ToolsAPI::rechteOR($pFelder['ue'], $pToolId, true)) {
        $showUe = true;
        $colsForBeginn -= 3;
      }
      $beginn
        .= HTMLOperations::CreateTdTag(
          '<label for="wt_kt_changeBeginn">' . 'Beginn:' . '</label>'
        )
        . HTMLOperations::CreateTdTag(
          HTMLOperations::CreateInputTag('wt_kt_changeBeginn_val', 'text', 'wt_kt_changeBeginn_val', 'uhrzeit val_time', $pKurstag->zeit_beg, '', false, false, 5)
           . $hlUhrzeitButton,
          '',
          '',
          '',
          false,
          $colsForBeginn
        );
      if ($showUe) {
        $beginn
          .= HTMLOperations::CreateTdTag('UE:')
          . HTMLOperations::CreateTdTag(
            HTMLOperations::CreateInputTag('wt_kt_changeUe_val', 'text', 'wt_kt_changeUe_val', 'ue val_float', $pKurstag->ue),
            '',
            '',
            '',
            false,
            2
          );
      }
      $beginn .= '</tr>';
    } else {
      $beginn = '';
    }
    if ($showEnde) {
      $ende = '<tr>'
        . HTMLOperations::CreateTdTag(
          HTMLOperations::CreateInputTag('wt_kt_changeEnde', 'checkbox', 'wt_kt_changeEnde', 'wt_kt_checkbox', '1')
        )
        . HTMLOperations::CreateTdTag(
          '<label for="wt_kt_changeEnde">' . 'Ende:' . '</label>'
        );
      $colsForEnde = 4;
      $showMinuten = false;
      if (isset($pFelder['minuten']) && ToolsAPI::rechteOR($pFelder['minuten'], $pToolId, true)) {
        $showMinuten = true;
        $colsForEnde -= 2;
      }
      $showPause = false;
      if (isset($pFelder['pause']) && ToolsAPI::rechteOR($pFelder['pause'], $pToolId, true)) {
        $showPause = true;
        $colsForEnde -= 1;
      }
      $ende
        .= HTMLOperations::CreateTdTag(
          HTMLOperations::CreateInputTag('wt_kt_changeEnde_val', 'text', 'wt_kt_changeEnde_val', 'uhrzeit val_time', $pKurstag->zeit_ende, '', false, false, 5)
           . $hlUhrzeitButton,
          '',
          '',
          '',
          false,
          $colsForEnde
        );
      if ($showMinuten) {
        $ende
          .= HTMLOperations::CreateTdTag('Minuten: ')
          . HTMLOperations::CreateTdTag(
            HTMLOperations::CreateInputTag('wt_kt_changeMinuten_val', 'text', 'wt_kt_changeMinuten_val', 'minuten val_int', $pKurstag->minuten)
          );
      }
      if ($showPause) {
        $ende
          .= HTMLOperations::CreateTdTag(
            'Pause: '
             . HTMLOperations::CreateInputTag('wt_kt_changePause_val', 'text', 'wt_kt_changePause_val', 'pause val_int', $pKurstag->pause)
          );
      }
      $ende .= '</tr>';
    } else {
      $ende = '';
    }
    
    if (isset($pFelder['ausfall']) && ToolsAPI::rechteOR($pFelder['ausfall'], $pToolId, true)) {
      $ausfallSelect = '<select name="wt_kt_changeAusfall_val" id="wt_kt_changeAusfall_val">' . ComboboxAPI::getAusfallTool3($pKurstag->ausfall) . '</select>';
      $status = '<tr>'
        . HTMLOperations::CreateTdTag(
          HTMLOperations::CreateInputTag('wt_kt_changeAusfall', 'checkbox', 'wt_kt_changeAusfall', 'wt_kt_checkbox', '1')
        )
        . HTMLOperations::CreateTdTag(
          '<label for="wt_kt_changeAusfall">' . 'Status:' . '</label>'
        )
          . HTMLOperations::CreateTdTag($ausfallSelect, '', '', '', false, 4) . '</tr>';
    } else {
      $status = '';
    }

    
    $buttonStyle = 'cursor:pointer;';
    if (isset($pFelder['kursort']) && ToolsAPI::rechteOR($pFelder['kursort'], $pToolId, true)) {
      $inputIds = array('wt_kt_changeKursort_val');
      $kursortButton = PageButtonsAPI::getHinterlegungButton(\HLDispatcher::HL_KURSORTE, $inputIds, 'button_hl_raum', $buttonStyle, 'hlraum_div', 'Räume');
      $colsForKursort = 8;
      $kursort = '<tr>'
          . HTMLOperations::CreateTdTag(
            HTMLOperations::CreateInputTag('wt_kt_changeKursort', 'checkbox', 'wt_kt_changeKursort', 'wt_kt_checkbox', '1')
          )
          . HTMLOperations::CreateTdTag(
            '<label for="wt_kt_changeKursort">' . 'Kursort:' . '</label>'
          )
          . HTMLOperations::CreateTdTag(
            HTMLOperations::CreateInputTag('wt_kt_changeKursort_val', 'text', 'wt_kt_changeKursort_val', '', $pKurstag->ort, '', false, false)
            . $kursortButton,
            '',
            '',
            '',
            false,
            $colsForKursort
          ) . '</tr>';
    } else {
      $kursort = '';
    }

    
    if (isset($pFelder['bemerkung']) && ToolsAPI::rechteOR($pFelder['bemerkung'], $pToolId, true)) {
      $bemerkung = '<tr>'
        . HTMLOperations::CreateTdTag(HTMLOperations::CreateInputTag('wt_kt_changeBemerkung', 'checkbox', 'wt_kt_changeBemerkung', 'wt_kt_checkbox', '1'))
        . HTMLOperations::CreateTdTag(
          '<label for="wt_kt_changeBemerkung">' . 'Bemerkung / Lehrinhalt:' . '</label>'
        )
        . HTMLOperations::CreateTdTag(HTMLOperations::CreateTextArea('wt_kt_changeBemerkung_val', 2, 45, 5, 'wt_kt_changeBemerkung_val', $pKurstag->bemerkungen), '', '', '', false, 4)
          . '</tr>';
    } else {
      $bemerkung = '';
    }


    $result = '';

    
    
    $result .= '<script type="text/javascript">';
    $result .= 'registerNamespace("KuferTools");';
    $result .= 'registerNamespace("KuferTools.KurstagPlanung");';
    $result .= JsOperations::getDeclarationBoolean('KuferTools.KurstagPlanung.Sammelaenderung', true);
    $result .= JsOperations::getDeclarationString('KuferTools.KurstagPlanung.Beginn', $pKurstag->zeit_beg);
    $result .= JsOperations::getDeclarationString('KuferTools.KurstagPlanung.Ende', $pKurstag->zeit_ende);
    $result .= JsOperations::getDeclarationFloatMitKomma('KuferTools.KurstagPlanung.Ue', $pKurstag->ue);
    $result .= JsOperations::getDeclarationInt('KuferTools.KurstagPlanung.Minuten', $pKurstag->minuten);
    $result .= JsOperations::getDeclarationInt('KuferTools.KurstagPlanung.Pause', $pKurstag->pause);
    $result .= '</script>';


    $result .= '<form id="kurstagSammelaenderung" method="post" action="' . CleanOperations::cleanStringForHtml($pAction) . '">';

    $result .= '<table width="100%">';
    $result .= '<caption>Sammeländerung von ' . count($pKtIds) . ' ' . CleanOperations::cleanStringForHtml($sprachSettings->KurstagVon['Plural']['von']) . ' für Kurs '
              . CleanOperations::cleanStringForHtml($pKurstag->kurs->id) . ', ' . CleanOperations::cleanStringForHtml($pKurstag->kurs->kurzbez) . '</caption>';
    $result .= '<tbody>';

    $result .= $datum;
    $result .= $beginn;
    $result .= $ende;
    $result .= $status;
    $result .= $kursort;
    $result .= $bemerkung;
    $result .= '<tr><td></td></tr>';

    $result .= '</tbody>';
    $result .= '</table>';
    $result .= '<input type="hidden" name="wt_kt_sammelids" value="' . implode(';', $pKtIds) . '">';
    $result .= '<input type="hidden" name="postId" value="' . (SessionOperations::getVarValueWTIntern('postId', 0) + 1) . '">';
    $result .= '</form>';

    return $result;
  }

  

  
  public static function actualizeFields4KTVars($pChangedFields, $pModeInsert = false)
  {
    
    if ($pModeInsert) {
      $pChangedFields[] = 'knr';
    }

    return $pChangedFields;
  }

  

  
  public static function aktualisiereKurstagZeit($pKurstag, $pBeginn = null, $pEnde = null, $pPause = null, $pMinuten = null, $pUe = null)
  {
    if (!is_null($pBeginn)) {
      $pKurstag->zeit_beg = $pBeginn;
    }
    if (!is_null($pEnde)) {
      $pKurstag->zeit_ende = $pEnde;
    }

    $minutenBeginn = DateTimeOperations::convertTimeToMinutes($pKurstag->zeit_beg);
    $minutenEnde = DateTimeOperations::convertTimeToMinutes($pKurstag->zeit_ende);
    $minutenGesamt = $minutenEnde - $minutenBeginn;

    
    if (!is_null($pPause)) {
      $pKurstag->pause = $pPause;
      $pKurstag->minuten = $minutenGesamt - $pKurstag->pause;
      
      $tmpue = MathOperations::calculateUE($pKurstag->minuten, null, $pKurstag->knr);
      $pKurstag->ue = MathOperations::floatToStringTruncateNull(round($tmpue, 2));
    } elseif (!is_null($pMinuten)) {
      $pKurstag->minuten = $pMinuten;
      $pKurstag->pause = $minutenGesamt - $pKurstag->minuten;
      $tmpue = MathOperations::calculateUE($pKurstag->minuten, null, $pKurstag->knr);
      $pKurstag->ue = MathOperations::floatToStringTruncateNull(round($tmpue, 2));
    } elseif (!is_null($pUe)) {
      $pKurstag->ue = $pUe;
      $pKurstag->minuten = MathOperations::calculateMin($pKurstag->ue, null, $pKurstag->knr);
      $pKurstag->pause = $minutenGesamt - $pKurstag->minuten;
    } else { 
      $pKurstag->minuten = $minutenGesamt - (int)$pKurstag->pause;
      $tmpue = MathOperations::calculateUE($pKurstag->minuten, null, $pKurstag->knr);
      $pKurstag->ue = MathOperations::floatToStringTruncateNull(round($tmpue, 2));
    }

    return $pKurstag;
  }

  

  public function getChangedFieldsFromPost()
  {
    $changedFields = array();
    
    
    $checkBoxen = array('wt_kt_changeDate' => 'datum', 'wt_kt_changeBeginn' => 'zeit_beg', 'wt_kt_changeEnde' => 'zeit_ende',
        'wt_kt_changeAusfall' => 'ausfall', 'wt_kt_changeKursort' => 'ort', 'wt_kt_changeBemerkung' => 'bemerkungen', 'wt_kt_changeDozent' => 'dozent'
    );

    foreach ($checkBoxen as $post => $objname) {
      if (PostOperations::getVarValue($post) == 1) {
        if ($objname == 'zeit_beg') {
          $changedFields[] = 'ue';
        } elseif ($objname == 'zeit_ende') {
          $changedFields[] = 'minuten';
          $changedFields[] = 'pause';
        }
        $changedFields[] = $objname;
      }
    }

    if (\in_array('bearbeiter', $changedFields)) { 
      unset($changedFields['bearbeiter']);
    }

    return $changedFields;
  }

  public function getKursTagIdsFromPost()
  {
    return explode(';', PostOperations::getVarValue('wt_kt_sammelids'));
  }

  public function getChangeObjFromPost()
  {
    $change = new stdClass();
    $change->date = PostOperations::getVarValue('wt_kt_changeDate_val');
    $change->bemerkung = PostOperations::getVarValue('wt_kt_changeBemerkung_val');
    $change->kursort = PostOperations::getVarValue('wt_kt_changeKursort_val');
    $change->ausfall = PostOperations::getVarValue('wt_kt_changeAusfall_val');
    $change->beginn = PostOperations::getVarValue('wt_kt_changeBeginn_val', null);
    $change->ende = PostOperations::getVarValue('wt_kt_changeEnde_val', null);
    $change->pause = PostOperations::getVarValue('wt_kt_changePause_val', null);
    $change->minuten = PostOperations::getVarValue('wt_kt_changeMinuten_val', null);
    $change->ue = PostOperations::getVarValue('wt_kt_changeUe_val', null);

    return $change;
  }

  
  public function doSammelaenderung4Termine()
  {
    $result = '';
    $allgSettings = AllgSettingsAPI::getAllgSettings();

    $changedFields = $this->getChangedFieldsFromPost();
    $ktids = $this->getKursTagIdsFromPost();
    $change = $this->getChangeObjFromPost();

    if (count($changedFields) == 0 || count($ktids) == 0) {
      
      $result .= HTMLOperations::getInfoBox('<div class="infobox_text">' . CleanOperations::cleanStringForHtml($allgSettings->failNoChangesMsgKursplanung) . '</div>', 'Hinweis', 'in_background');

      return $result;
    }

    try {
      $this->doSammelaenderung4TermineByParams($changedFields, $ktids, $change);

      $result .= HTMLOperations::getSuccessBox('<div class="successbox_text">' . CleanOperations::cleanStringForHtml($allgSettings->successMsgKursplanung) . '</div>', 'Übermittlung erfolgreich', 'in_background');
    } catch (AbgleichApiException $aae) {
      Logger::logg('Kurstagkorrektur - folgende Exception ist aufgetreten: ' . $aae->getMessage() . ' [' . $aae->getTraceAsString() . ']', 200);

      $result .= '<h1 class="headline status" id="ktform_message">';
      if ($aae->errorType == AbgleichApiResult::KURSTAG_KORREKTUR_KEINE_EINGETRAGEN) {
        $result .= HTMLOperations::getAlertBox('<div class="alertbox_text">' . CleanOperations::cleanStringForHtml($allgSettings->failMsgKursplanungKeineEingetr) . BR_WT
                    . CleanOperations::cleanStringForHtml($this->getFailedKT($aae->errorReason)) . '</div>', 'Fehler', 'in_background');
      } elseif ($aae->errorType == AbgleichApiResult::KURSTAG_KORREKTUR_TEILWEISE_EINGETRAGEN) {
        $result .= HTMLOperations::getAlertBox('<div class="alertbox_text">' . CleanOperations::cleanStringForHtml($allgSettings->failMsgKursplanungEinigeEingetr) . BR_WT
                    . CleanOperations::cleanStringForHtml($this->getFailedKT($aae->errorReason)) . '</div>', 'Achtung', 'in_background');
      } elseif ($aae->errorType == AbgleichApiResult::CONFLICT) {
        $result .= HTMLOperations::getAlertBox('<div class="alertbox_text">' . CleanOperations::cleanStringForHtml($allgSettings->failSubmitMsgConflict) . '</div>', 'Fehler', 'in_background');
      } else {
        $result .= HTMLOperations::getAlertBox('<div class="alertbox_text">' . CleanOperations::cleanStringForHtml($allgSettings->failSubmitMsgKursplanung) . '</div>', 'Fehler', 'in_background');
      }
      $result .= '</h1>';
    } catch (Exception $e) {
      Logger::logg('Kurstagkorrektur - folgende Exception ist aufgetreten: ' . $e->getMessage() . ' [' . $e->getTraceAsString() . ']', 200);
      $result .= HTMLOperations::getAlertBox('<div class="alertbox_text">' . CleanOperations::cleanStringForHtml($allgSettings->failSubmitMsgKursplanung) . '</div>', 'Fehler', 'in_background');
    }

    return $result;
  }

  

  
  public function doSammelaenderung4TermineByParams($changedFields, $ktids, $change)
  {
    
    $dbwkt = new DBWorkKurseTageWT();
    $kurstage = $dbwkt->getKurstageFromIDs($ktids, false);

    $tupelsForApi = array();
    $changeTimes = false;
    $realChangedFields = $changedFields;
    
    foreach ($kurstage as $kurstag) {
      $originalKurstag = $kurstag->copy();
      
      foreach ($changedFields as $fieldName) {
        switch ($fieldName) {
          case 'datum':
            $kurstag->setValue2Var('datum', \DateTimeOperations::addDays($kurstag->datum, $change->date));
            $realChangedFields[] = 'wotag';
            break;
          case 'bemerkungen':
            $kurstag->bemerkungen = $change->bemerkung;
            break;
          case 'ort':
            $kurstag->ort = $change->kursort;
            break;
          case 'ausfall':
            $kurstag->ausfall = $change->ausfall;
            break;
          case 'zeit_beg':
          case 'zeit_ende':
          case 'ue':
          case 'minuten':
          case 'pause':
            $changeTimes = true;
            break;
          case 'dozent':
            $kurstag->dnr = $change->dozent;
            break;
          case 'bearbeiter':
            $kurstag->bearbeiter = $change->bearbeiter;
            break;
        }
      }
      
      if ($changeTimes) {
        $kurstag = self::aktualisiereKurstagZeit(
          $kurstag,
          $change->beginn,
          $change->ende,
          $change->pause,
          $change->minuten,
          $change->ue
        );
      }

      
      
      $tupelsForApi[] = new Tuple($kurstag, $realChangedFields, $originalKurstag);
    }

    if (SessionOperations::isDmzBetrieb()) {
      

      $korrekturAPI = new KurskorrekturAPI();
      
      $korrekturAPI->correctKurstage($tupelsForApi);

      
      foreach ($tupelsForApi as $tupel) {
        $dbwkt->updateKurstag($tupel->getFirst(), true);
      }
    } else {
      
      foreach ($tupelsForApi as $tupel) {
        $dbwkt->updateKurstag($tupel->getFirst(), false);
      }
    }
  }

  
  public function getFailedKT($errorReason, $dbwkt = null)
  {
    if ($dbwkt == null) {
      $dbwkt = new DBWorkKurseTage();
    }
    
    $ktList = trim(\StringOperations::strrchr($errorReason, ':'), ' :');
    $retour = '';
    $ktToken = strtok($ktList, ' ,');
    while ($ktToken !== false) {
      $kt = $dbwkt->getKurstag($ktToken);
      $retour .= $kt->datum . ' ' . $kt->zeit_beg . BR_WT;
      $ktToken = strtok(' ,');
    }

    return $retour;
  }

  

  
  public static function getKurstag4Klassenbuch($pKtId)
  {
    $result = '';

    if (SessionOperations::isDmzBetrieb()) {
      try {
        $node = new XMLNode('id', $pKtId);

        $abgleichApi = new AbgleichAPI();
        $resultAbgleich = $abgleichApi->sendeNachricht(
          AbgleichAPI::ABGLEICH_GETKURSTAG4KLASSENBUCH,
          new Nutzlast($node)
        );

        $result = JsonOperations::getFromString($resultAbgleich->reason);
      } catch (Exception $e) {
        $result = HTMLOperations::getAlertBox('Es konnten nicht die aktuellsten Daten geladen werden. Falls dieses Problem weiterhin besteht, wenden Sie sich bitte an uns.', 'Hinweis');
        Logger::logg('ABGLEICH_GETKURSTAG4KLASSENBUCH - Folgende Exception ist aufgetreten: ' . $e->getMessage() . ' [' . $e->getTraceAsString() . ']', 200);
      }
    }

    return $result;
  }

  
  public static function updateKurstag4Klassenbuch($pKurstag, $pKurstag4Klassenbuch)
  {
    if (!empty($pKurstag4Klassenbuch)) {
      $pKurstag->bemerkungen = $pKurstag4Klassenbuch->Text;
      $pKurstag->klassenbuchtext = $pKurstag4Klassenbuch->Klassenbuchtext;
      $pKurstag->klassenbuchueok = $pKurstag4Klassenbuch->Klassenbuchueok;
      $pKurstag->klassenbuchabwue = MathOperations::floatToString($pKurstag4Klassenbuch->Klassenbuchabwue);
      $pKurstag->klassenbuchgrund = $pKurstag4Klassenbuch->Klassenbuchgrund;
    }

    return $pKurstag;
  }
}