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

namespace Kufer\Web\Classes\Rss;

class RssFeedMaileon extends RssFeed
{
  public static function getFeedname(): string
  {
    return 'maileon';
  }

  protected function useCache(): bool
  {
    return false;
  }

  
  protected function getMainRss($settings): Rss
  {
    $rss = new Rss();
    $rss->title = 'Maileon-RSS-Channel';
    $rss->link = 'http' . (\RequestOperations::isHttps() ? 's' : '') . '://' . \RequestOperations::getServerName();
    $rss->description = 'Kursinformationen für das Maileon-Backend';
    $rss->pubdate = date('r');
    $rss->namespaceAttributes = $this->getNamespaceAttributes($settings);

    return $rss;
  }

  protected function getRssItems(\KursWebUebersichtSettings $pSettings): array
  {
    $params = RssFeedMaileonParams::fromGetRequest();
    $dbwKurse = \DBWorkKurseINetAktiv::getDefaultInstance();
    $dbwKurse->newSearch();
    $dbwKurse->fromobject->semester = $pSettings->semlist;
    $dbwKurse->fromobject->kurse2->newsl_weitergabe = true;

    if ($params->KursBeginntAb !== 0) {
      $ab = \DateTimeObj::getNow()->addDays($params->KursBeginntAb);
      $dbwKurse->fromobject->beginn_dat = $ab;
    }
    if ($params->KursBeginntBis !== 0) {
      $bis = \DateTimeObj::getNow()->addDays($params->KursBeginntBis);
      $dbwKurse->toobject->beginn_dat = $bis;
    }

    $dbwKurse->orderby = 'beginn_dat';
    $dbwKurse->orderby2 = 'beginn';
    $dbwKurse->orderbyasc = $dbwKurse->orderbyasc2 = $params->sortAuf;

    $kurse = $dbwKurse->getKurse();
    $minPlaetzeFrei = max(1, $params->minPlaetzeFrei);
    $result = array();
    
    foreach ($kurse as $kurs) {
      $kursIsBzglPlaetzeOk = true;
      if ($params->maxPlaetzeFrei > 0) {
        if ($kurs->istPlatzFuer($params->maxPlaetzeFrei + 1, 0)) {
          $kursIsBzglPlaetzeOk = false;
        }
      }
      if (!$kurs->istPlatzFuer($minPlaetzeFrei, 0)) {
        $kursIsBzglPlaetzeOk = false;
      }
      if ($kursIsBzglPlaetzeOk) {
        $result[] = $this->convertKursToRssItem($kurs);
      }
    }

    return $result;
  }

