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

class ContentNavTools extends ContentSubNavigation
{
  public function getNavItems()
  {
    $navItems = array();

    
    $item = new NavItem();
    $item->name = 'Einstellungen';
    $item->objectName = $this->getObjectNameByAccess('tools', 'ContentSettingsTools');
    $nav = new ContentNavSettingsTools();
    $item->subItems = $nav->getNavItems();
    if (count($item->subItems) > 0) {
      array_push($navItems, $item);
    }

    $item = new NavItem();
    $item->name = 'Felderanordnung responsive';
    $item->objectName = $this->getObjectNameByAccess('tools', 'ContentWssTools');
    $nav = new ContentNavWssTools();
    $item->subItems = $nav->getNavItems();
    if (count($item->subItems) > 0) {
      array_push($navItems, $item);
    }

    
    $item = new NavItem();
    $item->name = 'Sichten responsive';
    $item->objectName = $this->getObjectNameByAccess('tools', 'ContentSightsTools');
    $nav = new ContentNavSightsTools();
    $item->subItems = $nav->getNavItems();
    array_push($navItems, $item);

    $item = new NavItem();
    $item->name = 'Sonstige Dateien';
    $item->objectName = $this->getObjectNameByAccess('tools', 'ContentNavCssAndJsTools');
    $nav = new ContentNavCssAndJsTools();
    $item->subItems = $nav->getNavItems();
    \array_push($navItems, $item);

    
    $item = new NavItem();
    $item->name = 'Zugang mit ausgewähltem Login';
    $item->objectName = $this->getObjectNameByAccess('tools', 'ContentLoginTools');
    array_push($navItems, $item);

    if (SessionOperations::isNichtReplikat()) {
      $item = new NavItem();
      $item->name = 'Rechte';
      $item->objectName = $this->getObjectNameByAccess('tools', 'ContentRechteTools');
      array_push($navItems, $item);
    }

    return $navItems;
  }
}

class ContentSettingsNavTools extends ContentSettings
{
  public function __construct($pConfigFile = '')
  {
    $this->settingConverter = new LibSettingTools();
    $this->action = 'settings_content_nav_tools';
    parent::__construct($pConfigFile);
  }
}

class ContentSettingsTNlisten extends ContentSettings
{
  public function __construct($pConfigFile = '', $pToolId = '')
  {
    $this->settingConverter = new LibSettingTnListe();
    $this->settingConverter->toolID = $pToolId;
    
    
    $this->action = 'settings_druck_von_teilnehmerlisten';
    parent::__construct($pConfigFile);
  }
}

class ContentSettingsDrucklisten extends ContentSettings
{
  public function __construct($pConfigFile = '', $pToolId = '')
  {
    $this->settingConverter = new LibSettingDruckListe();
    $this->settingConverter->toolID = $pToolId;
    
    
    $this->action = 'settings_druck_listen';
    parent::__construct($pConfigFile);
  }
}

class ContentSettingsSys extends ContentSettings
{
  public function __construct($pConfigFile = '')
  {
    $this->settingConverter = new LibSettingSys();
    
    
    $this->action = 'settings_allgemein';
    parent::__construct($pConfigFile);
  }
}

class ContentSightsTools extends Content
{
  private $currentSight;

  public function __construct($pSight = null)
  {
    $this->currentSight = $pSight;
  }

