<?php

namespace frontend\modules\forms\controllers;

use artbox\core\forms\DynamicModel;
use yii\web\Controller;
use yii\web\Response;

/**
 * Class SaveController
 *
 * @property \artbox\core\forms\Module $module
 * @package artbox\core\forms\controllers
 */
class SaveController extends Controller
{
	/**
	 * Custom data saving via POST
	 *
	 * @return bool|\yii\web\Response
	 * @throws \yii\base\InvalidConfigException
	 */
	public function actionNoAjax()
	{
		$returnUrl = \Yii::$app->request->referrer;
		$model = $this->module->model;
		if (\Yii::$app->request->isPost and $model->load(\Yii::$app->request->post())) {
			if ($model instanceof DynamicModel) {
				$this->sendEmail($model);
			} else {
				if ($model->save()) {
					if ($this->module->sendEmail) {
						$this->sendEmail($model);
						return $this->redirect($returnUrl);
					}
				} else {
					return false;
				}
			}
			return $this->redirect($returnUrl);

		}
		return $this->redirect($returnUrl);
	}

	/**
	 * Action that saves data submited via AJAX
	 *
	 * @return array
	 * @throws \yii\base\InvalidConfigException
	 */
	public function actionAjax()
	{
		\Yii::$app->response->format = Response::FORMAT_JSON;
		$model = $this->module->model;
		if (\Yii::$app->request->isPost and $model->load(\Yii::$app->request->post())) {
			if ($model instanceof DynamicModel) {
				$this->sendEmail($model);
				return ['status' => 'success'];
			} else {

				if ($model->save(false)) {
					if ($this->module->sendEmail) {
						$this->sendEmail($model);
						return ['status' => 'success'];
					}
					return ['status' => 'success'];
				} else {
					return ['status' => 'error','errors'=>$model->errors];
				}
			}

		}
		return ['status' => 'error','error' => 'if doesent work'];
	}

	/**
	 * @param $model
	 *
	 * @return bool
	 * @throws \yii\base\InvalidConfigException
	 */
	public function sendEmail($model)
	{

		if ($this->module->mailer == null) {
			$mailer = \Yii::$app->mailer;
		} else {
			$mailer = \Yii::$app->get($this->module->mailer);
		}
		return $mailer->compose(
			[
				'html' => $this->module->emailFile,
				'text' => $this->module->emailFile,
			],
			[$model]
		)
			->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])
			->setTo($this->module->email)
			->setSubject($this->module->subject)
			->send();
	}

}