<?php
/**
 * User: Warren Xia
 * Date: 15/9/8
 * Time: 下午10:16
 */
class AccountController extends Controller
{
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to access 'index' and 'view' actions.
              'actions'=>array('register','login'),
              'users'=>array('*'),
            ),
            array('allow', // allow authenticated users to access all actions
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
     * 注册
     */
    public function actionRegister()
    {
        $model = new User;
        $authAssignment = new Authassignment;
        if(isset($_POST['User']))
        {
            //var_dump($_POST['User']);die;
            $model->attributes = $_POST['User'];
            $model->password = md5($_POST['User']['password']);
            if($model->save())
            {
                $authAssignment->itemname = 'Authenticated';
                $authAssignment->userid = $model->attributes['id'];
                $authAssignment->save();

                Yii::app()->user->setFlash('register_success','注册成功，请登录系统!');
                $this->redirect('/account/login');
            }
        }
        $this->render('register',array(
            'model'=>$model,
            'group'=>$this->loadGroup(),
        ));
    }
    /**
     * 登陆
     */
    public function actionLogin()
    {
        $model=new LoginForm;
        // if it is ajax validation request
        if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        // collect user input data
        if(isset($_POST['LoginForm']))
        {
            $model->attributes=$_POST['LoginForm'];
            // validate user input and redirect to the previous page if valid
            if($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }
        // display the login form
        $this->renderPartial('login',array('model'=>$model));
    }

    /**
     * 退出
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }
    /**
     * 账号设置
     */
    public function actionDashboard()
    {
        $profile=new ProfileForm();
        $password = new PasswordForm();
        if (Yii::app()->user->isGuest) {
            $this->redirect($this->createUrl('account/login'));
        } else {
            $model = User::model()->findByPk(Yii::app()->user->getId());
            $this->render('dashboard',array(
                'user' => $model,
                'profile' => $profile,
                'password' => $password,
            ));
        }
    }
    /**
     * 修改个人信息
     */
    public function actionUpdateProfile()
    {
        if(isset($_POST['ProfileForm'])) {
            $username = $_POST['ProfileForm']['username'];
            $result =User::model()->updateByPk(Yii::app()->user->getId(), array(
                'username' => $username,
            ));
            if ($result) {
                Yii::app()->user->setState('name', $username);
                echo CJSON::encode(array('status' => 'success'));
            } else {
                echo CJSON::encode(array('status' => 'failure'));
            }
        }
    }
    /**
     * 检测当前密码
     */
    public function actionCheckPassword()
    {
        if(isset($_POST['password'])){
            $user = User::model()->findByPk(Yii::app()->user->id);
            if ($user->password === md5($_POST['password'])) {
                echo CJSON::encode(array('status'=>'success'));
            } else {
                echo CJSON::encode(array('status'=>'failure'));
            }
        }
    }
    /**
     * 修改用户密码
     */
    public function actionChangePassword()
    {
        $passwordModel = new PasswordForm();
        $model = User::model()->findByAttributes(array('id'=>Yii::app()->user->getId()));
        if(isset($_POST['PasswordForm'])){
            $passwordModel->attributes = $_POST['PasswordForm'];
            $valid = $passwordModel->validate();
            if($valid){
                $model->password = md5($passwordModel->new_password);
                if ($model->save()) {
                    echo CJSON::encode(array('status' => 'success'));
                } else {
                    echo CJSON::encode(array('status' => 'failure'));
                }
            }
        }

    }

    /**
     * 检测E-mail是否重复
     */
    public function actionCheckEmail()
    {
        if(isset($_POST['email'])) {
            $user = User::model()->findAllByAttributes(array('email'=>$_POST['email']));
            if($user) {
                echo CJSON::encode(array('status'=>true));
            }else{
                echo CJSON::encode(array('status'=>false));
            }
        }
        if(isset($_POST['password'])){
            $user = User::model()->findByPk(Yii::app()->user->id);
            if ($user->password === md5($_POST['password'])) {
                echo CJSON::encode(array('status'=>'success'));
            } else {
                echo CJSON::encode(array('status'=>'failure'));
            }
        }
    }
}