<?php

namespace common\modules\product\models;


use common\modules\rubrication\models\TaxGroup;
use common\modules\rubrication\models\TaxOption;
use Yii;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "product_variant".
 *
 * @property integer $product_variant_id
 * @property integer $product_id
 * @property string $name
 * @property string $remote_id
 * @property string $sku
 * @property double $price
 * @property double $price_old
 * @property double $stock
 * @property integer $status
 * @property integer $product_unit_id
 * @property integer $product_variant_type_id
 * @property ProductImage $image
 * @property array $images
 *
 * @property ProductUnit $productUnit
 */
class ProductVariant extends \yii\db\ActiveRecord
{

    /**just for rukzachok**/
    public $count;
    public $sum_cost;
    public $product_name;
    //public $image;
    public $translit;
    public $translit_rubric;
    private $data;
    public $_options = [];


    /** @var array $_images */
    public $imagesUpload = '';

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'product_unit_id'], 'required'],
            [['product_id', 'product_unit_id', 'product_variant_type_id','status'], 'integer'],
            ['status', 'default', 'value' => 0],
            [['price', 'price_old', 'stock'], 'number'],
            [['name', 'sku'], 'string', 'max' => 255],
            [['remote_id'], 'string', 'max' => 20],
            [['options', 'imagesUpload'], 'safe'],
