<?php
    
    namespace frontend\controllers;
    
    use frontend\models\Feedback;
    use yii\filters\Cors;
    use yii\swiftmailer\Mailer;
    use yii\web\Controller;
    use yii\web\Response;
    
    class FeedbackController extends Controller
    {
        public $enableCsrfValidation = false;
        
        public function behaviors()
        {
            return [
                'corsFilter' => [
                    'class' => Cors::className(),
                ],
            ];
        }
        
        public function actionIndex()
        {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            
            if (\Yii::$app->request->isPost) {
                $model = new Feedback(\Yii::$app->request->post());
                if ($model->validate() && $model->save()) {
                    /**
                     * @var Mailer $mailer
                     */
                    $mailer = \Yii::$app->get('smtpmailer');
                    try {
                        $mailer->compose(
                            '@frontend/views/mail/_feedback',
                            [
                                'model' => $model,
                            ]
                        )
                               ->setFrom(
                                   [
                                       'artboxcore@gmail.com' => 'ArtBox',
                                   ]
                               )
                               ->setTo(
                                   [
                                       'kennen.md@gmail.com',
                                       'mpav@artweb.ua',
                                       'kazimirova.artweb@gmail.com',
                                   ]
                               )
                               ->setSubject('Заявка с core.artbox.net.ua')
                               ->send();
                    } catch (\Exception $e) {
                        return [
                            'status'  => true,
                            'message' => $e->getMessage(),
                        ];
                    }
                    return [
                        'status'  => true,
                        'message' => 'Success',
                    ];
                }
            }
            
            return [
                'status'  => false,
                'message' => 'Error',
            ];
        }
    }