<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='user';

	public function beforeAction()
    {
		if ((UserType::model()->findByPk( User::model()->findByPK(Yii::app()->user->id)->user_type_id )->type) != 'administrator' && (UserType::model()->findByPk( User::model()->findByPK(Yii::app()->user->id)->user_type_id )->type)!='superadmin')
		{
			//$this->redirect(Yii::app()->homeUrl);
			echo 'HTTP Error 401 Unauthorized! You are not an administartor | '.CHtml::link('Home',"administrator.php");
			//$this->redirect('login');
			die();
		}
		
		return true;
    }
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * 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('index','create','update','admin','delete','Changepassword', 'ajaxupdate','frontStatusChange','change_wallet','ExportUsers','Settings','Resend'
				),
                            'expression'=>'$user->isAdmin()'
				
),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionAjaxupdate()
	{
		$model=$this->loadModel($_POST['autoId']);
		if($model->isNewUser=='Y' && $model->isActive=='N')
		{
			/*******************/
			/*$mailContent = array();
			$mailContent['fullname'] = $model->fullname; 
			$mailContent['walletpassword'] = $model->wallet_password;
			
			$message = new YiiMailMessage;
			$message->view = 'emailWalletPassword';
			
			$message->setBody(array('mailContent'=>$mailContent), 'text/html');
			$message->subject = 'Dlink Wallet Password ';
			
			$message->from	=	Yii::app()->params['adminEmail'];
			$message->addTo($model->company_email_address);
			Yii::app()->mail->send($message);*/
			$model->isNewUser	=	'N';
			$model->wallet_password	=	md5($model->wallet_password);
			$model->save(false);

		}
		/*******************/
		parent::actionAjaxupdate();
	}
	
	function get_random_string($valid_chars, $length)
	{
		$random_string = "";
		$num_valid_chars = strlen($valid_chars);
		for ($i = 0; $i < $length; $i++)
		{
			$random_pick = mt_rand(1, $num_valid_chars);
			$random_char = $valid_chars[$random_pick-1];
			$random_string .= $random_char;
		}
		return $random_string;
	}

	
	public function actionChange_wallet($id,$mail=false)
	{
			$model=$this->loadModel($id);
			$model->wallet_password	= $this->get_random_string('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqestuvwxyz1234567890',8);
			$model->isWalletPaswdRequested	=	'N';
			if($mail)
			{
				$mailContent = array();
				$mailContent['fullname'] = $model->fullname; 
				$mailContent['walletpassword'] = $model->wallet_password;
				
				$message = new YiiMailMessage;
				$message->view = 'emailWalletPassword';
				
				$message->setBody(array('mailContent'=>$mailContent), 'text/html');
				$message->subject = 'Dlink Wallet Password (New) ';
				
				$message->from	=	'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
				$message->addTo($model->company_email_address);
				Yii::app()->mail->send($message);
			}
			$model->wallet_password	=	md5($model->wallet_password);
			$model->save(false);
	}
	
	public function actionFrontStatusChange($id)
	{
		$model=$this->loadModel($id);
		$model->isActive	=	($model->isActive=='Y')?'N':'Y';
		$model->save(false);
		$this->redirect(array('site/index'));
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User('signup');

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
                if(count($_POST) > 0 && isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->isActive	=	'Y';
			$model->isConfirmed	=	'Y';
			
			if($model->save())
			{
				Yii::app()->user->setFlash('success', "User created successfully!");
				$this->redirect(array('index'));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model	=	new User('update');
		$model	=	$model->findByPk($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
                if(count($_POST) > 0 && isset($_POST['User']))		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('index'));
		}
		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	/*change password of user */
	public function actionChangepassword($id)
	{
		$model	=	User::model()->findByPk($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
                if(count($_POST) > 0 && isset($_POST['User']))		{
			$model->scenario = 'change_password';
			$model->password=$_POST['User']['password'];
			$model->repeat_password=$_POST['User']['repeat_password'];
			if($model->validate())
			{
				$model->save();
				$this->redirect(array('index'));
			}
		}
		$this->render('changepassword',array(
			'model'=>$model,
		));
	}
	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

		/**
	 * Manages all models.
	 */
	public function actionIndex($isActive=null)
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if($isActive!=null)
			$model->isActive	=	$isActive;
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	public function actionSettings()
	{
		$model	=	Settings::model()->findByPK(1);
		if(isset($_POST['Settings']))		{
			$model->attributes = $_POST['Settings'];
			$model->save();
			Yii::app()->user->setFlash('success', "Template changed!");
		}
		$this->render('settings',array(
			'model'=>$model,
		));
	}
        
        public function actionExportUsers()
        {
            $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
            if(count($_POST) > 0 && isset($_POST['country_id']))		{
                        $model	=	User::model()->findAll(array('condition'=>'user_type_id <> 3 AND country_id="'.$_POST['country_id'].'"'));
                        $country    =   Country::model()->findByPK($_POST['country_id'])->country;
                        //$model	=	User::model()->findAll(array('condition'=>'isActive="Y"'));
                        $data=array();
                        $data[1]    =   array (
                            'Name', 
                            'Company Email Address',
                            'Personal Email Address',
                            'Company',
                            'Designation',
                            'Mobile Number',
                            'Industry',
                            'Country',
                            'Address',
                            'City',
                            'Zip');
                        foreach($model as $i=>$eachUser)
                        {
                             $data[$i+2][0]    =   $eachUser->fullname;
                             $data[$i+2][1]    =   $eachUser->company_email_address;
                             $data[$i+2][2]    =   $eachUser->personal_email;
                             $data[$i+2][3]    =   $eachUser->company_name;
                             $data[$i+2][4]    =   $eachUser->designation;
                             $data[$i+2][5]    =   $eachUser->mobile_number;
                             $data[$i+2][6]    =   Industry::model()->findByPK($eachUser->industry_id)->industry;
                             $data[$i+2][7]    =   $country;
                             $data[$i+2][8]    =   $eachUser->postal_address; 
                             $data[$i+2][9]    =   $eachUser->city; 
                             $data[$i+2][10]   =   $eachUser->zip;                   
                             
                        }
                        
                        header('Content-type: application/ms-excel');
                        Yii::import('application.extensions.phpexcel.JPhpExcel');
                        $xls = new JPhpExcel('UTF-8', false, 'My Test Sheet');
                        $xls->addArray($data);
                        
                        $xls->generateXML('Users_from_'.$country);
                        
                        
                        ob_flush();
                        die();
                        
		}
            
            $this->render('export_form',array(
			'model'=>$model,
		));
        }
        
        public function actionResend($id=null) //send mail to users those yet to confirm tre email address
	{
				if($id==null)
					$condition	=	'isConfirmed="N"';
				else
					$condition	=	'id='.$id.' AND isConfirmed="N"';
				$models	=	User::model()->findAll(array('condition'=>$condition));
				foreach($models as $i=>$model)
				{
				$mailContent = array();
				$mailContent['fullname'] = $model->fullname; 
				$mailContent['confirmLink'] = 'http://www.dlinkmea.com/partner/index.php/site/confirmEmail?token='.$model->authCode;
				
				$message = new YiiMailMessage;
				$message->view = 'emailVerification';
				 
				$message->setBody(array('mailContent'=>$mailContent), 'text/html');
				$message->subject = 'Dlink Email Confirmation ';
				 
				$message->from	=	'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
				$message->addTo($model->company_email_address);
                                $message->addTo('jisha@mailbluesky');
				$message->addBcc('arun.kumar@bluesky.ae');
				$swiftAttachment = Swift_Attachment::fromPath('images/dmailsignature.jpg'); // create a Swift Attachment
				$message->attach($swiftAttachment);
				Yii::app()->mail->send($message);				
				}
	}
}
