<?php
    
    namespace common\models\blog;
    
    use artbox\core\models\Image;
    use artbox\core\models\traits\AliasableTrait;
    use artbox\webcomment\models\CommentModel;
    use yii\behaviors\TimestampBehavior;
    use yii\db\ActiveRecord;
    use artbox\core\models\Language;
    use yii\db\ActiveQuery;
    use yii\db\Query;
    use yii\helpers\Json;
    use yii2tech\ar\linkmany\LinkManyBehavior;
    use yii2tech\ar\position\PositionBehavior;
    use yii2tech\ar\variation\VariationBehavior;
    
    /**
     * This is the model class for table "blog_article".
     *
     * @property integer     $id
     * @property Image       $image
     * @property integer     $created_at
     * @property integer     $updated_at
     * @property integer     $deleted_at
     * @property integer     $sort
     * @property boolean     $status
     * @property integer     $author_id
     * @property integer     $image_id
     * @property ArticleLang[] $blogArticleLangs
     * @property Language[]  $languages
     * @property \common\models\blog\Article[]     $relatedBlogArticles
     * @property \common\models\blog\Article[]     $articles
     * @property Category[]  $categories
     * @property Category    $category
     * @property Tag[]       $tags
     *  * from VariationBehavior
     * @method ActiveQuery  hasDefaultVariationRelation();
     */
    class Article extends ActiveRecord
    {
        use AliasableTrait;
        
        /**
         * @inheritdoc
         */
        public static function tableName()
        {
            return 'blog_article';
        }
        
        public function behaviors()
        {
            return [
                'translations'         => [
                    'class'                             => VariationBehavior::className(),
                    'variationsRelation'                => 'languages',
                    'defaultVariationRelation'          => 'language',
                    'variationOptionReferenceAttribute' => 'language_id',
                    'optionModelClass'                  => Language::className(),
                    'defaultVariationOptionReference'   => function () {
                        return Language::getCurrent()->id;
                    },
                    'optionQueryFilter'                 => function (ActiveQuery $query) {
                        $query->where(
                            [
                                'status' => true,
                            ]
                        );
                    },
                ],
                'positionBehavior'     => [
                    'class'             => PositionBehavior::className(),
                    'positionAttribute' => 'sort',
                ],
                'linkCategoryBehavior' => [
                    'class'                      => LinkManyBehavior::className(),
                    'relation'                   => 'categories',
                    'relationReferenceAttribute' => 'categoryIds',
                ],
                'linkTagBehavior'      => [
                    'class'                      => LinkManyBehavior::className(),
                    'relation'                   => 'tags',
                    'relationReferenceAttribute' => 'tagIds',
                ],
                'linkArticleBehavior'  => [
                    'class'                      => LinkManyBehavior::className(),
                    'relation'                   => 'articles',
                    'relationReferenceAttribute' => 'articleIds',
                ],
                'timestamp'            => [
                    'class' => TimestampBehavior::className(),
                ],
            ];
        }
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [
                    [
                        'created_at',
                        'updated_at',
                        'deleted_at',
                        'sort',
                        'author_id',
                        'image_id',
                    ],
                    'integer',
                ],
                [
                    [ 'status' ],
                    'boolean',
                ],
                
                [
                    [
                        'categoryIds',
                        'tagIds',
                        'articleIds',
                    ],
                    'safe',
                ],
            ];
        }
        
        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'id'          => 'ID',
                'image'       => 'Image',
                'created_at'  => 'Created At',
                'updated_at'  => \Yii::t('core', 'Updated At'),
                'deleted_at'  => 'Deleted At',
                'sort'        => \Yii::t('core', 'Sort'),
                'status'      => \Yii::t('core', 'Status'),
                'author_id'   => 'Author ID',
                'title'       => \Yii::t('core', 'Title'),
                'categories'  => \Yii::t('core', 'Categories'),
                'tags'        => \Yii::t('core', 'Tags'),
                
                'image_id'    => \Yii::t('core', 'Image'),
                'categoryIds' => \Yii::t('core', 'Categories'),
                'tagIds'      => \Yii::t('core', 'Tags'),
                'articleIds'  => \Yii::t('core', 'Articles'),
            ];
        }
        
        public function getLanguages()
        {
            return $this->hasMany(ArticleLang::className(), [ 'blog_article_id' => 'id' ]);
        }
        
        /**
         * @return \yii\db\ActiveQuery
         */
        public function getLanguage()
        {
            return $this->hasDefaultVariationRelation();
        }
        
        /**
         * @return \yii\db\ActiveQuery
         */
        public function getRelatedBlogArticles()
        {
            return $this->hasMany(Article::className(), [ 'id' => 'related_blog_article_id' ])
                        ->viaTable('blog_article_to_article', [ 'blog_article_id' => 'id' ]);
        }
        public function getRoute()
        {
            return Json::encode(
                [
                    'blog/view',
                    'id' => $this->id,
                ]
            );
        }
        
        /**
         * @return Query
         */
        public function getRelatedProducts()
        {
            if (class_exists('\artbox\catalog\models\Product')) {
                return $this->hasMany('\artbox\catalog\models\Product', [ 'id' => 'product_id' ])
                            ->via('articleToProduct');
            } else {
                return ( new Query() )->where('1 = 0');
            }
        }
        
        //        public function getCommentsCount()
        //        {
        //
        //            if (class_exists('\artbox\webcomment\models\CommentModel')) {
        //                $comments = CommentModel::find()->where("status = 1 and entity = 'artbox\weblog\models\Article' and entity_id = ".$this->id)->count();
        //                return $comments;
        //            } else {
        //                return null;
        //            }
        //        }
        
        /**
         * @return Query
         */
        public function getArticleToProduct()
        {
            
            if (class_exists('\artbox\catalog\models\Product')) {
                return $this->hasMany(ArticleToProduct::className(), [ 'article_id' => 'id' ]);
            } else {
                return ( new Query() )->where('1 = 0');
            }
        }
        
        /**
         * @return \yii\db\ActiveQuery
         */
        public function getImage()
        {
            return $this->hasOne(Image::className(), [ 'id' => 'image_id' ]);
        }
        
        /**
         * @return \yii\db\ActiveQuery
         */
        public function getArticles()
        {
            return $this->hasMany(Article::className(), [ 'id' => 'blog_article_id' ])
                        ->viaTable('blog_article_to_article', [ 'related_blog_article_id' => 'id' ]);
        }
        
        /**
         * @return \yii\db\ActiveQuery
         */
        public function getCategories()
        {
            return $this->hasMany(Category::className(), [ 'id' => 'blog_category_id' ])
                        ->viaTable('blog_article_to_category', [ 'blog_article_id' => 'id' ]);
        }
        
        /**
         * @return \yii\db\ActiveQuery
         */
        public function getCategory()
        {
            return $this->hasOne(Category::className(), [ 'id' => 'blog_category_id' ])
                        ->viaTable('blog_article_to_category', [ 'blog_article_id' => 'id' ]);
        }
        
        /**
         * @return \yii\db\ActiveQuery
         */
        public function getTags()
        {
            return $this->hasMany(Tag::className(), [ 'id' => 'blog_tag_id' ])
                        ->viaTable('blog_article_to_tag', [ 'blog_article_id' => 'id' ]);
        }
    }