  public function getContent()
  {
    
    $smarty = $this->getSmarty();
    $errors = array();
    if (PostOperations::getVarValue('savesight', false) !== false) {
      $lib = new LibSightsTools();
      $sight = $lib->getSightFromPost();
      $lib->saveSight($sight);

      foreach ($sight->getParts() as $part) {
        $parser = new \Kufer\Web\Classes\Scripting3\Parser($part);
        try {
          $parser->parseToPHP(static function($varname) {
            return \Exportadapter::permanentVarUpdate($varname);
          });
        } catch (\Exception $ex) {
        }

        if (!empty($parser->getErrors())) {
          array_push($errors, ...$parser->getErrors());
        }
      }
    }

    
    $si = $this->currentSight;
    if ($si != null) {
      $libTools = new LibSightsTools();
      $sight = $si->returnSight();
      $smarty->assign('selflink', $this->getPageLink());

      $smarty->assign('sightloaded', true);
      $smarty->assign('sightid', $sight->id);
      if (isset($sight->toolid)) {
        $smarty->assign('toolid', $sight->toolid);
      }
      $smarty->assign('sightversion', $sight->version);
      $smarty->assign('description', $sight->description);

      $parts = array();
      if ($si->showHeader) {
        array_push($parts, array('id' => 'header', 'name' => $si->nameHeader, 'value' => $libTools->encode($si->getHeader())));
      }
      if ($si->showBody) {
        array_push($parts, array('id' => 'body', 'name' => $si->nameBody, 'value' => $libTools->encode($si->getBody())));
      }
      if ($si->showFooter) {
        array_push($parts, array('id' => 'footer', 'name' => $si->nameFooter, 'value' => $libTools->encode($si->getFooter())));
      }
      if ($si->showNoColumn) {
        array_push($parts, array('id' => 'nocolumn', 'name' => $si->nameNoColumn, 'value' => $libTools->encode($si->getNoColumn())));
      }
      if ($si->showNoData) {
        array_push($parts, array('id' => 'nodata', 'name' => $si->nameNoData, 'value' => $libTools->encode($si->getNoData())));
      }

      $smarty->assign('sightparts', $parts);
    } else {
      $smarty->assign('sightloaded', false);
      $smarty->assign('sightspath', BASEDIR . CleanOperations::cleanStringForHtml(SIGHTS_PATH));
    }

    $smarty->assign('errors', $errors);

    return $smarty->fetch('tools/sight.html');
  }
}

class ContentLoginTools extends Content
{
  public function getContent()
  {
    $smarty = $this->getSmarty();
    $meldung = '';
    $success = false;

    $login = trim(PostOperations::getVarValue('username'));
    if ($login !== '') {
      $dbwUser = new DBWorkUser();
      $user = $dbwUser->getUserbyLogin($login);
      if (isset($user->id)) {
        SecurityOperations::setWtUserToSession($login, $user->getIdentifier(), $user->admin);
        
        $settings = ToolSettingsAPI::getToolSettings(0);
        if ($settings->loginStammHoerer) {
          SessionOperations::logInCurrentToolsTnAsStammhoerer();
        }
        $success = true;
      } else {
        $meldung .= 'Das angegebene Login existiert nicht!';
      }
    }

    $smarty->assign('login', $login);
    $smarty->assign('selflink', $this->getPageLink());
    $smarty->assign('meldung', $meldung);
    $smarty->assign('loginErfolgreich', $success);

    return $smarty->fetch('tools/login.html');
  }
}

class ContentSightSearchTools extends Content
{
  private $navItems;

  
  private function getLinkForSight($pSight)
  {
    if (!isset($this->navItems)) {
      $navSights = new ContentNavSightsTools();
      $this->navItems = $navSights->getNavItemsProcessed();
    }

    foreach ($this->navItems as $item) {
      foreach ($item->subItems as $subItem) {
        $link = $this->getLinkFromNavItem($subItem, $pSight);
        if (!is_null($link)) {
          return $link;
        }
      }
    }

    throw new Exception('Die Sicht ' . $pSight->id . ' ist im Navigationsmenü nicht enthalten!');
  }

  private function getLinkFromNavItem($pItem, $pSight)
  {
    if (count($pItem->subItems) > 0) {
      foreach ($pItem->subItems as $subItem) {
        $link = $this->getLinkFromNavItem($subItem, $pSight);
        if (!is_null($link)) {
          return $link;
        }
      }

      return null;
    } elseif ($pItem->objectParam->id == $pSight->id && $pItem->objectParam->toolid == $pSight->toolid) {
      return $pItem->link;
    } else {
      return null;
    }
  }

