<?php

namespace common\modules\content\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use himiklab\sitemap\behaviors\SitemapBehavior;
use \yii\helpers\Url;

use common\modules\content\models\CoBlocks;
use common\modules\content\models\CoContentLang;
use common\modules\languages\models\Languages;
use common\models\MetaTags;

/**
 * This is the model class for table "co_content".
 *
 * @property integer $id
 * @property integer $category_id
 * @property string $url
 * @property string $name
 * @property string $title
 * @property string $text
 * @property integer $active
 * @property integer $created_at
 * @property integer $updated_at
 *
 * @property CoCategory $category
 */
class CoContent extends \common\components\ActiveRecordModel
{
    public $image;

    const PHOTO_FOLDER = '/uploads/content/';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'co_content';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'meta' => [
                'class' => 'common\components\activeRecordBehaviors\MetaTagBehavior',
            ],
            'langs' => [
                'class' => 'common\modules\content\components\CoContentLangBehavior',
            ],
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => time(),
            ],
            'sitemap' => [
                'class' => SitemapBehavior::className(),
                'scope' => function ($model) {
                    /** @var \yii\db\ActiveQuery $model */
                    $model->select(['url', 'updated_at', 'priority']);
                    // $model->andWhere(['is_deleted' => 0]);
                },
                'dataClosure' => function ($model) {
                    return [
                        'loc' => Url::to($model->url, true),
                        'lastmod' => date('c', $model->updated_at),
                        'changefreq' => SitemapBehavior::CHANGEFREQ_DAILY,
                        'priority' => $model->priority
                    ];
                }
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function name() {
		return 'Контент';
	}

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['active'], 'integer'],
            [['image'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif'],
            [['url'], 'required'],
            [['url'], 'string', 'max' => 250],
            [['category_id', 'priority'], 'safe'],
            [['priority'], 'double']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('content', 'ID'),
            'category_id' => Yii::t('content', 'Category ID'),
            'url' => Yii::t('content', 'Url'),
            'name' => Yii::t('content', 'Name'),
            'image' => 'Превью',
            'priority' => 'Приоритет в Sitemap',
            'title' => Yii::t('content', 'Title'),
            'text' => Yii::t('content', 'Content'),
            'active' => Yii::t('content', 'Active'),
            'created_at' => Yii::t('content', 'Created At'),
            'updated_at' => Yii::t('content', 'Updated At'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMetaTags($lang_id = null) 
    {
        $query = $this->hasMany(MetaTags::className(), ['object_id' => 'id'])->where(['model_id'  => get_class($this)]);

        if($lang_id)
        {
            $query->andWhere(['lang_id' => $lang_id]);
        }

        return $query;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMetaTag($lang_id = null) 
    {
        $lang_id = ($lang_id === null)? Languages::getCurrent()->id: $lang_id;

        return $this->hasOne(MetaTags::className(), ['object_id' => 'id'])->where([
            'model_id'  => get_class($this),
            'lang_id' => $lang_id
        ]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(CoCategory::className(), ['id' => 'category_id']);
    }

    public function getLang($lang_id = null)
    {
        $lang_id = ($lang_id === null)? Languages::getCurrent()->id: $lang_id;

        return $this->hasOne(CoContentLang::className(), ['content_id' => 'id'])->where('lang_id = :lang_id', [':lang_id' => $lang_id]);
    }

    public function getLangs()
    {
        return $this->hasMany(CoContentLang::className(), ['content_id' => 'id']);
    }

    private function getPath()
    {
        return Yii::getAlias('@frontend/web') . self::PHOTO_FOLDER;
    }

    public function upload()
    {
        if ($this->validate()) 
        {
            if(!file_exists($this->getPath()))
            {
                mkdir($this->getPath(), 0777, true);
            }

            $this->preview = date('dmYHis-') . uniqid() . '.' . $this->image->extension;
            $this->image->saveAs($this->getPath() . $this->preview);
            return true;
        } 
        else 
        {
            return false;
        }
    }

    public function deletePreview()
    {
        if(file_exists($this->getPath() . $this->preview))
        {
            unlink($this->getPath() . $this->preview);
        }
    }
}
