<?php defined('MW_PATH') || exit('No direct script access allowed');

/**
 * GuestController
 * 
 * Handles the actions for guest related tasks
 * 
 * @package MailWizz EMA
 * @author Serban George Cristian <cristian.serban@mailwizz.com> 
 * @link http://www.mailwizz.com/
 * @copyright 2013-2014 MailWizz EMA (http://www.mailwizz.com)
 * @license http://www.mailwizz.com/license/
 * @since 1.0
 */
 
class UserController extends Controller
{
    public $layout = 'sub_account';
     public function actions()
	{  
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xC4DBFF,
				'foreColor'=>0xffffff,
				'height'=>32,
				'width'=>130,
				'testLimit'=>1,
				'offset'=>3
			),
			// 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',
			),
		);
	}
    public function  Init()
    {
		$this->getData('pageStyles')->add(array('src' => Yii::app()->baseUrl."/backend/assets/css/table2.css"));
		$this->getData('pageScripts')->add(array('src' => AssetsUrl::js('reservetrip.js')));
		$this->getData('pageScripts')->add(array('src' => AssetsUrl::js('jquery.jqtransform.js')));
		$this->getData('pageStyles')->add(array('src' => AssetsUrl::css('jqtransform.css')));
	}
    /**
     * Display the login form so that a guest can login and become an administrator
     */
    public function actionSignin()
    {
		
		$this->layout =   Yii::app()->LayoutClass->layoutpath("fullwidth");
        $model = new UserLogin();
        $request = Yii::app()->request;
      //  print_r($_POST);
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			 
			//print_r($_POST);exit;
            $model->attributes = $attributes;
            if ($model->validate()) {
			    if(Yii::app()->user->returnUrl)
			    {
				  $this->redirect(Yii::app()->user->returnUrl);
			    }
			    else
			    {
                   $this->redirect(Yii::app()->createUrl('user/my_profile'));
		        }
            }
        }
        
        $this->setData(array(
            'pageMetaTitle' => Yii::app()->name . ' | '. Yii::t('users', 'Please login'), 
            'pageHeading'   => Yii::t('users', 'Please login'),
        ));
        
        $this->render(Yii::app()->LayoutClass->viewpath("login"), compact('model'));
    }
    public function actionLogin()
    {
		 
		 
        $model = new UserLogin();
        $request = Yii::app()->request;
      //  print_r($_POST);
        if ($request->isPostRequest && ($attributes = $_POST)) {
			 
			
            $model->attributes = $attributes;
            $model->email = $_POST['username'];
          //  print_r($model->attributes);exit;
            if ($model->validate()) {
			    if(Yii::app()->user->returnUrl)
			    {
				  $this->redirect(Yii::app()->user->returnUrl);
			    }
			    else
			    {
                   $this->redirect(Yii::app()->createUrl('user/my_profile'));
		        }
            }
            else
        {
			 Yii::app()->user->setFlash('loginfail',CHtml::errorSummary($model));
			 
			 $this->redirect(Yii::app()->createUrl('user/signin'));
			
		}
        }
        
    }
    public function actionSignup()
    {
		$this->layout =   Yii::app()->LayoutClass->layoutpath("fullwidth");
        $model = new ListingUsers();
        $request = Yii::app()->request;
        
         
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
			 
			//print_r($_POST);exit;
            $model->attributes = $attributes;
            if ($model->save()) {
				 
				 Yii::app()->user->setFlash('success','1');
                $this->redirect(Yii::app()->createUrl('user/signup'));
            }
         
        }
        
        $this->setData(array(
            'pageMetaTitle' => Yii::app()->name . ' | '. Yii::t('users', 'Please login'), 
            'pageHeading'   => Yii::t('users', 'Please login'),
        ));
        
        $this->render(Yii::app()->LayoutClass->viewpath("register"), compact('model'));
    }
    public function actionRegister()
    {
		 
		 
        $model = new ListingUsers();
        $request = Yii::app()->request;
       
        if ($request->isPostRequest && ($attributes = (array)$_POST) ) {
			 
			// print_r($_POST);exit;
            $model->attributes = $attributes;
            $model->con_password= $_POST['password2'];
            $model->password= $_POST['password1'];
            
            if(isset($_POST['dob_year']))
            {
				$model->dob = $_POST['dob_year'].'-'.$_POST['dob_month'].'-'.$_POST['dob_day'] ;
			}
         //  print_r($model->attributes);exit;
             $model->status='I';
            $model->verification_code = md5(uniqid(rand(), true));
            if ($model->save()) {
				
				$emailTemplate =  CustomerEmailTemplate::model()->findByName("registration");
			    if($emailTemplate)
			    {
					 $emailTemplate = $emailTemplate->content;
				}
				else
				{
					    $emailTemplate = $options->get('system.email_templates.common');
				}
				 
                $emailBody = $this->renderPartial('_registration_verification', compact('model'), true);
                $emailTemplate = str_replace('[CONTENT]', $emailBody, $emailTemplate);
                $mail = new YiiMailer();
				$mail->setFrom(Yii::app()->params['admin_email'], Yii::app()->name );
				$mail->setTo($model->email);
				$mail->setView('email');
				$mail->setSubject(Yii::app()->name .' Account created . Explore your new account ');
				$mail->setData(array('emailTemplate' => $emailTemplate));
			    $mail->send();
				Yii::app()->user->setFlash('registered','1');
				 
                $this->redirect(Yii::app()->createUrl('user/signup'));
            }
            else
            {
				 
				 Yii::app()->user->setFlash('registerfail',CHtml::errorSummary($model));
			 
				 $this->redirect(Yii::app()->createUrl('user/signup'));
			}
            //	exit;
            
        }
        
        
    }
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->user->loginUrl);    
    }
    
    /**
     * Display the form to retrieve a forgotten password.
     */
    public function actionForgot_password()
    {
		$this->layout =   Yii::app()->LayoutClass->layoutpath("fullwidth");
		Yii::import('webroot.apps.extensions.YiiMailer.YiiMailer');
		 
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $model = new ListingUserPasswordReset();
        
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($model->modelName, array()))) {
            $model->attributes = $attributes;
            if (!$model->validate()) {
                $notify->addError(Yii::t('app', 'Please fix your form errors!'));
            } else {
				
                $options = Yii::app()->options;
                $user = ListingUsers::model()->findByAttributes(array('email' => $model->email));
                $model->user_id = $user->user_id;
                $model->save(false);
                
                $emailTemplate = $options->get('system.email_templates.common');
                $emailBody = $this->renderPartial('_email-reset-key', compact('model', 'user'), true);
                $emailTemplate = str_replace('[CONTENT]', $emailBody, $emailTemplate);
                $mail = new YiiMailer();
				$mail->setFrom(Yii::app()->params['forgot_password_mail'], Yii::app()->name);
				$mail->setTo($user->email);
				$mail->setView('forgotpassword');
				$mail->setSubject('Reset Password Link '.Yii::app()->name);
				$mail->setData(array('emailTemplate' => $emailTemplate));
				 if (!$mail->send()){
					    Yii::app()->user->setFlash('failure','Temporary error while sending your email, please try again later or contact us!');
                } else {
                         Yii::app()->user->setFlash('success','Please check your email address.');
                         $model->unsetAttributes();
                         $model->email = null;
                }

                
            }
        }
     
      

        $this->render(Yii::app()->LayoutClass->viewpath("forgot_password"), compact('model'));
    }
    public function actionForgot_password_new()
    {
		$this->layout =   Yii::app()->LayoutClass->layoutpath("fullwidth");
		Yii::import('webroot.apps.extensions.YiiMailer.YiiMailer');
		 
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $model = new ListingUserPasswordReset();
        
        if ($request->isPostRequest && ($attributes = (array)$_POST)) {
			 
            $model->attributes = $attributes;
            $model->email=@$attributes['username'];
            if (!$model->validate()) {
			 
				 Yii::app()->user->setFlash('forgotfail',CHtml::errorSummary($model));
				 $this->redirect(Yii::app()->createUrl('user/forgot_password'));
            } else {
				
				 
                $options = Yii::app()->options;
                $user = ListingUsers::model()->findByAttributes(array('email' => $model->email));
                $model->user_id = $user->user_id;
                $model->save(false);
                
                $emailTemplate = $options->get('system.email_templates.common');
                $emailBody = $this->renderPartial('_email-reset-key', compact('model', 'user'), true);
                $emailTemplate = str_replace('[CONTENT]', $emailBody, $emailTemplate);
                $mail = new YiiMailer();
				$mail->setFrom(Yii::app()->params['forgot_password_mail'], Yii::app()->name);
				$mail->setTo($user->email);
				$mail->setView('forgotpassword');
				$mail->setSubject('Reset Password Link '.Yii::app()->name);
				$mail->setData(array('emailTemplate' => $emailTemplate));
				 if (!$mail->send()){
					    Yii::app()->user->setFlash('forgotfail','Temporary error while sending your email, please try again later or contact us!');
                } else {
                         Yii::app()->user->setFlash('forgotsuccess','Please check your email address for password reset link.');
                         $model->unsetAttributes();
                         $model->email = null;
                }

                
            }
        }
     
      

        $this->render(Yii::app()->LayoutClass->viewpath("forgot_password"), compact('model'));
    }
    
    /**
     * Reached from email, will reset the password for given user and send a new one via email.
     */
    public function actionReset_password($reset_key)
    {
		$this->layout ="sub";
		Yii::import('webroot.apps.extensions.YiiMailer.YiiMailer');
        $model = ListingUserPasswordReset::model()->findByAttributes(array(
            'reset_key' => $reset_key,
            'status'    => UserPasswordReset::STATUS_ACTIVE,
        ));
        
        if (empty($model)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        $randPassword = StringHelper::random();
        $hashedPassword = Yii::app()->passwordHasher->hash($randPassword);
        
        ListingUsers::model()->updateByPk((int)$model->user_id, array('password' => $hashedPassword));
        $model->status = ListingUserPasswordReset::STATUS_USED;
        $model->save();
        
        $options = Yii::app()->options;
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        $user = ListingUsers::model()->findByPk($model->user_id);
        $currentPassword = $user->password;
        
        
        $emailTemplate = $options->get('system.email_templates.common');
        $emailBody = $this->renderPartial('_email-new-login', compact('model', 'user', 'randPassword'), true);
        $emailTemplate = str_replace('[CONTENT]', $emailBody, $emailTemplate);
		$mail = new YiiMailer();
		$mail->setFrom(Yii::app()->params['forgot_password_mail'], Yii::app()->name);
		$mail->setTo($user->email);
		$mail->setView('resetpassword');
		$mail->setSubject(Yii::app()->name." New Password");
		$mail->setData(array('emailTemplate' => $emailTemplate));
		if (!$mail->send()){
		 
          ListingUsers::model()->updateByPk((int)$model->user_id, array('password' => $currentPassword));
          Yii::app()->user->setFlash('failure','Temporary error while sending your email containing your new login, please try again later or contact us!');
	    }
	    else
	    {
		 
			 Yii::app()->user->setFlash('success','Your new login has been successfully sent to your email address.');
		}
         
        
        $this->redirect(array('user/signin'));
    }
    public function actionMy_profile()
    {
		 
	       $this->setData(array(
            'pageMetaTitle'     =>  Yii::t('app', '{name} :: My Profile', array('{name}' => Yii::app()->name )), 
            'pageHeading'       => Yii::t('hotel_booking', 'My Profile'),
            'pageMetaDescription'   => Yii::app()->params['description'],
             
        ));
        $user =  new ListingUsers();
         $user =  $user->findByPk((int)Yii::app()->user->getId());
        if(Yii::app()->request->isPostRequest)
			{
				 
				  $attributes = (array)Yii::app()->request->getPost('ListingUsers', array());
				  $user->attributes =  $attributes;
				  if($user->save())
				  {
					  Yii::app()->user->setFlash('success','1');
					  $this->redirect(Yii::app()->createUrl('user/my_profile'));
					  
				  }
				 
				 
			}
		
		 if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
         }
         $this->render("my_profile",compact("user"));
	}
    public function actionMy_ads()
    {
		 
	       $this->setData(array(
            'pageMetaTitle'     =>  Yii::t('app', '{name} :: My Booking', array('{name}' => Yii::app()->name )), 
            'pageHeading'       => Yii::t('hotel_booking', 'My Booking'),
            'pageMetaDescription'   => Yii::app()->params['description'],
             
        ));
        $user =  new ListingUsers();
        $user =  $user->findByPk((int)Yii::app()->user->getId());
        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
         }
         
                    $criteria= new CDbCriteria;
				    $criteria->condition= "t.user_id=:uid";
				    $criteria->order="t.id desc";
				    $criteria->params[":uid"] = (int)Yii::app()->user->getId();
				    $count=PlaceAnAd::model()->count($criteria);
				    
				    $pages=new CPagination($count);
				    $pages->pageSize=10;
					$pages->applyLimit($criteria);
				    $model = PlaceAnAd::model()->findAll($criteria);
                    $this->render("my_booking",compact("user","model","pages"));
	}
    
    public function actionAccount_settings()
    {
		  $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('ui.js')));
          $this->getData('pageStyles')->add(array('src' => AssetsUrl::css('ui.css')));
		 
	       $this->setData(array(
            'pageMetaTitle'     =>  Yii::t('app', '{name} :: Account Settings', array('{name}' => Yii::app()->name )), 
            'pageHeading'       => Yii::t('hotel_booking', 'Account Settings'),
            'pageMetaDescription'   => Yii::app()->params['description'],
             
        ));
        $user =  new ListingUsers();
        $user =  $user->findByPk((int)Yii::app()->user->getId());
         $user->scenario="updatepassword";
        if(Yii::app()->request->isPostRequest)
        {
			$attributes = Yii::app()->request->getPost("ListingUsers");
			$user->attributes = $attributes;
			
			if($user->validate())
			{
				 
			    $hashedPassword = Yii::app()->passwordHasher->hash($user->password);
                ListingUsers::model()->updateByPk((int)$user->user_id, array('password' => $hashedPassword));
				Yii::app()->user->setFlash('success','succesfully updated your password');
				   $this->redirect(Yii::app()->createUrl('user/account_settings'));
			}
			 
		}
       
       
        if (empty($user)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
         }
         
                   
			$user->password="";	    
          
		
		
                     $this->render("account_settings",compact("user"));
	}
    
    /**
     * The error handler
     */
    public function actionError()
    {    
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest) {
                echo CHtml::encode($error['message']);
            } else {
                $this->setData(array(
                    'pageMetaTitle' => Yii::t('app', 'Error {code}!', array('{code}' => $error['code'])), 
                ));
                $this->render('error', $error) ;
            }    
        }
    }
}