//            [['imagesUpload'], 'safe'],
//            [['imagesUpload'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, gif', 'maxFiles' => 50],
            [['product_unit_id'], 'exist', 'skipOnError' => true, 'targetClass' => ProductUnit::className(), 'targetAttribute' => ['product_unit_id' => 'product_unit_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'product_variant_id' => Yii::t('product', 'Product Variant ID'),
            'product_id' => Yii::t('product', 'Product ID'),
            'name' => Yii::t('product', 'Name'),
            'sku' => Yii::t('product', 'Sku'),
            'price' => Yii::t('product', 'Price'),
            'price_old' => Yii::t('product', 'Price Old'),
            'stock' => Yii::t('product', 'Stock'),
            'product_unit_id' => Yii::t('product', 'Product Unit ID'),
            'product_variant_type_id' => Yii::t('product', 'Product Variant Type ID'),
            'stock_caption' => Yii::t('product', 'Stock'),
            'image' => Yii::t('product', 'Image'),
            'images' => Yii::t('product', 'Images'),
            'status' => Yii::t('product', 'Снят с производства'),
        ];
    }

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

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

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

    public function getProductStock() {
        return $this->hasMany(ProductStock::className(), ['product_variant_id' => 'product_variant_id']);
    }

    public function getQuantity() {
        return ProductStock::find()
            ->where(['product_variant_id' => $this->product_variant_id])
            ->sum('quantity');
    }

    public function getStock_caption() {
        return is_null($this->stock) ? '∞' : ($this->stock > 0 ? Yii::t('product', 'Enable') : Yii::t('product', 'Disable')); // intval($this->stock);
    }

    public function getVariantStocks(){

        return $this->hasMany(ProductStock::className(),['product_variant_id'=> 'product_variant_id'])->joinWith('stock');
    }


    public function getStocks(){

        return $this->hasMany(Stock::className(),['stock_id'=>'stock_id'])
            ->viaTable(ProductStock::tableName(),['product_variant_id'=> 'product_variant_id']);
    }


    public function getFilters(){

        return $this->hasMany(TaxOption::className(), ['tax_option_id' => 'option_id'])
            ->viaTable('product_variant_option',[ 'product_variant_id'=> 'product_variant_id'])
            ->joinWith('taxGroup');
    }


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

    /**
     * fetch stored image url
     * @return string
     */
    public function getImageUrl()
    {
        // return a default image placeholder if your source image is not found
        return (!empty($this->image) &&  file_exists(Yii::getAlias('@productsDir') . "/" . $this->image->image )) ? $this->image->imageUrl : '/storage/no_photo.png';
    }

    public function getFullname() {
       return empty($this->product) ? null : ($this->product->name . (empty($this->name) ? '' : ' '. $this->name));
    }

    public function getImagesHTML() {
        $op = [];
        if ($this->images) {
            foreach ($this->images as $image) {
                $op[] = \common\components\artboximage\ArtboxImageHelper::getImage($image->imageUrl, 'admin_thumb');
            }
        }
        return $op;
    }

    public function getImagesConfig() {
        $op = [];
        if ($this->images) {
            foreach ($this->images as $image) {
                $op[] = [
                    'caption' => $image->image,
                    'width' => '120px',
                    'url' => \yii\helpers\Url::to(['/product/manage/delimg', 'id' => $image->product_image_id]),
                    'key' => $image->product_image_id,
                    'extra' => [
                        'id' => $image->product_image_id,
                    ],
                ];
            }
        }
        return $op;
    }

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

    public function getOptions() {
        return $this->hasMany(TaxOption::className(), ['tax_option_id' => 'option_id'])->viaTable('product_variant_option', ['product_variant_id' => 'product_variant_id']);
    }

    public function setOptions($value){
        $this->_options = $value;
    }

    public function getProperties() {
        $groups = $options = [];
        foreach ($this->options as $option) {
            $options[$option->tax_group_id][] = $option;
        }
        foreach (TaxGroup::find()->where(['tax_group_id' => array_keys($options)])->all() as $group) {
            if (!empty($options[$group->tax_group_id])) {
                $group->_options = $options[$group->tax_group_id];
                $groups[] = $group;
            }
        }
        return $groups;
    }
    

    public function getId(){
        return $this->product_variant_id;
    }

    public function setStocks($stocks) {
        $this->stocks = (array) $stocks;
    }

    public function getCategory() {
        return $this->hasOne(Category::className(), ['category_id' => 'category_id'])->viaTable('product_category', ['product_id' => 'product_id']);
    }
    
    public function getCategories() {
        return $this->hasMany(Category::className(), ['category_id' => 'category_id'])->viaTable('product_category', ['product_id' => 'product_id']);
    }
    
    public function getTaxGroupsByLevel($level)
    {
        $categories = ArrayHelper::getColumn($this->categories, 'category_id');
        return TaxGroup::find()->distinct()->innerJoin('tax_group_to_category', 'tax_group_to_category.tax_group_id = tax_group.tax_group_id')->where(['tax_group_to_category.category_id'  => $categories])->where(['level' => $level]);
    }

    public function afterSave($insert, $changedAttributes)
    {

        if(!empty($this->_options)){
            $options = TaxOption::findAll($this->_options);
            $this->unlinkAll('options',true);
            foreach($options as $option){
                $this->link('options', $option);
            }
        }


//        if (!is_null($this->stocks)) {
//            //ProductStock::deleteAll(['product_variant_id' => $this->product_variant_id]);
//            $values = [];
//            foreach ($this->stocks as $id => $quantity) {
//                $productStock = ProductStock::find()->where(['product_variant_id' => $this->product_variant_id, 'stock_id' => $id])->one();
//                $productStock->quantity = $quantity;
//                $productStock->save();
//            }
//        }
        parent::afterSave($insert, $changedAttributes);
    }

    public function beforeDelete() {
        if(parent::beforeDelete()){
            ProductVariantOption::deleteAll(['product_variant_id' => $this->product_variant_id]);
            ProductImage::deleteAll(['product_variant_id' => $this->product_variant_id]);
            ProductStock::deleteAll(['product_variant_id' => $this->product_variant_id]);
            return true;
        }
        return false;
    }

    public function imagesUpload()
    {
        if ($this->validate()) {
            $images = [];
            foreach ($this->imagesUpload as $image) {
                $imageName = $image->baseName .'.'. $image->extension;
                $i = 0;
                while(file_exists(Yii::getAlias('@imagesDir/products/' . $imageName))) {
                    $i++;
                    $imageName = $image->baseName .'_'. $i .'.'. $image->extension;
                }

                $image->saveAs(Yii::getAlias('@imagesDir/products/' .$imageName));
                $images[] = $imageName;
            }
            return $images;
        } else {
            return false;
        }
    }
}
