<?php
namespace front\factory;

class Articles
{
  static public 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;
    }
  }

  // funkcja wywoływana dla każdego dopasowania do wyrażenia regularnego
  static public 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) { // jeśli nie ma atrybutu id
      $id = \S::seo( $content );
      $attrs .= sprintf(' id="%s"', $id);
    }

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

  static public function generateHeadersIds( $text )
  {
    $pattern = '/<h([1-6])(.*?)>(.*?)<\/h\1>/si';

    $text = preg_replace_callback( $pattern, array(__CLASS__, 'processHeaders'), $text );

    return $text;
  }

  public static function news( $page_id, $limit = 6, $lang_id )
  {
    $sort = \front\factory\Pages::page_sort( $page_id );

    $articles_id = \front\factory\Articles::artciles_id( (int)$page_id, $lang_id, $limit, $sort, 0 );
    if ( is_array( $articles_id ) and !empty( $articles_id ) ) foreach ( $articles_id as $article_id )
      $articles[] = \front\factory\Articles::article_details( $article_id, $lang_id );

    return $articles;
  }

  public static function get_image( $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;
  }

  public static function article_noindex( $article_id )
  {
    global $mdb, $lang;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Articles::article_noindex:$article_id";

    $objectData = $cacheHandler -> get( $cacheKey );

    if ( !$objectData )
    {
      $noindex = $mdb -> get( 'pp_articles_langs', 'noindex', [ 'AND' => [ 'article_id' => (int)$article_id, 'lang_id' => $lang[0] ] ] );

      $cacheHandler -> set( $cacheKey, $noindex );
    }
    else
    {
      return unserialize( $objectData );
    }
    return $noindex;
  }

  public static function page_articles( $page, $lang_id, $bs )
  {
    $count  = \front\factory\Articles::page_articles_count( $page['id'], $lang_id );
    $ls     = ceil( $count / $page['articles_limit'] );

    if ( $bs < 1 )
      $bs = 1;
    else if ( $bs > $ls )
      $bs = $ls;

    $from = $page['articles_limit'] * ( $bs - 1 );

    if ( $from < 0 )
      $from = 0;

    $results['articles'] = \front\factory\Articles::artciles_id( (int)$page['id'], $lang_id, (int)$page['articles_limit'], $page['sort_type'], $from );
    $results['ls'] = $ls;

    return $results;
  }

  public static function article_details( $article_id, $lang_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Articles::article_details:$article_id:$lang_id";

    $objectData = $cacheHandler->get($cacheKey);

    if ( !$objectData )
    {
      $article = $mdb -> get( 'pp_articles', '*', [ 'id' => (int)$article_id ] );

      $results = $mdb -> select( 'pp_articles_langs', '*', [ 'AND' => [ 'article_id' => (int)$article_id, 'lang_id' => $lang_id ] ] );
      if ( is_array( $results ) ) foreach ( $results as $row )
      {
        if ( $row['copy_from'] )
        {
          $results2 = $mdb -> select( 'pp_articles_langs', '*', [ 'AND' => [ 'article_id' => (int)$article_id, 'lang_id' => $row['copy_from'] ] ] );
          if ( is_array( $results2 ) ) foreach ( $results2 as $row2 )
            $article['language'] = $row2;
        }
        else
          $article['language'] = $row;
      }

      $article['images']  = $mdb -> select( 'pp_articles_images', '*', [ 'article_id' => (int)$article_id, 'ORDER' => [ 'o' => 'ASC', 'id' => 'DESC' ] ] );
      $article['files']   = $mdb -> select( 'pp_articles_files', '*', [ 'article_id' => (int)$article_id ] );
      $article['pages']   = $mdb -> select( 'pp_articles_pages', 'page_id', [ 'article_id' => (int)$article_id ] );

      $cacheHandler -> set( $cacheKey, $article );
    }
    else
    {
      return unserialize( $objectData );
    }

    return $article;
  }

  public static function artciles_id( $page_id, $lang_id, $articles_limit, $sort_type, $from )
  {
    global $mdb;

    switch ( $sort_type )
    {
      case 0: $order = 'date_add ASC'; break;
      case 1: $order = 'date_add DESC'; break;
      case 2: $order = 'date_modify ASC'; break;
      case 3: $order = 'date_modify DESC'; break;
      case 4: $order = 'o ASC'; break;
      case 5: $order = 'title ASC'; break;
      case 6: $order = 'title DESC'; break;
      default: $order = 'id ASC'; break;
    }

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Artiles::artciles_id:$page_id:$lang_id:$articles_limit:$sort_type:$from:$order";

    $objectData = $cacheHandler->get($cacheKey);

    if ( !$objectData )
    {
      $results = $mdb -> query( 'SELECT * FROM ( '
                                      . 'SELECT '
                                          . 'a.id, date_modify, date_add, o, '
                                          . '( CASE '
                                            . 'WHEN copy_from IS NULL THEN title '
                                            . 'WHEN copy_from IS NOT NULL THEN ( '
                                              . 'SELECT '
                                                . 'title '
                                              . 'FROM '
                                                . 'pp_articles_langs '
                                              . 'WHERE '
                                                . 'lang_id = al.copy_from AND article_id = a.id '
                                              . ') '
                                           . 'END ) AS title '
                                      . 'FROM '
                                        . 'pp_articles_pages AS ap '
                                        . 'INNER JOIN pp_articles AS a ON a.id = ap.article_id '
                                        . 'INNER JOIN pp_articles_langs AS al ON al.article_id = ap.article_id '
                                      . 'WHERE '
                                        . 'status = 1 AND page_id = ' . (int)$page_id . ' AND lang_id = \'' . $lang_id . '\' '
                                  . ') AS q1 '
                                  . 'WHERE '
                                    . 'q1.title IS NOT NULL '
                                  . 'ORDER BY '
                                    . 'q1.' . $order . ' '
                                  . 'LIMIT '
                                    . (int)$from . ',' . (int)$articles_limit ) -> fetchAll();
      if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
        $output[] = $row['id'];

      $cacheHandler -> set( $cacheKey, $output );
    }
    else
    {
      return unserialize($objectData);
    }
    return $output;
  }

  public static function page_articles_count( $page_id, $lang_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\front\factory\Articles::page_articles_count:$page_id:$lang_id";

    $objectData = $cacheHandler -> get( $cacheKey );

    if ( !$objectData )
    {
      $results = $mdb -> query( 'SELECT COUNT(0) FROM ( '
                                    . 'SELECT '
                                        . 'a.id, '
                                        . '( CASE '
                                          . 'WHEN copy_from IS NULL THEN title '
                                          . 'WHEN copy_from IS NOT NULL THEN ( '
                                            . 'SELECT '
                                              . 'title '
                                            . 'FROM '
                                              . 'pp_articles_langs '
                                            . 'WHERE '
                                              . 'lang_id = al.copy_from AND article_id = a.id '
                                            . ') '
                                         . 'END ) AS title '
                                    . 'FROM '
                                      . 'pp_articles_pages AS ap '
                                      . 'INNER JOIN pp_articles AS a ON a.id = ap.article_id '
                                      . 'INNER JOIN pp_articles_langs AS al ON al.article_id = ap.article_id '
                                    . 'WHERE '
                                      . 'status = 1 AND page_id = ' . (int)$page_id . ' AND lang_id = \'' . $lang_id . '\' '
                                . ') AS q1 '
                                . 'WHERE '
                                  . 'q1.title IS NOT NULL' ) -> fetchAll();
      $articles_count = $results[0][0];

      $cacheHandler -> set( $cacheKey, $articles_count );
    }
    else
    {
      return unserialize( $objectData );
    }

    return $articles_count;
  }
}
