<?php

class BaseView extends View
{
  public string $Title = '';

  function ShowLocaleSelector()
  {
    $Output = ' <select onchange="window.location=this.value">';
    foreach (Core::Cast($this->System)->LocaleManager->Available as $Locale)
    {
      $Remaining = substr($_SERVER["REQUEST_URI"], strlen(Core::Cast($this->System)->BaseURL));
      if (substr($Remaining, 1, strlen($Locale['Code'].'/')) == Core::Cast($this->System)->LocaleManager->LangCode.'/')
        $Remaining = substr($Remaining, strlen('/'.$Locale['Code']));
      if ($Locale['Code'] == Core::Cast($this->System)->LocaleManager->CurrentLocale->Texts->Code) $Selected = ' selected="selected"';
        else $Selected = '';
      $Remaining = Core::Cast($this->System)->TranslateReverseURL($Remaining, Core::Cast($this->System)->LocaleManager->LangCode);

      $URL = Core::Cast($this->System)->LinkLocale($Remaining, $Locale['Code']);
      $Output .= '<option title="" value="'.$URL.'"'.$Selected.' onchange="this.form.submit()">'.$Locale['Title'].'</option>';
    }
    $Output .= '</select><noscript><span><input type="submit" value="Submit"/></span></noscript>';

    return $Output;
  }

  function ShowTopBar()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '<div class="Menu">';
    if (isset($User))
    {
      if (!$User->Licence(LICENCE_USER))
        $Output .= '<div class="advert">'.Core::Cast($this->System)->Config['Web']['Advertisement'].'</div>';
    }
    $Output .= '<span class="MenuItem"></span><span class="MenuItem2">';

    // Show bars items
    $Bar = '';
    foreach (Core::Cast($this->System)->Bars['Top'] as $BarItem)
      $Bar .= call_user_func($BarItem);
    if (trim($Bar) != '') $Output .= $Bar;
      else $Output .= '&nbsp;';

