<?php

/*
 * This file is part of the Dektrium project.
 *
 * (c) Dektrium project <http://github.com/dektrium/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace dektrium\user\controllers;

use yii;
use dektrium\user\Finder;
use dektrium\user\models\AddForm;
use dektrium\user\models\User;
use dektrium\user\helpers\RoleHelper;
use dektrium\user\helpers\Password;
use yii\base\Model;
use yii\web\Controller;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * AdminController allows you to administrate users.
 *
 * @property \dektrium\user\Module $module
 * @author Dmitry Erofeev <dmeroff@gmail.com
 */
class UpdateController extends Controller {

    /** @var Finder */
    protected $finder;
    public $defaultAction = 'update';

    /**
     * @param string $id
     * @param \yii\base\Module $module
     * @param Finder $finder
     * @param array $config
     */
    public function __construct($id, $module, Finder $finder, $config = []) {
        $this->finder = $finder;
        parent::__construct($id, $module, $config);
    }

    /** @inheritdoc */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['update', 'change'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ]
            ]
        ];
    }

    public function actionUpdate($id) {
        $user = $this->findModel($id);
        $user->scenario = 'update';
        $profile = $this->finder->findUserById($id);
        $r = \Yii::$app->request;

        $this->performAjaxValidation([$user]);

        if ($user->load($r->post()) && $user->save()) {
            \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'User has been updated'));
            return $this->redirect([User::getUserUrl() . '/user']);
        }

        return $this->render('update', [
                    'user' => $user,
                    'module' => $this->module,
        ]);
    }

     public function actionChange()
     {
	  $model=$this->findModel(Yii::$app->user->id);
	  $model->scenario = 'change';

		if(isset($_POST['User']))
		{
			$model->attributes = $_POST['User'];
			$user = User::findOne(Yii::$app->user->id);
			$model->password_hash = Password::hash($model->new_pass);
			if($model->save())
				return $this->redirect(['/dashboard']);
		}
	   return $this->render('password_changeform',['model'=>$model]);
     }
	
    protected function findModel($id) {
        $user = $this->finder->findUserById($id);

        if ($user === null) {
            throw new NotFoundHttpException('The requested page does not exist');
        }
        return $user;
    }

    /**
     * Performs AJAX validation.
     * @param array|Model $models
     * @throws \yii\base\ExitException
     */
    protected function performAjaxValidation($models) {
        if (\Yii::$app->request->isAjax) {
            if (is_array($models)) {
                $result = [];
                foreach ($models as $model) {
                    if ($model->load(\Yii::$app->request->post())) {
                        \Yii::$app->response->format = Response::FORMAT_JSON;
                        $result = array_merge($result, ActiveForm::validate($model));
                    }
                }
                echo json_encode($result);
                \Yii::$app->end();
            } else {
                if ($models->load(\Yii::$app->request->post())) {
                    \Yii::$app->response->format = Response::FORMAT_JSON;
                    echo json_encode(ActiveForm::validate($models));
                    \Yii::$app->end();
                }
            }
        }
    }

}
