<?php
class LoginController extends RController
{
    public $defaultAction = 'login';
    public $layout = 'login';
    /**
     * Displays the login page
     */
    public function actionLogin()
    {
	if (Yii::app()->user->isGuest === false)
	{
	    $this->redirect(array('/admin/default/index'));
	}
	$model = new UserLogin;
	// 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['UserLogin']))
	{
	    $model->attributes = $_POST['UserLogin'];
	    // validate user input and redirect to the previous page if valid
	    if ($model->validate() && $model->login()){
			$this->lastViset();
			$this->redirect(array('/admin/default/index'));
		}else
	    {
//		Yii::app()->db->createCommand()->insert("{{user_failedlogin_log}}", array(
//		    'username' => $model->encrypt($model->username),
//		    'password' => $model->encrypt($model->password),
//		    'try_logintime' => new CDbExpression("NOW()"),
//		    'ip_address' => ip2long(Yii::app()->request->getUserHostAddress()),
//		    'http_referer' => Yii::app()->request->getUrlReferrer(),
//		    'user_agent' => Yii::app()->request->getUserAgent(),
//		    'user_agent_hash' => hash('crc32', Yii::app()->request->getUserAgent()),
//		));
	    }
	}
	// display the login form
	$this->render('/user/login', array('model' => $model));
    }
    private function lastViset()
    {
		$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);

		// $y=$lastVisit->lastvisit = time();
		$lastVisit->lastvisit_at= date("Y-m-d H:i:s");;
		// var_dump($lastVisit->lastvisit_at);
		// die;
		$lastVisit->save();
    }

    public function actionLogout()
    {
	Yii::app()->user->logout();
	$this->redirect(Yii::app()->user->loginUrl);
    }
}
