<?php
class SiteController extends Controller
{
	
	public $layout	=	"product";	
	/*  action filters  */
	/*public function beforeAction()
    {
		if(Yii::app()->user->isGuest )
		{
			$this->layout	=	"login";
		}
		else if(!(Yii::app()->user->isAdmin()))
		{
			Yii::app()->user->logout();
			//$this->redirect(Yii::app()->homeUrl);
			//echo 'HTTP Error 401 Unauthorized! You are not an administartor | '.CHtml::link('Home',"index.php");
			$this->redirect(array('login'));
			die();
		}
		
		return true;
    }*/
	
	
	/**
	 * 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 perform 'index' and 'view' actions
				'actions'=>array('login','error','logout','test','recover'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index','ajaxupdate'),
				'expression'=>'$user->isAdmin()'
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	
	public function filters()
    {
        return array( 'accessControl' ); // perform access control for CRUD operations
    }
	
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$newUsers	=	User::model()->findAll(array(/*'condition'=>'user_type_id <> 3',*/'limit'=>5,'order'=>'id desc'));
		$caseStudies	=	Paper::model()->findAll(array('limit'=>5,'order'=>'id desc'));
		$rewards	=	Reward::model()->with('user')->findAll(array('limit'=>5,'order'=>'t.id desc'));
		$newsLetters	=	Newsletter::model()->findAll(array('condition'=>'t.isActive="Y"','limit'=>5,'order'=>'t.id desc'));
		$this->render('index',
		array('newUsers'=>$newUsers,
		'caseStudies'=>$caseStudies,
		'rewards'=>$rewards,
		'newsLetters'=>$newsLetters)
		);
		//$this->redirect(array('Product/create'));
		
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}

	/* create a passowrd */
	public function actionRecover()
	{
		$model=new User('recover');
		// if it is ajax validation request
		$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
                if(count($_POST) > 0 && isset($_POST['ajax']) && $_POST['ajax']==='admin-recover-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}	
		if(count($_POST) > 0 && isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model	= $model->findByAttributes(array('company_email_address'=>$model->company_email_address));
			if($model!=null)
			{
				$tempPswd	=	uniqid('DL');
				$model->password	=	md5($tempPswd);
				$model->save(false);
				
				$mailContent = array();
				$mailContent['company_email_address'] = $model->company_email_address; 
				$mailContent['password'] = $tempPswd; 
				
				$message = new YiiMailMessage;
				$message->view = 'forgotPassword';
				 
				$message->setBody(array('mailContent'=>$mailContent), 'text/html');
				$message->subject = 'Temporrary password';
				 
				$message->from	=	'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
				$message->addTo($model->company_email_address);
				Yii::app()->mail->send($message);				
				
				Yii::app()->user->setFlash('success','Check your mail for temporrory password.');
				$this->redirect(array('login'));
				
			}
			else
			{
				die('No such user found!');
				//$this->addError('company_email_address','No such user found!');
				Yii::app()->user->setFlash('error','No such user found!');
			}
		}
		$this->redirect(array('login'));
	}
	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new User('login');
       
		// if it is ajax validation request
		$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(!empty($_POST) && isset($_POST['ajax']) && $_POST['ajax']==='admin-login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}	

		// collect user input data
		if(!empty($_POST) && isset($_POST['User']))
		{			
			$model->attributes=$_POST['User'];			
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
			{
				$model	=	User::model()->findByPk(Yii::app()->user->id);
				$model->last_login	=	date('Y-m-d H:i:s');
				$model->save();
				$this->redirect(Yii::app()->user->returnUrl);
			}
			
		} 
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
}