<?php
class Article implements \ArrayAccess
{
  public function __construct( $article_id, $lang_id )
  {
    global $mdb;

    $result = $mdb -> get( 'pp_articles', '*', [ 'id' => (int)$article_id ] );
    if ( \S::is_array_fix( $result ) ) foreach ( $result as $key => $val )
      $this -> $key = $val;

    $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 )
          $this -> language = $row2;
      }
      else
      $this -> language = $row;

      preg_match_all( \front\view\Site::container_pattern, $this -> language['entry'], $container_list );
      if ( is_array( $container_list[0] ) ) foreach( $container_list[0] as $container_list_tmp )
      {
        $container_list_tmp = explode( ':', $container_list_tmp );
        $this -> language['entry'] = str_replace( '[KONTENER:' . $container_list_tmp[1] . ']', \front\view\Scontainers::scontainer( $container_list_tmp[1] ), $this -> language['entry'] );
      }

      preg_match_all( \front\view\Site::container_pattern, $this -> language['text'], $container_list );
      if ( is_array( $container_list[0] ) ) foreach( $container_list[0] as $container_list_tmp )
      {
        $container_list_tmp = explode( ':', $container_list_tmp );
        $this -> language['text'] = str_replace( '[KONTENER:' . $container_list_tmp[1] . ']', \front\view\Scontainers::scontainer( $container_list_tmp[1] ), $this -> language['text'] );
      }
    }

    $this -> images = $mdb -> select( 'pp_articles_images', '*', [ 'article_id' => (int)$article_id, 'ORDER' => [ 'o' => 'ASC', 'id' => 'ASC' ] ] );
    $this -> files = $mdb -> select( 'pp_articles_files', '*', [ 'article_id' => (int)$article_id ] );
    $this -> pages = $mdb -> select( 'pp_articles_pages', 'page_id', [ 'article_id' => (int)$article_id ] );
    $this -> tags = $mdb -> select( 'pp_tags', [ '[><]pp_articles_tags' => [ 'id' => 'tag_id' ] ], 'name', [ 'article_id' => (int)$article_id ] );
    $results = $mdb -> select( 'pp_articles_additional_params', [ '[><]pp_articles_additional_values' => [ 'id' => 'param_id' ] ], [ 'name', 'value', 'language_id' ], [ 'article_id' => (int)$article_id ] );
    if ( is_array( $results ) ) foreach ( $results as $row )
    {
      if ( !$row['language_id'] )
        $params[ $row['name'] ] = $row['value'];
      else
        $params[ $row['name'] ][$row['language_id']] = $row['value'];
    }
    $this -> params = $params;
  }

  public function get_from_cache( $article_id, $lang_id )
  {
    $cacheHandler = new \CacheHandler();
    $cacheKey = "\Article::get_from_cache:$article_id:$lang_id";

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

    if ( !$objectData )
    {
      $article = new \Article( $article_id, $lang_id );

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

    return $article;
  }

  public function updateView()
  {
    global $mdb;
    $mdb -> update( 'pp_articles', [ 'views[+]' => 1 ], [ 'id' => $this -> id ] );
  }

  static public function newsList( $articles )
  {
    return \Tpl::view( 'articles/news-list', [
      'articles' => $articles
    ] );
  }

  // pobierz najczęściej wyświtlane artykuły
  static public function getTopNews( $page_id, $limit = 6, $lang_id )
  {
    global $mdb;

    $cacheHandler = new \CacheHandler();
    $cacheKey = "\Article::getTopNews:$page_id:$limit:$lang_id";

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

    if ( !$objectData )
    {
      $articles_id = $mdb -> query( 'SELECT * FROM ( '
                                      . 'SELECT '
                                          . 'a.id, date_add, views, '
                                          . '( 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.views DESC '
                                  . 'LIMIT '
                                    . '0, ' . (int)$limit ) -> fetchAll( \PDO::FETCH_ASSOC );

      $cacheHandler -> set( $cacheKey, $articles_id );
    }
    else
    {
      $articles_id = unserialize( $objectData );
    }

    if ( \S::is_array_fix( $articles_id ) ) foreach ( $articles_id as $article_tmp )
    {
      $article = \Article::get_from_cache( $article_tmp['id'], $lang_id );
      $articles[] = $article;
    }

    return $articles;
  }

  static public function getNews( $page_id, $limit = 6, $lang_id )
  {
    global $mdb;

    if ( !$articles_id = \Cache::fetch( "getNews:$page_id:$limit:$lang_id" ) )
    {
      $articles_id = $mdb -> query( 'SELECT * FROM ( '
                                      . 'SELECT '
                                          . 'a.id, date_add, '
                                          . '( 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.date_add DESC '
                                  . 'LIMIT '
                                    . '0, ' . (int)$limit ) -> fetchAll( \PDO::FETCH_ASSOC );
      \Cache::store( "getNews:$page_id:$limit:$lang_id", $articles_id );
    }

    if ( \S::is_array_fix( $articles_id ) ) foreach ( $articles_id as $article_tmp )
    {
      $article = \Article::get_from_cache( $article_tmp['id'], $lang_id );
      $articles[] = $article;
    }

    return $articles;
  }

  public function __get( $variable )
  {
    if ( array_key_exists( $variable, $this -> data ) )
      return $this -> $variable;
  }

  public function __set( $variable, $value )
  {
    $this -> $variable = $value;
  }

  public function offsetExists( $offset )
  {
    return isset( $this -> $offset );
  }

  public function offsetGet( $offset )
  {
    return $this -> $offset;
  }

  public function offsetSet( $offset, $value )
  {
    $this -> $offset = $value;
  }

  public function offsetUnset( $offset )
  {
    unset( $this -> $offset );
  }
}