<?php
namespace front\view;

class Site
{
  const menu_pattern      = '/MENU:[0-9]*/';
  const main_menu_pattern = '/MENU_GLOWNE:[0-9]*/';
  const submenu_pattern   = '/SUBMENU:[0-9]*/';
  const container_pattern = '/KONTENER:[0-9]*/';
  const language_pattern  = '/LANG:[a-zA-Z0-9_-]*/';
  const news_pattern      = '/AKTUALNOSCI:([0-9]*)((:([0-9]*))?)/';
  const article_pattern   = '/ARTYKUL:[0-9]*/';
  const maps_pattern      = '/\[MAPA](.*)\[\/MAPA]/';

  public static function show()
  {
    global $page, $settings, $lang, $lang_id;

    if ( \S::get( 'article' ) )
      $layout = \front\factory\Layouts::article_layout( \S::get( 'article' ) );

    if ( !$layout )
      $layout = \front\factory\Layouts::active_layout( $page['id'] );

    if ( \S::get( 'layout_id' ) )
      $layout = \front\factory\Layouts::layout_details( \S::get( 'layout_id' ) );

    if ( $settings['devel'] == true and file_exists( 'devel.html' ) )
      $html = file_get_contents( 'devel.html' );
    else
    {
      if ( \S::is_mobile() and !empty( $layout['m_html'] ) )
        $html = $layout['m_html'];
      else
        $html = $layout['html'];
    }

    if ( $settings['google_search_console'] )
      $html = str_replace( '</head>', '<meta name="google-site-verification" content="' . $settings['google_search_console'] . '"></head>', $html );

    if ( \S::get_session( 'contrast' ) )
      $html = str_replace( '</head>', '<link rel="stylesheet" type="text/css" href="/layout/contrast.css"></head>', $html );

    if ( $settings['facebook_link'] )
      $html = str_replace( '</body>', \front\view\Site::facebook( $settings['facebook_link'] ) . '</body>', $html );

    if ( strpos( $html, '[BANER_STRONA_GLOWNA]' ) === false )
      $html = str_replace( '</body>', '[BANER_STRONA_GLOWNA]' . '</body>', $html );

    if ( strpos( $html, '[WIDGET_TELEFON]' ) === false )
      $html = str_replace( '</body>', '[WIDGET_TELEFON]' . '</body>', $html );

    if ( $settings['ssl'] == true )
    {
      $layout['css'] = str_replace( 'http://', 'https://', $layout['css'] );
      $layout['js'] = str_replace( 'http://', 'https://', $layout['js'] );
      $layout['m_css'] = str_replace( 'http://', 'https://', $layout['m_css'] );
      $layout['m_js'] = str_replace( 'http://', 'https://', $layout['m_js'] );
    }

    $html = str_replace( '[COPYRIGHT]',           \front\view\Site::copyright(),  $html );
    $html = str_replace( '[BANER_STRONA_GLOWNA]', \front\view\Banners::main_banner( \front\factory\Banners::main_banner() ), $html );
    $html = str_replace( '[BANERY]',              \front\view\Banners::banners( \front\factory\Banners::banners() ), $html );
    $html = str_replace( '[LICZNIK_ODWIEDZIN]',   \front\view\Site::visit_counter( \S::get_session( 'visits' ) ), $html );
    $html = str_replace( '[WYSZUKIWARKA]',        \front\view\Search::search_form(), $html );
    $html = str_replace( '[CHMURA_TAGOW]',        \front\view\Articles::tags_cloud(), $html );
    $html = str_replace( '[KONTRAST]',            \front\view\Site::contrast(), $html );
    $html = str_replace( '[NEWSLETTER]',          \front\view\Newsletter::newsletter(), $html );
    $html = str_replace( '[WIDGET_TELEFON]',      $settings['widget_phone'] == 1 ? \front\view\Site::widget_phone() : '', $html );

    if ( \S::is_mobile() and !empty( $layout['m_html'] ) )
      $html = str_replace( '[CSS]',           $layout['m_css'],                 $html );
    else
      $html = str_replace( '[CSS]',           $layout['css'],                   $html );

    if ( \S::is_mobile() and !empty( $layout['m_html'] ) )
      $html = str_replace( '[JAVA_SCRIPT]',   $layout['m_js'],                  $html );
    else
      $html = str_replace( '[JAVA_SCRIPT]',   $layout['js'],                    $html );

    preg_match_all( self::menu_pattern, $html, $menu );
    if ( is_array( $menu[0] ) ) foreach( $menu[0] as $menu_tmp )
    {
      $menu_tmp = explode( ':', $menu_tmp );
      $html = str_replace( '[MENU:' . $menu_tmp[1] . ']', \front\view\Menu::menu(
                                                            \front\factory\Menu::menu_details( $menu_tmp[1] ), $page['id']
                                                          ), $html );
    }

    preg_match_all( self::main_menu_pattern, $html, $menu );
    if ( is_array( $menu[0] ) ) foreach( $menu[0] as $menu_tmp )
    {
      $menu_tmp = explode( ':', $menu_tmp );
      $html = str_replace( '[MENU_GLOWNE:' . $menu_tmp[1] . ']', \front\view\Menu::main_menu(
                                                            \front\factory\Menu::menu_details( $menu_tmp[1] ), $page['id']
                                                          ), $html );
    }

    preg_match_all( self::submenu_pattern, $html, $submenu );
    if ( is_array( $submenu[0] ) ) foreach( $submenu[0] as $submenu_tmp )
    {
      $submenu_tmp = explode( ':', $submenu_tmp );
      $html = str_replace( '[SUBMENU:' . $submenu_tmp[1] . ']', \front\view\Menu::submenu(
                                                                  \front\factory\Menu::submenu_details( $submenu_tmp[1] ), $page['id'], $submenu_tmp[1]
                                                                ), $html );
    }

    preg_match_all( self::container_pattern, $html, $container_list );
    if ( is_array( $container_list[0] ) ) foreach( $container_list[0] as $container_list_tmp )
    {
      $container_list_tmp = explode( ':', $container_list_tmp );
      $html = str_replace( '[KONTENER:' . $container_list_tmp[1] . ']', \front\view\Scontainers::scontainer( $container_list_tmp[1] ), $html );
    }

    preg_match_all( self::language_pattern, $html, $language_list );
    if ( is_array( $language_list[0] ) ) foreach( $language_list[0] as $language_list_tmp )
    {
      $language_list_tmp = explode( ':', $language_list_tmp );
      $html = str_replace( '[LANG:' . $language_list_tmp[1] . ']', \S::lang( $language_list_tmp[1] ), $html );
    }

    preg_match_all( self::news_pattern, $html, $news_list );
    if ( is_array( $news_list[0] ) ) foreach( $news_list[0] as $news_list_tmp )
    {
      $news_list_tmp = explode( ':', $news_list_tmp );

      $news_list_tmp[2] != '' ? $news_limit = $news_list_tmp[2] : $news_limit = $settings['news_limit'];

      $news_list_tmp[2] != '' ? $pattern = '[AKTUALNOSCI:' . $news_list_tmp[1] . ':' . $news_list_tmp[2] . ']' : $pattern = '[AKTUALNOSCI:' . $news_list_tmp[1] . ']';
      $html = str_replace( $pattern, \front\view\Articles::news(
                                                                        $news_list_tmp[1],
                                                                        \front\factory\Articles::news( $news_list_tmp[1], $news_limit, $lang_id )
                                                                      ), $html );
    }

    $html = str_replace( '[ZAWARTOSC]', \front\controls\Site::route(), $html );

    if ( \S::get( 'article' ) )
    {
      $article = \front\factory\Articles::article_details( \S::get( 'article' ), $lang_id );

      $title            = $article['language']['meta_title'] ? $article['language']['meta_title'] : $article['language']['title'];
      $meta_keywords    = $article['language']['meta_keywords'];
      $meta_description = $article['language']['meta_description'];
    }
    else if ( \S::get( 'tag' ) )
    {
      $tag = \front\factory\Articles::tag_details( \S::get( 'tag' ) );

      $title            = 'Tag: ' . $tag['name'];
      $meta_keywords    = $tag['name'];
      $meta_description = 'Artykuły oznaczone tagiem: ' . $tag['name'];
    }
    else if ( \S::get( 'search' ) )
    {
      $title            = 'Wyniki wyszukiwania: ' . \S::get_session( 'search_txt' );
      $meta_keywords    = \S::get_session( 'search_txt' );
      $meta_description = 'Wyniki wyszukiwania: ' . \S::get_session( 'search_txt' );
    }
    else
    {
      if ( $page['language']['meta_title'] )
        $title = $page['language']['meta_title'];
      else
        $title = $page['language']['title'] . ' ● ' . $settings['firm_name'];

      $meta_keywords    = $page['language']['meta_keywords'];
      $meta_description = $page['language']['meta_description'];
    }

    $seo_additional = \front\factory\SeoAdditional::seo_active();
    if ( is_array( $seo_additional ) and count( $seo_additional ) ) foreach ( $seo_additional as $seo )
    {
      preg_match( '/' . str_replace( '/', '\/', $seo['url'] ) . '/', $_SERVER['REQUEST_URI'], $seo_results );

      if ( is_array( $seo_results ) and count( $seo_results ) )
      {
        if ( $seo['title'] )
        {
          if ( \S::get( 'cp' ) and strpos( $seo['title'], '[STRONA]' ) !== false )
            $title = str_replace( '[STRONA]', \S::get( 'cp' ), $seo['title'] );
          else
            $title = $seo['title'];
        }

        if ( $seo['keywords'] )
          $meta_keywords = $seo['keywords'];

        if ( $meta_description )
          $meta_description = $seo['description'];

        if ( $seo['text'] )
          $html = str_replace( '[DODATKOWA_TRESC]', '<div class="seo-additional-text">' . $seo['text'] . '</div>', $html );
        else
          $html = str_replace( '[DODATKOWA_TRESC]', '', $html );
      }
    }

    $html = str_replace( '[DODATKOWA_TRESC]', '', $html );
    $html = str_replace( '[TITLE]', $title, $html );
    $html = str_replace( '[META_KEYWORDS]', $meta_keywords, $html );
    $html = str_replace( '[META_DESCRIPTION]', $meta_description, $html );
    $html = str_replace( '[JEZYKI]', \front\view\Languages::languages(), $html );
    $html = str_replace( '[KALENDARZ]', \front\view\Site::calendar(), $html );
    $html = str_replace( '[TYTUL_STRONY]', \front\view\Site::title(
                                                $page['language']['title'],
                                                $page['show_title'],
                                                $page['language']['site_title']
                                              ), $html );
    $html = str_replace( '[STRONA_GLOWNA]', \front\factory\Pages::lang_url(
                                              \front\factory\Pages::main_page_id(),
                                              $lang_id,
                                              \S::get_domain( $_SERVER['HTTP_HOST'] ),
                                              \front\factory\Languages::default_domain()
                                            ), $html );

    preg_match_all( self::article_pattern, $html, $articles_list );
    if ( is_array( $articles_list[0] ) ) foreach( $articles_list[0] as $article_tmp )
    {
      $article_tmp = explode( ':', $article_tmp );
      $html = str_replace( '[ARTYKUL:' . $article_tmp[1] . ']', \front\view\Articles::article_full( $article_tmp[1], $lang_id ), $html );
    }

    /* atrybut noindex */
    if ( \S::get( 'article' ) )
    {
      \front\factory\Articles::article_noindex( \S::get( 'article' ) ) === '1' ? $noindex = 'noindex, follow' : $noindex = 'index, follow';
      $html = str_replace( '[META_INDEX]', '<meta name="robots" content="' . $noindex . '">', $html );
    }
    else
    {
      $page['language']['noindex'] === '1' ? $noindex = 'noindex, follow' : $noindex = 'index, follow';
      $html = str_replace( '[META_INDEX]', '<meta name="robots" content="' . $noindex . '">', $html );
    }

    if ( $page['language']['canonical'] )
      $html = str_replace( '</head>', '<link rel="canonical" href="' . $page['language']['canonical'] . '" /></head>', $html );

    while ( strpos( $html, '[PHP]' ) !== false )
    {
      $text = explode( '[PHP]', $html );
      $before = $text[0];
      for ( $i = 1; $i < count( $text ); $i++ )
      {
        $temp   = explode( '[/PHP]' , $text[$i] );
        $code   = $temp[0];

        ob_start();
        eval( str_replace( '&#39;', '"', $code ) );
        $out .= ob_get_contents();
        ob_end_clean();

        $out .= $temp[1];
      }
      $html = $before . $out;
    }

    preg_match_all( self::maps_pattern, $html, $maps_list );
    if ( is_array( $maps_list[1] ) and !empty( $maps_list[1] ) )
    {
      $html = strrev( implode( strrev( '<link class="footer" rel="stylesheet" type="text/css" href="/libraries/leaflet/leaflet.css"><script class="footer" type="text/javascript" src="/libraries/leaflet/leaflet.js"></script></head>' ), explode( strrev( '</head>' ), strrev( $html ), 2 ) ) );
      foreach( $maps_list[1] as $map_tmp )
      {
        ++$map_counter;
        $map_settings = explode( '|', $map_tmp );
        $html         = str_replace( '[MAPA]' . $map_tmp . '[/MAPA]', \front\view\Articles::map( $map_settings, $map_counter ), $html );
      }
    }

    $html = str_replace( '[ALERT]', \front\view\Site::alert(), $html );
    $html = str_replace( '[ALERT_PROMPT]', \front\view\Site::alert_prompt(), $html );

    return $html;
  }

