<?php

namespace common\modules\product\models;

use common\behaviors\RuSlug;
use common\components\artboxtree\ArtboxTreeBehavior;
use common\components\artboxtree\ArtboxTreeHelper;
use common\modules\relation\relationBehavior;
use common\modules\rubrication\behaviors\ArtboxSynonymBehavior;
use Yii;

/**
 * This is the model class for table "category".
 *
 * @property integer $category_id
 * @property string $remote_id
 * @property integer $parent_id
 * @property string $path
 * @property integer $depth
 * @property string $image
 * @property string $meta_title
 * @property string $meta_desc
 * @property string $meta_robots
 * @property string $seo_text
 * @property integer $category_name_id
 * @property integer $product_unit_id
 * @property string $alias
 * @property boolean $populary
 *
 * @property CategoryName $categoryName
 * @property ProductUnit $productUnit
 * @property CategoryName[] $categoryNames
 * @property ProductCategory[] $productCategories
 */
class Category extends \yii\db\ActiveRecord
{
    public $imageUpload;

    public function behaviors()
    {
        return [
            'artboxtree' => [
                'class' => ArtboxTreeBehavior::className(),
                'keyNameGroup' => null,
                'keyNamePath' => 'path',
            ],
            'artboxsynonym' => [
                'class' => ArtboxSynonymBehavior::className(),
                'keyNameValue' => 'category_name_id',
                'valueModel' => CategoryName::className(),
                'valueOptionId' => 'category_id',
                'valueFields' => [ // postKey => DBFieldName
                    'name' => 'value'
                ],
                'slug' => [
                    'valueKeyName' => 'value',
                    'slugKeyName' => 'alias',
                    'translit' => true
                ]
            ],
            [
                'class' => relationBehavior::className(),
                'relations' => [
                    'product_categories' => 'entity2', // Products of category
                    'tax_group_to_category' => 'entity2',
                ]
            ],
        ];
    }

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'string'],
            [['parent_id', 'depth', 'category_name_id', 'product_unit_id'], 'integer'],
            [['path', 'meta_desc', 'seo_text'], 'string'],
            [['meta_title'], 'string', 'max' => 255],
            [['meta_robots'], 'string', 'max' => 50],
            [['alias', 'name'], 'string', 'max' => 250],
            [['populary'], 'boolean'],
            [['group_to_category', 'remote_category'], 'safe'],
            [['category_name_id'], 'exist', 'skipOnError' => true, 'targetClass' => CategoryName::className(), 'targetAttribute' => ['category_name_id' => 'category_name_id']],
            [['imageUpload'], 'safe'],
            [['imageUpload'], 'file', 'extensions' => 'jpg, gif, png'],
//            [['product_unit_id'], 'exist', 'skipOnError' => true, 'targetClass' => ProductUnit::className(), 'targetAttribute' => ['product_unit_id' => 'product_unit_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'category_id' => Yii::t('product', 'Category ID'),
            'parent_id' => Yii::t('product', 'Parent ID'),
            'path' => Yii::t('product', 'Path'),
            'depth' => Yii::t('product', 'Depth'),
            'image' => Yii::t('product', 'Image'),
            'imageUrl' => Yii::t('product', 'Image'),
            'meta_title' => Yii::t('product', 'Meta Title'),
            'meta_desc' => Yii::t('product', 'Meta Desc'),
            'meta_robots' => Yii::t('product', 'Meta Robots'),
            'seo_text' => Yii::t('product', 'Seo Text'),
            'product_unit_id' => Yii::t('product', 'Product Unit ID'),
            'alias' => Yii::t('product', 'Alias'),
            'populary' => Yii::t('product', 'Populary'),
            'name' => Yii::t('product', 'Name'),
            'remote_id' => Yii::t('product', 'Remote ID'),
        ];
    }

    public static function find()
    {
        return new CategoryQuery(get_called_class());
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductUnit()
    {
        return $this->hasOne(ProductUnit::className(), ['product_unit_id' => 'product_unit_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategoryNames()
    {
        return $this->hasMany(CategoryName::className(), ['category_id' => 'category_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductCategories()
    {
        return $this->hasMany(ProductCategory::className(), ['category_id' => 'category_id']);
    }

    public function getTaxGroups()
    {
        return $this->getRelations('tax_group_to_category');
    }

    public function getRemote_category()
    {
        return ArtboxTreeHelper::getArrayField($this->remote_id);
    }

    public function setRemote_category($value)
    {
        if (!empty($value) && is_array($value)) {
            $this->remote_id = ArtboxTreeHelper::setArrayField($value, false);
        }
    }

    public function getCategoryName()
    {
        return $this->hasOne(CategoryName::className(), ['category_name_id' => 'category_name_id']);
    }

    public function getName()
    {
        return empty($this->categoryName) ? null : $this->categoryName->value;
    }



    /**
     * fetch stored image file name with complete path
     * @return string
     */
    public function getImageFile()
    {
        return isset($this->image) ? '/images/category/' . $this->image : null;
    }

    /**
     * fetch stored image url
     * @return string
     */
    public function getImageUrl()
    {
        // return a default image placeholder if your source image is not found
        return isset($this->image) ? '/storage/category/'. $this->image : '/storage/no_photo.png';
    }


    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {

            if (empty($this->parent_id))
                $this->parent_id = 0;

            return true;
        }
        return false;
    }
}