    $Output .= $this->ShowLocaleSelector();
    $Output .= '</span></div>';
    return $Output;
  }

  function ShowMainMenu()
  {
    $User = ModuleUser::Cast($this->System->GetModule('User'))->User;
    $Output = '<strong>'.T('Menu').':</strong>'.
      '<div class="verticalmenu"><ul>';
    foreach (Core::Cast($this->System)->Menu as $MenuItem)
    {
      if (!isset($User) or $User->Licence($MenuItem['Permission']))
      {
        if (isset($MenuItem['Click'])) $OnClick = ' onclick="'.$MenuItem['Click'].'"';
        else $OnClick = '';
        if ($MenuItem['Icon'] != '') $Icon = '<img src="'.$this->System->Link('/images/menu/'.$MenuItem['Icon']).'"/>';
        else $Icon = '';
        $Output .= '<li>'.$Icon.'<a class="verticalmenua" title="'.$MenuItem['Hint'].'" href="'.
          $MenuItem['Link'].'"'.$OnClick.'>'.$MenuItem['Title'].'</a></li>';
      }
    }
    $Output .= '</ul></div>';
    return $Output;
  }

  function ShowHeader()
  {
    $Output = ''.
    '<!DOCTYPE html>'.
    '<html>'.
    '<head>'.
    '<meta http-equiv="content-type" content="text/html; charset='.Core::Cast($this->System)->Config['Web']['Charset'].'" />'.
    '<meta name="keywords" content="'.Core::Cast($this->System)->Config['Web']['Keywords'].'" />'.
    '<meta name="description" content="'.Core::Cast($this->System)->Config['Web']['Description'].'" />'.
    '<meta name="robots" content="all" />'.
    '<meta name="viewport" content="width=device-width, initial-scale=1">'.
    '<link rel="stylesheet" href="'.$this->System->Link('/style/style.css').'" type="text/css" media="all" />'.
    '<script type="text/javascript" src="'.$this->System->Link('/style/global.js').'"></script>'.
    '<link rel="shortcut icon" href="'.$this->System->Link('/images/favicon.ico').'" />';

    // Show page headers
    $Bar = '';
    foreach (Core::Cast($this->System)->PageHeaders as $Item)
    {
      $Output .= call_user_func($Item);
    }

    $Title = Core::Cast($this->System)->Config['Web']['Title'];
    if ($this->Title != '') $Title = $this->Title.' - '.$Title;
    $Output .= '<title>'.$Title.'</title>'.
    '<script src="'.$this->System->Link('/style/respond.js').'"></script>'.
    '</head><body>';

    $Output .= $this->ShowTopBar();
    $Output .= '<table class="page"><tr><td class="menu">';
    $Output .= $this->ShowMainMenu();

    // Show bars items
    $Bar = '';
    foreach (Core::Cast($this->System)->Bars['Left'] as $BarItem)
      $Bar .= call_user_func($BarItem);
    if (trim($Bar) != '') $Output .= $Bar;
      else $Output .= '&nbsp;';

    $Output .= '</td><td id="border-left"></td><td class="content">';
    return $Output;
  }

  function ShowFooter()
  {
    global $ScriptStartTime, $Revision, $ReleaseDate, $Version;

    $ScriptGenerateDuration = round(GetMicrotime() - $ScriptStartTime, 2);

    $Output = '</td>';
    $Output .= '<td class="menu2">';
    // Show bars items
    $Bar = '';
    foreach (Core::Cast($this->System)->Bars['Right'] as $BarItem)
      $Bar .= call_user_func($BarItem);
    if (trim($Bar) != '') $Output .= $Bar;
      else $Output .= '&nbsp;';
    $Output .= '</td>';
    $Output .= '</tr><tr>'.
      '<td colspan="4" class="page-bottom">'.T('Version').': '.$Version.' '.T('Revision').': '.$Revision.' ('.Core::Cast($this->System)->HumanDate($ReleaseDate).')'.
      ' &nbsp; <a href="https://app.zdechov.net/wowpreklad/browser/trunk">'.T('Source code').'</a> &nbsp; '.
      '<a href="https://app.zdechov.net/wowpreklad/log/trunk?verbose=on">'.T('Changelog').'</a> &nbsp; '.
      Core::Cast($this->System)->Config['Web']['WebCounter'];

    $Output .= '</td></tr>';
    if (Core::Cast($this->System)->Config['Web']['ShowRuntimeInfo'] == true)
      $Output .= '<tr><td colspan="3" style="text-align: center;">'.T('Generating duration').': '.
    $ScriptGenerateDuration.' s / '.ini_get('max_execution_time').' s &nbsp;&nbsp; '.T('Used memory').': '.
    HumanSize(memory_get_peak_usage(FALSE)).' / '.ini_get('memory_limit').'B &nbsp;&nbsp; <a href="http://validator.w3.org/check?uri='.
    htmlentities('http://'.$_SERVER['HTTP_HOST'].GetRequestURI().'?'.$_SERVER['QUERY_STRING']).'">HTML validator</a></td></tr>';
    $Output .= '</table>'.
      '</body>'.
      '</html>';
    return $Output;
  }

  function ShowPage($Content)
  {
    $Output = $this->ShowHeader().$Content.$this->ShowFooter();
    if (Core::Cast($this->System)->Config['Web']['FormatOutput'])
      $Output = $this->FormatOutput($Output);
    return $Output;
  }

  function FormatOutput($s)
  {
    $out = '';
    $nn = 0;
    $n = 0;
    while ($s != '')
    {
      $start = strpos($s, '<');
      $end = strpos($s, '>');
      if ($start != 0)
      {
        $end = $start - 1;
        $start = 0;
      }
      $line = trim(substr($s, $start, $end + 1));
      if (strlen($line) > 0)
        if ($line[0] == '<')
        {
          if ($s[$start + 1] == '/')
          {
            $n = $n - 2;
            $nn = $n;
          } else
          {
            if (strpos($line, ' ')) $cmd = substr($line, 1, strpos($line, ' ') - 1);
            else $cmd = substr($line, 1, strlen($line) - 2);
            //echo('['.$cmd.']');
            if (strpos($s, '</'.$cmd.'>')) $n = $n + 2;
          }
        }// else $line = '['.$line.']';
        //if ($line != '') echo(htmlspecialchars(str_repeat(' ',$nn).$line."\n"));
        if ($nn < 0) $nn = 0;
        if ($line != '') $out .= (str_repeat(' ', $nn).$line."\n");
        $s = substr($s, $end + 1, strlen($s));
        $nn = $n;
    }
    return $out;
  }
}