  private function convertKursToRssItem(\Kurs $pKurs): \RssItem
  {
    $item = new \RssItem();

    $kname = preg_replace('/ /i', '_', $pKurs->kurzbez);

    if (trim($pKurs->kurzbez) !== '') {
      $item->title = $pKurs->kurzbez;
    } else {
      $item->title = $pKurs->titel;
    }

    if (trim($pKurs->titel) != '') {
      $item->description = $pKurs->titel;
    }
    $item->content = $pKurs->getVarValue('webinfo');

    $exportKurse = new \ExportKursuebersicht();
    $allgSettings = \AllgSettingsAPI::getAllgSettings();

    $item->maileon = new \stdClass();
    $item->maileon->startDate = $pKurs->getVarValue('beginn_dat');
    $item->maileon->endDate = $pKurs->getVarValue('ende_dat');
    $item->maileon->startTime = $pKurs->getVarValue('beginn');
    $item->maileon->endTime = $pKurs->getVarValue('ende');
    $item->maileon->category = \ExportBasis::exportSingleVar('k_kategorie_text', $pKurs, $exportKurse);
    $item->maileon->categorypath = \ExportBasis::exportSingleVar('k_katpfad', $pKurs, $exportKurse);

    $item->maileon->duration = $pKurs->getVarValue('dauer');
    $item->maileon->location = $pKurs->getVarValue('ort');
    $item->maileon->lecturer = \ExportBasis::exportSingleVar('doz_vorname', $pKurs, $exportKurse) . ' ' . \ExportBasis::exportSingleVar('doz_name', $pKurs, $exportKurse);
    $item->maileon->lecturers = $pKurs->getVarValue('dozenten_kommasepariert_titelvornamenachname');
    $item->maileon->branch = $pKurs->getVarValue('aussenst');
    $item->maileon->price = \ExportBasis::exportSingleVar('k_gebuehr', $pKurs, $exportKurse);
    $item->maileon->maxParticipants = \ExportBasis::exportSingleVar('k_teil_max', $pKurs, $exportKurse);
    $item->maileon->currentParticipants = \ExportBasis::exportSingleVar('k_teil_akt', $pKurs, $exportKurse);
    $item->maileon->minParticipants = \ExportBasis::exportSingleVar('k_teil_min', $pKurs, $exportKurse);

    $item->maileon->vorspann = $pKurs->getVarValue('vorspann');
    $item->maileon->nachspann = $pKurs->getVarValue('nachspann');
    $item->maileon->zielgruppe = $pKurs->getVarValue('zielgruppe');
    $item->maileon->voraussetzungen = $pKurs->getVarValue('voraussetzungen');
    $item->maileon->anmeldebedingungen = $pKurs->getVarValue('anmelde');
    $item->maileon->individuelleTerminangaben = $pKurs->getVarValue('individtermine_ausgewertet');
    $item->maileon->terminangabenWeb = $pKurs->getVarValue('termindarstweb');
    $item->maileon->textBeiUndefiniertemKursbeginn = $pKurs->getVarValue('keinkursbeginn');
    $item->maileon->ziel = $pKurs->getVarValue('ziel');
    $item->maileon->methode = $pKurs->getVarValue('methode');
    $item->maileon->textBeiGebuehrNull = $pKurs->getVarValue('kostenfreitxt');
    $item->maileon->ergaenzenderGebuehrenText = $pKurs->getVarValue('gebuehrergaenztext');

    $this->addImage($item, $pKurs->id, 1);
    $this->addImage($item, $pKurs->id, 2);
    $this->addImage($item, $pKurs->id, 3);
    $this->addImage($item, $pKurs->id, 4);
    $this->addImage($item, $pKurs->id, 5);
    $this->addImage($item, $pKurs->id, 6);

    if ($allgSettings->linkkursdetails != '') {
      $item->maileon->weblink = str_replace('{%k_id%}', $pKurs->id, $allgSettings->linkkursdetails);
    } else {
      $item->maileon->weblink = (new \NoCmsAnb())->getKuferWebUrl() . 'webbasys/index.php?kathaupt=11?knr=' . $pKurs->id;
    }

    $item->guid = $pKurs->id;
    $item->pubdate = date('r', $this->getPubDateForId($pKurs->id));

    return $item;
  }

  
  protected function getNamespaceAttributes($settings): string
  {
    return 'xmlns:maileon="http://rssext.maileon.com/"';
  }

  
  private function addImage(\RssItem $item, $knr, $lfdnr): \RssItem
  {
    $foto = \FotoAPI::getFotoByVarname('foto_' . $lfdnr . '_x', 'K', $knr);
    if (!is_null($foto) && !is_null($foto['foto']->nr)) {
      $item->maileon->{'image' . $lfdnr} = \URL::loadCurrent()->getDirectory() . '/' . (new \Kufer\Web\Classes\Export\ExportCalculation\ExportCalcFotos())->resolveVar('link', $foto['foto']);
      $item->maileon->{'image' . $lfdnr . '_subtitle'} = (new \Kufer\Web\Classes\Export\ExportCalculation\ExportCalcFotos())->resolveVar('untertitel', $foto['foto']);
      $item->maileon->{'image' . $lfdnr . '_desc'} = (new \Kufer\Web\Classes\Export\ExportCalculation\ExportCalcFotos())->resolveVar('beschreibung_bf', $foto['foto']);
      $item->maileon->{'image' . $lfdnr . '_copyright'} = (new \Kufer\Web\Classes\Export\ExportCalculation\ExportCalcFotos())->resolveVar('copyright', $foto['foto']);
    }

    return $item;
  }
}

class RssFeedMaileonParams
{
  public $minPlaetzeFrei;
  public $maxPlaetzeFrei;
  public $KursBeginntBis;
  public $KursBeginntAb;
  public $sortAuf;


  
  

  public static function fromGetRequest(): self
  {
    $self = new self();
    $self->minPlaetzeFrei = \GetOperations::getInt('minPlaetzeFrei', 0);
    $self->maxPlaetzeFrei = \GetOperations::getInt('maxPlaetzeFrei', 0);
    $self->KursBeginntBis = \GetOperations::getInt('KursBeginntBis', 0);
    $self->KursBeginntAb = \GetOperations::getInt('KursBeginntAb', 0);
    $self->sortAuf = \GetOperations::getVarValue('sortierung') === 'auf';

    return $self;
  }
}