<?php

namespace app\models\base;
use  \app\models\base\Tags;

use Yii;

/**
 * This is the model class for table "tags_relation".
 *
 * @property int $news_id
 * @property int $topic_id
 * @property string $type
 */
class TagsRelation extends BaseFrontendClass
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tags_relation';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['news_id', 'topic_id'], 'integer'],
            [['type'], 'required'],
            [['type'], 'string', 'max' => 32],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'news_id' => 'News ID',
            'topic_id' => 'Topic ID',
            'type' => 'Type',
        ];
    }

	/**
     * {@inheritdoc}
     * @return status
     */
    public function saveNewsTags($id, $topics)
    {
		$status = true;
		foreach( $topics as $item ){
			if( is_numeric($item) && (int) $item > 0 ){
				$item = (int) $item;
				$status &= $this->db->createCommand()->insert(self::tableName(), [
					'news_id' => $id,
					'topic_id' => $item,
					'type' => 'news'
				])->execute();
			}else{
				if( mb_strlen( $item ) > 2 ){	//совсем мусор
					$tags = new Tags();
					$r = $tags->simpleAdd($item);
					if( $r !== false && $r*1 > 0 ){
						$status &= $this->db->createCommand()->insert(self::tableName(), [
						'news_id' => $id,
						'topic_id' => $r,
						'type' => 'news'
						])->execute();
					}
				}
			}
		}
        return $status;
    }

    public function mergeTags( $from, $to ){
// UPDATE `tags_relation` SET `topic_id` = 1000 WHERE `topic_id` = 3
		$this->db->createCommand()->update(self::tableName(), array( 'topic_id'=>$to ), 'topic_id=:topic_id', array(':topic_id'=>$from) );
		$tags = new Tags();
		if($tags) $tags->Show($from, 'N');		// soft delete
		if($tags) $tags->Active($from, 0);		//
		Yii::$app->cache->delete("archive_tags-{$from}");
	}

    /**
     * {@inheritdoc}
     * @return TagsRelationQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new TagsRelationQuery(get_called_class());
    }
}
