<?php
    
    namespace backend\controllers;
    
    use common\models\ProductToProject;
    use common\models\ProductToProjectSearch;
    use common\models\Project;
    use common\models\ProjectImage;
    use common\models\ProjectSearch;
    use common\modules\product\models\Product;
    use common\modules\product\models\ProductVariant;
    use Yii;
    use yii\helpers\ArrayHelper;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    use yii\filters\VerbFilter;
    use developeruz\db_rbac\behaviors\AccessBehavior;
    use yii\web\UploadedFile;
    
    /**
     * ProjectController implements the CRUD actions for Project model.
     */
    class ProjectController extends Controller
    {
        
        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                'access' => [
                    'class' => AccessBehavior::className(),
                    'rules' => [
                        'site' => [
                            [
                                'actions' => [
                                    'login',
                                    'error',
                                ],
                                'allow'   => true,
                            ],
                        ],
                    ],
                ],
                'verbs'  => [
                    'class'   => VerbFilter::className(),
                    'actions' => [
                        'delete' => [ 'POST' ],
                    ],
                ],
            ];
        }
        
        /**
         * Lists all Project models.
         * @return mixed
         */
        public function actionIndex()
        {
            $searchModel = new ProjectSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            
            return $this->render('index', [
                'searchModel'  => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }
        
        /**
         * Displays a single Project model.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionView($id)
        {
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }
        
        /**
         * Creates a new Project model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         * @return mixed
         */
        public function actionCreate()
        {
            $model = new Project();
            $model->generateLangs();
            if($model->load(Yii::$app->request->post())) {
                $model->loadLangs(\Yii::$app->request);
                if($model->save() && $model->transactionStatus) {
                    return $this->redirect([
                        'view',
                        'id' => $model->project_id,
                    ]);
                }
            }
            return $this->render('create', [
                'model'       => $model,
                'model_langs' => $model->model_langs,
            ]);
        }
        
        /**
         * Updates an existing Project model.
         * If update is successful, the browser will be redirected to the 'view' page.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionUpdate($id)
        {
            $model = $this->findModel($id);
            $model->generateLangs();
            if($model->load(Yii::$app->request->post())) {
                $model->loadLangs(\Yii::$app->request);
                if($model->save() && $model->transactionStatus) {
                    return $this->redirect([
                        'view',
                        'id' => $model->project_id,
                    ]);
                }
            }
            return $this->render('update', [
                'model'       => $model,
                'model_langs' => $model->model_langs,
            ]);
        }
        
        /**
         * Deletes an existing Project model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         *
         * @param integer $id
         *
         * @return mixed
         */
        public function actionDelete($id)
        {
            $this->findModel($id)
                 ->delete();
            
            return $this->redirect([ 'index' ]);
        }
        
        public function actionDelimg($id)
        {
            $model = ProjectImage::findOne($id);
            if(empty( $model )) {
                throw new NotFoundHttpException();
            }
            $model->delete();
            return '1';
        }
        
        public function actionProduct($id)
        {
            $model = $this->findModel($id);
            $searchModel = new ProductToProjectSearch();
            $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
            $dataProvider->query->andWhere(['project_id' => $model->project_id]);
            return $this->render('product', [
                'project'      => $model,
                'searchModel'  => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }
        
        public function actionProductCreate($id)
        {
            $project = $this->findModel($id);
            $model = new ProductToProject();
            $products = Product::find()
                               ->distinct()
                               ->select([
                                   'product_lang.name',
                                   'product.product_id',
                               ])
                               ->joinWith('variants', true, 'INNER JOIN')
                               ->joinWith('lang', true, 'INNER JOIN')
                               ->indexBy('product_id')
                               ->asArray()
                               ->column();
            $variants = [];
            if($model->load(\Yii::$app->request->post())) {
                $model->project_id = $project->project_id;
                if($model->save()) {
                    return $this->redirect([
                        'product',
                        'id' => $id,
                    ]);
                } else {
                    if(!empty( $model->product_id ) && !empty( $products[ $model->product_id ] )) {
                        $variants = ProductVariant::find()
                                                  ->select([
                                                      'product_variant_lang.name',
                                                      'product_variant.product_variant_id',
                                                  ])
                                                  ->joinWith('lang', true, 'INNER JOIN')
                                                  ->where([ 'product_variant.product_id' => $model->product_id ])
                                                  ->asArray()
                                                  ->indexBy('product_variant_id')
                                                  ->column();
                    }
                }
            }
            return $this->render('product-create', [
                'project'  => $project,
                'model'    => $model,
                'products' => $products,
                'variants' => $variants,
            ]);
        }
        
        public function actionProductUpdate($id, $product_to_project_id)
        {
            $project = $this->findModel($id);
            $model = ProductToProject::find()
                                     ->with('product')
                                     ->where([ 'product_to_project_id' => $product_to_project_id ])
                                     ->one();
            if(empty( $model )) {
                throw new NotFoundHttpException();
            }
            $model->product_id = $model->product->product_id;
            if($model->load(\Yii::$app->request->post())) {
                $model->project_id = $project->project_id;
                if($model->save()) {
                    return $this->redirect([
                        'product',
                        'id' => $id,
                    ]);
                }
            }
            $products = Product::find()
                               ->select([
                                   'product_lang.name',
                                   'product.product_id',
                               ])
                               ->joinWith('variants', true, 'INNER JOIN')
                               ->joinWith('lang', true, 'INNER JOIN')
                               ->indexBy('product_id')
                               ->asArray()
                               ->column();
            $variants = [];
            if(!empty( $model->product_id ) && !empty( $products[ $model->product_id ] )) {
                $variants = ProductVariant::find()
                                          ->select([
                                              'product_variant_lang.name',
                                              'product_variant.product_variant_id',
                                          ])
                                          ->joinWith('lang', true, 'INNER JOIN')
                                          ->where([ 'product_variant.product_id' => $model->product_id ])
                                          ->asArray()
                                          ->indexBy('product_variant_id')
                                          ->column();
            }
            return $this->render('product-create', [
                'project'  => $project,
                'model'    => $model,
                'products' => $products,
                'variants' => $variants,
            ]);
        }
        
        public function actionProductDelete($product_to_project_id)
        {
            $model = ProductToProject::find()
                                     ->where([ 'product_to_project_id' => $product_to_project_id ])
                                     ->one();
            if(empty( $model )) {
                throw new NotFoundHttpException();
            }
            $project_id = $model->project_id;
            $model->delete();
            return $this->redirect([
                'project/product',
                'id' => $project_id,
            ]);
        }
        
        public function actionGetVariants($product_id)
        {
            $response = \Yii::$app->response;
            $response->format = $response::FORMAT_JSON;
            $product = Product::find()
                              ->joinWith('variants.lang', true, 'INNER JOIN')
                              ->where([ 'product.product_id' => $product_id ])
                              ->one();
            if(empty( $product ) || empty( $product->variants )) {
                throw new NotFoundHttpException();
            }
            $variants = ArrayHelper::toArray($product->variants, [
                'common\modules\product\models\ProductVariant' => [
                    'product_variant_id',
                    'lang',
                ],
            ]);
            return $variants;
        }
        
        /**
         * Finds the Project model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         *
         * @param integer $id
         *
         * @return Project the loaded model
         * @throws NotFoundHttpException if the model cannot be found
         */
        protected function findModel($id)
        {
            if(( $model = Project::findOne($id) ) !== NULL) {
                return $model;
            } else {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
        }
    }