  public static function widget_phone()
  {
    $tpl = new \Tpl;
    return $tpl -> render( 'widgets/widget-phone' );
  }

  public static function facebook( $facebook_link )
  {
    $tpl = new \Tpl;
    $tpl -> facebook_link = $facebook_link;
    return $tpl -> render( 'site/facebook' );
  }

  public static function title( $title, $show_title, $site_title )
  {
    if ( !$show_title )
      return false;

    if ( $site_title )
      $title = $site_title;

    $tpl = new \Tpl;
    $tpl -> title = $title;
    return $tpl -> render( 'site/title' );
  }

  public static function alert_prompt()
  {
    if ( $alert_prompt = \S::get_session( 'alert-prompt' ) )
    {
      \S::delete_session( 'alert-prompt' );

      return \S::alert_prompt( $alert_prompt );
    }
  }

  public static function alert()
  {
    if ( $alert = \S::get_session( 'alert' ) )
    {
      $alert_class = \S::get_session( 'alert-class' );
      \S::delete_session( 'alert' );
      \S::delete_session( 'alert-class' );

      $tpl = new \Tpl;
      $tpl -> alert       = $alert;
      $tpl -> alert_class = $alert_class;
      return $tpl -> render( 'site/alert' );
    }
  }

  public static function copyright()
  {
    $tpl = new \Tpl;
    return $tpl -> render( 'site/copyright' );
  }

  public static function contact()
  {
    $tpl = new \Tpl;
    return $tpl -> render( 'site/contact' );
  }

  public static function cookie_information()
  {
    $tpl = new \Tpl;
    return $tpl -> render( 'site/cookie-information' );
  }

  public static function calendar( $month = '', $year = '', $ajax = false )
  {
    global $settings, $lang_id;

    if ( !$settings['calendar'] )
      return false;

    if ( !$month ) $month = date( 'n' );
    if ( !$year ) $year = date( 'Y' );

    $tpl = new \Tpl;
    $tpl -> month     = $month;
    $tpl -> year      = $year;
    $tpl -> months    = \S::months();
    $tpl -> ajax      = $ajax;
    $tpl -> articles  = \front\factory\Articles::articles_by_date( $month, $year, $lang_id );
    return $tpl -> render( 'site/calendar' );
  }

  public static function visit_counter( $visit_counter )
  {
    $tpl = new \Tpl;
    $tpl -> visit_counter = $visit_counter;
    return $tpl -> render( 'site/visit-counter' );
  }

  public static function contrast()
  {
    $tpl = new \Tpl;
    return $tpl -> render( 'site/contrast' );
  }
}
?>
