<?php
namespace front\Views;

class Articles
{
  /**
   * Renderuje pelny widok pojedynczego artykulu.
   */
  public static function fullArticle( $article )
  {
    $tpl = new \Shared\Tpl\Tpl;
    $tpl->article = $article;
    return $tpl->render( 'articles/article' );
  }

  /**
   * Renderuje liste artykulow w trybie miniaturek z pagerem.
   */
  public static function miniatureArticlesList( $articles, $ls, $bs, $page )
  {
    $out = '';

    if ( is_array( $articles ) ) foreach ( $articles as $article )
    {
      $tpl = new \Shared\Tpl\Tpl;
      $tpl->article = $article;
      $out .= $tpl->render( 'articles/article-miniature' );
    }

    if ( $ls > 1 )
    {
      $tpl = new \Shared\Tpl\Tpl;
      $tpl->ls    = $ls;
      $tpl->bs    = $bs ? $bs : 1;
      $tpl->page  = $page;
      $out .= $tpl->render( 'site/pager' );
    }

    return $out;
  }

  /**
   * Renderuje liste artykulow w trybie wprowadzen z pagerem.
   */
  public static function entryArticlesList( $articles, $ls, $bs, $page )
  {
    $tpl = new \Shared\Tpl\Tpl;
    $tpl->page_id   = $page['id'];
    $tpl->articles  = $articles;
    $out = $tpl->render( 'articles/articles-entries' );

    if ( $ls > 1 )
    {
      $tpl = new \Shared\Tpl\Tpl;
      $tpl->ls    = $ls;
      $tpl->bs    = $bs ? $bs : 1;
      $tpl->page  = $page;
      $out .= $tpl->render( 'site/pager' );
    }

    return $out;
  }

  /**
   * Renderuje liste pelnych artykulow z pagerem.
   */
  public static function fullArticlesList( $articles, $ls, $bs, $page )
  {
    $out = '';

    if ( is_array( $articles ) ) foreach ( $articles as $article )
    {
      $tpl = new \Shared\Tpl\Tpl;
      $tpl->article = $article;
      $out .= $tpl->render( 'articles/article-full' );
    }

    if ( $ls > 1 )
    {
      $tpl = new \Shared\Tpl\Tpl;
      $tpl->ls    = $ls;
      $tpl->bs    = $bs ? $bs : 1;
      $tpl->page  = $page;
      $out .= $tpl->render( 'site/pager' );
    }

    return $out;
  }

  /**
   * Renderuje box z aktualnosciami.
   */
  public static function news( $page_id, $articles )
  {
    $tpl = new \Shared\Tpl\Tpl;
    $tpl->page_id   = $page_id;
    $tpl->articles  = $articles;
    return $tpl->render( 'articles/news' );
  }

  /**
   * Renderuje prosta liste artykulow (news-list).
   */
  public static function newsList( $articles )
  {
    return \Shared\Tpl\Tpl::view( 'articles/news-list', [
      'articles' => $articles
    ] );
  }

  // =========================================================================
  // UTILITY (czyste transformacje HTML, brak DB)
  // =========================================================================

  /**
   * Generuje spis tresci z naglowkow HTML.
   */
  public static function generateTableOfContents( $content )
  {
    $result = '';
    $currentLevel = [];

    preg_match_all( '/<(h[1-6])([^>]*)>(.*?)<\/\1>/', $content, $matches, PREG_SET_ORDER );

    $firstLevel = true;

    foreach ( $matches as $match )
    {
      $level = intval( substr( $match[1], 1 ) );

      while ( $level < count( $currentLevel ) )
      {
        $result .= '</li></ol>';
        array_pop( $currentLevel );
      }

      if ( $level > count( $currentLevel ) )
      {
        while ( $level > count( $currentLevel ) )
        {
          if ( count( $currentLevel ) > 0 || $firstLevel )
          {
            $result .= '<ol>';
            $firstLevel = false;
          }
          array_push( $currentLevel, 0 );
        }
        $result .= '<li>';
      }
      else
      {
        $result .= '</li><li>';
      }

      $currentLevel[ count( $currentLevel ) - 1 ]++;

      preg_match( '/\sid="([^"]*)"/', $match[2], $idMatches );
      $id = isset( $idMatches[1] ) ? $idMatches[1] : '';

      $result .= sprintf(
        '<a href="#%s">%s</a>',
        urlencode( strtolower( $id ) ),
        $match[3]
      );
    }

    while ( !empty( $currentLevel ) )
    {
      $result .= '</li></ol>';
      array_pop( $currentLevel );
    }

    if ( substr( $result, 0, 8 ) === '<ol><ol>' )
      return substr( $result, 4, -5 );
    else
      return $result;
  }

  /**
   * Callback dla processHeaders.
   */
  public static function processHeaders( $matches )
  {
    $level = $matches[1];
    $attrs = $matches[2];
    $content = $matches[3];
    $id_attr = 'id=';
    $id_attr_pos = strpos( $attrs, $id_attr );
    if ( $id_attr_pos === false )
    {
      $id = \Shared\Helpers\Helpers::seo( $content );
      $attrs .= sprintf( ' id="%s"', $id );
    }

    return sprintf( '<h%d%s>%s</h%d>', $level, $attrs, $content, $level );
  }

  /**
   * Dodaje atrybuty id do naglowkow HTML.
   */
  public static function generateHeadersIds( $text )
  {
    $pattern = '/<h([1-6])(.*?)>(.*?)<\/h\1>/si';
    $text = preg_replace_callback( $pattern, array( __CLASS__, 'processHeaders' ), $text );
    return $text;
  }

  /**
   * Pobiera glowne zdjecie artykulu (z entry, text lub galerii).
   */
  public static function getImage( $article )
  {
    if ( $main_img = $article['language']['main_image'] )
      return $main_img;

    $dom = new \DOMDocument();
    @$dom->loadHTML( mb_convert_encoding( $article['language']['entry'], 'HTML-ENTITIES', 'UTF-8' ) );
    $images = $dom->getElementsByTagName( 'img' );
    foreach ( $images as $img )
    {
      $src = $img->getAttribute( 'src' );
      if ( file_exists( substr( $src, 1, strlen( $src ) ) ) )
        return $src;
    }

    $dom = new \DOMDocument();
    @$dom->loadHTML( mb_convert_encoding( $article['language']['text'], 'HTML-ENTITIES', 'UTF-8' ) );
    $images = $dom->getElementsByTagName( 'img' );
    foreach ( $images as $img )
    {
      $src = $img->getAttribute( 'src' );
      if ( file_exists( substr( $src, 1, strlen( $src ) ) ) )
        return $src;
    }

    if ( $article['images'] )
      return $article['images'][0]['src'];

    return false;
  }
}
