<?php
    
    namespace frontend\controllers;
    
    use artbox\core\models\Alias;
    use common\models\Feedback;
    use artbox\core\models\Language;
    use common\models\Comment;
    use common\models\Package;
    use common\models\Question;
    use common\models\Service;
    use common\models\Settings;
    use common\models\slider\Slide;
    use common\models\Visit;
    use Yii;
    use yii\data\ActiveDataProvider;
    use yii\db\ActiveQuery;
    use yii\db\Expression;
    use yii\filters\VerbFilter;
    use yii\helpers\Json;
    use yii\swiftmailer\Mailer;
    use yii\web\BadRequestHttpException;
    use yii\web\Controller;
    use yii\web\Response;
    use common\components\MailerComponent;
    use common\models\Doctor;
    
    /**
     * Site controller
     */
    class SiteController extends Controller
    {
        /**
         * @inheritdoc
         */
        public function actions()
        {
            return [
                'error' => [
                    'class' => 'yii\web\ErrorAction',
                ],
            ];
        }
        
        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class'   => VerbFilter::className(),
                    'actions' => [
                        'feedback' => [ 'post' ],
                    ],
                ],
            ];
        }
        
        /**
         * Displays homepage.
         *
         * @return mixed
         */
        public function actionIndex()
        {
	        $slides = Slide::find()
                           ->with('language')
                           ->where([ 'status' => true ])
                           ->orderBy('sort')
                           ->with('language.image')
                           ->all();
            $services = Service::find()
                               ->where(
                                   [
                                       'is not',
                                       'image_id',
                                       null,
                                   ]
                               )
                               ->andWhere(
                                   [
                                       'status' => true,
                                       'level'  => 0,
                                   ]
                               )
                               ->with(
                                   [
                                       'image',
                                       'language.alias',
                                       'services' => function (ActiveQuery $query) {
                                           $query->where([ 'status' => true ])
                                                 ->with([ 'language.alias' ]);
                                       },
                                   ]
                               )
                               ->orderBy([ new Expression('sort ASC NULLS LAST') ])
                               ->all();
            $comments = Comment::find()
                               ->where(
                                   [
                                       'status'  => true,
                                       'on_main' => true,
                                   ]
                               )
                               ->limit(6)
                               ->all();
            
            $package = Package::find()
                              ->with(
                                  [
                                      'language.alias',
                                      'image',
                                  ]
                              )
                              ->where([ 'status' => true ])
                              ->orderBy('sort')
                              ->limit(3)
                              ->all();
            $doctors = Doctor::find()
                ->where(['status' => true])
                ->orderBy([
                    'sort' => SORT_ASC,
                    'id' => SORT_ASC
                ])
                ->all();
            $settings = Settings::getInstance();
            return $this->render(
                'index',
                [
                    'slides'   => $slides,
                    'services' => $services,
                    'comments' => $comments,
                    'settings' => $settings,
                    'package'  => $package,
                    'docs'      => $doctors
                ]
            );
        }
        
        /**
         * Displays contact page.
         *
         * @return mixed
         */
        public function actionContact()
        {
            $contact = new Feedback();
            $settings = Settings::getInstance();
            return $this->render(
                'contact',
                [
                    'contact'  => $contact,
                    'settings' => $settings,
                ]
            );
        }


	    /**
         * Action to view robots.txt file dinamycli
         *
         * @return string
         */
        public function actionRobots()
        {
            $response = \Yii::$app->response;
            /**
             * @var Settings $settings
             */
            $settings = Settings::find()
                                ->one();
            $temp = tmpfile();
            fwrite($temp, $settings->robots);
            $meta = stream_get_meta_data($temp);
            $response->format = $response::FORMAT_RAW;
            $response->headers->set('Content-Type', 'text/plain');
            return $this->renderFile($meta[ 'uri' ]);
        }

        public function actionCallback(){

	        \Yii::$app->response->format = Response::FORMAT_JSON;
            $model = new Visit();
            if ($model->load(\Yii::$app->request->post()) && $model->save()){
	            $mode = $model->time;
	            MailerComponent::sendListToAdminAfterSubmit($mode, ['user_data' => $model->phone]);
	            return ['success' => true];
            }else{
                return ['success' => false, 'errors' => $model->errors];
            }
        }
        
        public function actionFeedback()
        {
            Yii::$app->response->format = Response::FORMAT_JSON;
            
            /**
             * @var Mailer $mailer
             */
            $mailer = \Yii::$app->get('smtpmailer');
            $settings = Settings::getInstance();

	        if (empty(Yii::$app->request->post())) {
                throw new BadRequestHttpException();
            } else {
                $model = new Feedback();
                if ($model->load(Yii::$app->request->post()) && $model->save()) {
                    
                    $mailer->compose(
                        'feedback',
                        [
                            'model' => $model,
                        ]
                    )
                           ->setFrom('artbox@domain.com')
                           ->setTo($settings->email)
                           ->setSubject(\Yii::t('app', 'Feedback'))
                           ->send();
                    
                    return [
                        'success' => true,
                        'message' => 'Success message',
                        'alert'   => '<div class="alert alert-success">
            <h3>Success</h3>
            <p>
              Success text
            </p>
          </div>',
                    ];
                } else {
                    return [
                        'success' => false,
                        'error'   => $model->errors,
                    ];
                }
            }
        }
        public function actionPrices()
        {
            $services = Service::find()
                               ->innerJoinWith(
                                   [
                                       'prices' => function (ActiveQuery $query) {
                                           $query->where([ 'price.status' => true ])
                                                 ->with('language');
                                       },
                                   ]
                               )
                               ->with('language.alias')
                               ->all();
            
            return $this->render(
                'prices',
                [
                    'services' => $services,
                ]
            );
        }
        
        public function actionPage1()
        {
            return $this->render('page1');
        }
        
        public function actionPage2()
        {
            return $this->render('page2');
        }
        
        public function actionPage22()
        {
            return $this->render('page2-2');
        }
        
        public function actionPage23()
        {
            return $this->render('page2-3');
        }
        
        public function actionPage3()
        {
            return $this->render('page3');
        }
        
        public function actionPage4()
        {
            return $this->render('page4');
        }
        
        public function actionPage5()
        {
            return $this->render('page5');
        }
        
        public function actionPage6()
        {
            return $this->render('page6');
        }

        public function actionDoctor()
        {
	        $doctors = Doctor::find()
		        ->where(['status' => true])
		        ->orderBy([
			        'sort' => SORT_ASC,
			        'id' => SORT_ASC
		        ])
		        ->all();

	        return $this->render('doctor',
		        [
			        'docs' => $doctors
		        ]);
        }
        
        # Вопрос/ответ
        public function actionQuestions($service_id = null)
        {
            Language::getCurrent();
            
            if (\Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $model = new Question();
                $model->scenario = Question::SCENARIO_QUESTION;
                if ($model->load(\Yii::$app->request->post()) and $model->save()) {
                    return [
                        'status'  => true,
                        'message' => 'Спасибо за Ваш вопрос',
                    ];
                } else {
                    return [
                        'status'  => false,
                        'message' => 'Ошибка',
                    ];
                }
            }
            $dataProvider = new ActiveDataProvider(
                [
                    'query'      => Question::find()
                                            ->where([ 'status' => true ])
                                            ->andFilterWhere([ 'service_id' => $service_id ])
                                            ->with([ 'doctor.language' ]),
                    'pagination' => [
                        'pageSize' => 10,
                    ],
                ]
            );
            $services = Service::find()
                               ->where([ 'status' => true ])
                               ->andWhere([ 'parent_id' => null ])
                               ->with('language')
                               ->all();
            $route = [];
            foreach ($services as $service) {
                $route[] = Json::encode(
                    [
                        'site/questions',
                        'service_id' => $service->id,
                    ]
                );
            }
            $route [] = '{"0":"site/questions"}';
            $alias = Alias::find()
                          ->where([ 'route' => $route ])
                          ->andWhere([ 'language_id' => Language::getCurrent()->id ])
                          ->indexBy('route')
                          ->asArray()
                          ->all();
            return $this->render(
                'questions',
                [
                    'dataProvider' => $dataProvider,
                    'services'     => $services,
                    'service_id'   => $service_id,
                    'alias'        => $alias,
                ]
            );
        }
        
        public function actionComments($service_id = null)
        {
            
            if (\Yii::$app->request->isAjax) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                $model = new Comment();
                #if ($model->load(\Yii::$app->request->post()) and $model->save()){
                if ($model->load(\Yii::$app->request->post())) {
                    if (!$model->entity_id) {
                        $model->entity_id = 0;
                    }
                    $model->entity = Service::className();
                    $model->save();
                    return [
                        'status'  => true,
                        'message' => 'Спасибо за Ваш отзыв. После проверки модератором он появится на сайте',
                    ];
                } else {
                    return [
                        'status'  => false,
                        'message' => 'Ошибка',
                    ];
                }
            }
            
            # подкоректировал логику для сохранрения в БД/выдачи вопросов с категории "Общие вопросы"
            # закрепил за ними entity_id=0
            if($service_id==null)$service_id=0;
            $dataProvider = new ActiveDataProvider([
                                                       'query' => Comment::find()
                                                           ->where(['status' => true])
                                                           ->andWhere(['entity' => Service::className()])
                                                           ->andFilterWhere(['entity_id' => $service_id])//'SELECT * FROM \"comment\" WHERE (\"status\"=TRUE) AND (\"entity\"=\'common\\models\\Service\')'
                                                           ->orderBy(['id'=>SORT_DESC]),
                                                        'pagination' => [
                                                           'pageSize' => 10,
                                                       ],

                                                   ]);
            $services = Service::find()->where(['status' => true])->andWhere(['parent_id' => null])->all();

            return $this->render('comments', [
                'dataProvider' => $dataProvider,
                'services'  => $services,
                'service_id' => $service_id
            ]);
        }
    }
