<?php
namespace app\modules\user\controllers\frontend;

use app\modules\user\models\User;
use yii\filters\AccessControl;
use yii\web\Controller;
use Yii;
use app\modules\user\models\frontend\form\ProfileUpdateForm;
use app\modules\user\models\frontend\form\PasswordChangeForm;
use app\modules\user\Module;

class ProfileController extends Controller
{
	public function behaviors()
	{
		return [
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					[
						'allow' => true,
						'roles' => ['@'],
					],
				],
			],
		];
	}

	public function actionIndex()
	{
		return $this->render('index', [
			'model' => $this->findModel(),
		]);
	}

	public function actionUpdate()
	{
		$user = $this->findModel();
		$model = new ProfileUpdateForm($user);

		if ($model->load(Yii::$app->request->post()) && $model->update())
		{
			return $this->redirect(['index']);
		}
		else
		{
			return $this->render('update', [
				'model' => $model,
			]);
		}
	}

	public function actionPasswordChange()
	{
		$user = $this->findModel();
		$model = new PasswordChangeForm($user);

		if ($model->load(Yii::$app->request->post()) && $model->changePassword())
		{
			Yii::$app->getSession()
				->setFlash('success', Module::t('module', 'FLASH_PASSWORD_CHANGE_SUCCESS'));
			return $this->redirect(['index']);
		}
		else
		{
			return $this->render('passwordChange', [
				'model' => $model,
			]);
		}
	}

	/**
	 * @return User the loaded model
	 */
	private function findModel()
	{
		return User::findOne(Yii::$app->user->identity->getId());
	}
}