  public function getContent()
  {
    $lib = new LibSightsTools();
    $smarty = $this->getSmarty();
    $searchword = SessionOperations::getVarValueIntern('admin_sightsearchword', '');
    $searchword = trim(PostOperations::getVarValue('sightsearch_searchword', $searchword));
    SessionOperations::setVarValueIntern('admin_sightsearchword', $searchword);

    
    $smarty->assign('start', $searchword != '');
    if ($searchword != '') {
      $sights = $lib->searchSight($searchword);
      $smarty->assign('count', count($sights));
      $items = array();
      foreach ($sights as $sight) {
        $items[] = array(
        'id' => $sight->id,
        'title' => $sight->name,
        'link' => $this->getLinkForSight($sight),
        'menu' => $sight->configFile->longName
        );
      }
      $smarty->assign('sights', $items);
    }

    $smarty->assign('selflink', $this->getPageLink());
    $smarty->assign('searchword', CleanOperations::cleanStringForHtml($searchword));

    return $smarty->fetch('tools/sight_search.html');
  }
}

class ContentWssTools extends Content
{
  private $currentSight;
  private $title;

  public function __construct($pParam = null)
  {
    $this->currentSight = $pParam['sightId'];
    $this->title = $pParam['name'];
  }

  public function getContent()
  {
    $wssInFiles = new \Kufer\Web\KuferTools\Utils\WssInFiles();
    
    
    if (PostOperations::isDefined('felder')) {
      $felderAry = JsonOperations::decodeJustString(PostOperations::getVarValue('felder'));
      if (is_array($felderAry)) {
        $wssAry = array();
        foreach ($felderAry as $feld) {
          if ($feld->wsfId > 0) {
            $wss = new Column();
            $wss->sight_field_id = $feld->wsfId;
            $wss->title = $feld->label;
            $wss->head = $feld->head ?? '';
            $wss->tail = $feld->tail ?? '';
            $wss->bold = $feld->bold ?? 0;
            $wss->maxlength = $feld->maxlength;
            $wss->fontsize = $feld->fontsize;
            $wss->textfarbe = $feld->textfarbe ?? '';
            $wss->ausrichtung = $feld->ausrichtung ?? '';
            $wss->mandatory_field = $feld->mandatory ?? 0;
            $wss->wenn_leer = $feld->wenn_leer ?? '';
            $wss->responsive = 'W';
            $wssAry[] = $wss;
          }
        }

        $wssInFiles->saveWss($this->currentSight, $wssAry);
      }
    }

    $eingestellteSpalten = $this->normalizeEingestellteSpalte($wssInFiles->getWss(
      new \Kufer\Web\KuferTools\Basis\UseCaseBuilder\SpecificToolSection(-1, -1),
      new \ToolSettings(),
      $this->currentSight
    ));
    $smarty = $this->getSmarty();
    $smarty->assign('selflink', $this->getPageLink());
    $smarty->assign('eingestellteSpalten', $eingestellteSpalten);
    $smarty->assign('sightId', $this->currentSight);
    $smarty->assign('title', $this->title);

    return $smarty->fetch('tools/wss.html');
  }

  private function normalizeEingestellteSpalte(array $eingestellteSpalten)
  {
    foreach ($eingestellteSpalten as $wss) {
      if (!isset($wss->wenn_leer)) {
        $wss->wenn_leer = '';
      }
    }

    return $eingestellteSpalten;
  }
}

class ContentNavCssAndJsTools extends ContentSubNavigation
{
  public function getNavItems()
  {
    $navItems = array();

    $file = \FSOperations::path(BASEDIR, 'kufertools/settings/user/layout/css/eigeneCssAngaben.css');
    $this->makeSureFileExists($file);
    $item = new NavItem();
    $item->name = \basename($file);
    $item->objectName = 'ContentCss';
    $item->objectParam = $file;
    \array_push($navItems, $item);

    $file = \FSOperations::path(BASEDIR, 'kufertools/settings/user/layout/js/eigeneJsAngaben.js');
    $this->makeSureFileExists($file);
    $item = new NavItem();
    $item->name = \basename($file);
    $item->objectName = 'ContentJs';
    $item->objectParam = $file;
    \array_push($navItems, $item);

    return $navItems;
  }

  private function makeSureFileExists($file): void
  {
    $dir = \dirname($file);
    if (!\is_dir($dir)) {
      \FSOperations::mkDir($dir);
    }
    if (!\file_exists($file)) {
      \file_put_contents($file, '');
    }
  }
}