<?php

namespace common\modules\product\controllers;

use common\modules\product\models\Product;
use common\modules\product\models\ProductImage;
use common\modules\product\models\ProductStock;
use common\modules\product\models\ProductVariant;
use common\modules\product\models\ProductVariantListSearch;
use common\modules\product\models\Stock;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * ManageController implements the CRUD actions for ProductVariant model.
 */
class VariantController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ProductVariant models.
     * @return mixed
     */
    public function actionIndex($product_id)
    {
        $searchModel = new ProductVariantListSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$product_id);

        if ( ($product = Yii::$app->request->get('product_id')) !== null) {
            $product = Product::findOne($product);
        }

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'product' => $product,
            'product_id' => $product_id,
        ]);
    }

    /**
     * Displays a single ProductVariant model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProductVariant model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($product_id)
    {
        $model = new ProductVariant();
        $model->product_id = $product_id;
        if ($model->load(Yii::$app->request->post())) {

            $model->imagesUpload = UploadedFile::getInstances($model, 'imagesUpload');
            $model->validate();

            if ($model->save()) {

                if ( ($images = $model->imagesUpload()) !== FALSE) {
                    foreach ($images as $image) {
                        $imageModel = new ProductImage();
                        $imageModel->product_id = $model->product_id;
                        $imageModel->product_variant_id = $model->product_variant_id;
                        $imageModel->image = $image;
                        $imageModel->save();
                    }
                }

                return $this->redirect(['index', 'product_id' => $product_id]);
            }
        } else {
            $groups = $model->getTaxGroupsByLevel(1);

            return $this->render('create', [
                'model' => $model,
                'groups' => $groups,
                'stocks' => [new ProductStock()],
            ]);
        }
    }

    /**
     * Updates an existing ProductVariant model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $product_id
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($product_id, $id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            $model->unlinkAll('options',true);
            if ($model->save()) {


                if ( ($image = UploadedFile::getInstance($model, 'image')) ) {
                    $imageModel = ProductImage::find()->where(['product_variant_id' => $model->product_variant_id])->one();

                    if($imageModel instanceof ProductImage) {
                        $imageModel->product_id = $model->product_id;
                        $imageModel->product_variant_id = $model->product_variant_id;
                        $imageModel->image = $image->name;
                        $imageModel->save();
                    } else {
                        $imageModel = new ProductImage();
                        $imageModel->product_id = $model->product_id;
                        $imageModel->product_variant_id = $model->product_variant_id;
                        $imageModel->image = $image->name;
                        $imageModel->save();
                    }


                    $imgDir = Yii::getAlias('@storage/products/');

                    if(!is_dir($imgDir)) {
                        mkdir($imgDir, 0755, true);
                    }

                    $image->saveAs(Yii::getAlias('@storage/products/' . $image->name));
                }


                $ProductStocks = Yii::$app->request->post('ProductStock');

                $quantity = 0;

                if(is_array($ProductStocks)){

                    foreach($ProductStocks as $index => $ProductStock){
                        $stock = Stock::find()->where(['name'=>$ProductStock['name']])->one();
                        if(!$stock instanceof Stock){
                            $stock = new Stock();
                            $stock->name = $ProductStock['name'];
                            $stock->save();
                        }

                        $psModel = ProductStock::find()->where(['product_variant_id'=>$model->product_variant_id, 'stock_id' =>$stock->stock_id ])->one();
                        if(!$psModel instanceof ProductStock){
                            $psModel = new ProductStock;
                            $psModel->load(['ProductStock'=>$ProductStock]);
                            $psModel->stock_id = $stock->stock_id;
                            $psModel->product_variant_id = $model->product_variant_id;
                            $psModel->product_id = $model->product->product_id;
                            $quantity = $quantity + $psModel->quantity;
                            $psModel->validate();
                            $psModel->save();
                        } else {
                            $psModel->load(['ProductStock'=>$ProductStock]);
                            $quantity = $quantity + $psModel->quantity;
                            $psModel->save();
                        }

                    }
                } else {
                    $model->unlinkAll('stocks',true);
                }


                $model->stock = $quantity;
                $model->save();
            }
            return $this->redirect(['index', 'product_id'=>$product_id]);




        } else {
            $groups = $model->getTaxGroupsByLevel(1);

            return $this->render('update', [
                'model' => $model,
                'groups' => $groups,
                'stocks' => (!empty($model->variantStocks)) ? $model->variantStocks : [new ProductStock],
            ]);
        }
    }

    /**
     * Deletes an existing ProductVariant model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($product_id, $id)
    {

        $this->findModel($id)->delete();

        return $this->redirect(['index', 'product_id'=>$product_id]);
    }

    public function actionDelimg($id)
    {
        $image = ProductImage::findOne($id);

        if ($image) {
            $image->delete();
        }

        print '1';
        exit;
    }

    /**
     * Finds the ProductVariant model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProductVariant the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProductVariant::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
