<?php

/**
*
* @package Free Tube Script
* @version v1.0
* @copyright (c) 2011 Agriz
* @license GNU Public License Under Certain Conditions [Powered by should remain unchanged]
* @contact http://www.agrizlive.com
*
*/

class UsersController extends AppController {
	var $name = 'Users';
	var $components = array('Auth','Email','Captcha','Password');
	var $helpers = array('Captcha','Html','Form','Time');
	
	function signup(){
		
		$captcha = true;
		
		if (!empty($this->data)) {
		
			if(Configure::read('MyApp.captcha_use') == "yes")
			{
				if($this->Captcha->validate()) {
					$captcha = true;
				}
				else {
					$captcha = false;
				}
			}			
			
			if($captcha) {
				$this->data['User']['password2hashed'] = $this->Auth->password($this->data['User']['password2']);
				//print_r($this->data);
				$this->User->set($this->data);
				if ($this->User->validates()) {
					if(isset($this->data['User']['password2']))					
						$this->data['User']['email_validation_key'] = String::uuid();
						$this->data['User']['userip'] = $_SERVER['REMOTE_ADDR'];
						$this->data['User']['account_status'] = 'active';
						$this->data['User']['group_id'] = '3'; //users group
						$this->User->create();
					if ($this->User->save($this->data,array('validate' => false, 'fieldList' => array('email_validation_key','userip','username','password','email','account_status','group_id'),'callbacks' => true))) {
						$id = $this->User->getLastInsertID();
						$this->sendEmail($this->data,$id);
					} else {
						$this->set('error_message',"There is a problem in signing up. Try later");
						$this->data = null;
					}
				}
				else
				{
					$User = $this->User->invalidFields();
					$data = compact('User');
					$this->set('errors', compact('message', 'data'));
				}	
			}
			else {
				$User = array("Invalid Captcha");
				$data = compact('User');
				$this->set('errors', compact('message', 'data'));
			}		
			$this->render('user_signup_ajax','ajax');	
		}
				
		$this->set('title_for_layout',"Free signup");
		$this->set('keywords_for_layout',"User signup, free signup");
		$this->set('description_for_layout',"User signup page. register for free");
	
	}
	
	function forgot() {
		if(!empty($this->data)) {
			
			$captcha = true;
			if(Configure::read('MyApp.captcha_use') == "yes")
			{
				if($this->Captcha->validate()) {
					$captcha = true;
				}
				else {
					$captcha = false;
				}
			}
			
			if($captcha) {
				$email = $this->data['User']['email'];
				$user_data = $this->User->findByEmail($email);
				
				if(empty($user_data)) {
					$this->Session->setFlash("No record found");
				}
				else {
					$password_key = String::uuid();
					$this->User->id = $user_data['User']['id'];
					$this->User->saveField('password_reset_code', $password_key);
					
					//send mail
					$this->Email->to = $user_data['User']['email'];
					$this->Email->subject = 'Reset Password';
					$this->Email->replyTo = Configure::read('MyApp.admin_email');
					$this->Email->from = Configure::read('MyApp.mail_from_name').'<'.Configure::read('MyApp.admin_email').'>';
					$this->Email->sendAs = 'html';
					$this->Email->template = 'forgot_password';
					$this->set('name', $user_data['User']['username']);
					$this->set('server_name', $_SERVER['SERVER_NAME']);
					$this->set('id', $user_data['User']['id']);
					$this->set('code', $password_key);
					if ($this->Email->send()) {
						$this->set('confirm_mail',"Confirmation mail sent");
					} else {
						//$this->User->delete($this->User->getLastInsertID());
						$this->set('error_message',"There is a problem in sending confirmation mail");
					}
					$this->Session->setFlash("Check your email to reset the password");
				}
			}	
			else {
				$this->Session->setFlash("Invalid Captcha");
			}
		}
		$this->set('title_for_layout',"Reset Password");
		$this->set('keywords_for_layout',"");
		$this->set('description_for_layout',"");
	}
	
	
	function password_reset($user_id=null, $code=null) {
		if(empty($user_id) || empty($code)) {
			$this->set('reset', false);
			$this->render();
		}
		$user = $this->User->read(null, $user_id);
		if(empty($user)) {
			$this->set('reset', false);
			$this->render();
		}
		if($user['User']['password_reset_code'] == $code){
			$this->User->id = $user_id;
			$rand_pass = $this->Password->generatePassword();
			$password = $this->Auth->password($rand_pass);
			$this->User->saveField('password', $password);
			$this->set('reset', true);
			
			//send mail
			$this->Email->to = $user['User']['email'];
			$this->Email->subject = 'New Password';
			$this->Email->replyTo = Configure::read('MyApp.admin_email');
			$this->Email->from = Configure::read('MyApp.mail_from_name').'<'.Configure::read('MyApp.admin_email').'>';
			$this->Email->sendAs = 'html';
			$this->Email->template = 'new_password';
			$this->set('name', $user['User']['username']);
			$this->set('server_name', $_SERVER['SERVER_NAME']);
			$this->set('id', $user['User']['id']);
			$this->set('code', $rand_pass);
			if ($this->Email->send()) {
				$this->set('confirm_mail',"New password sent to your email");
			} else {
				//$this->User->delete($this->User->getLastInsertID());
				$this->set('error_message',"There is a problem in sending the new password to your email. Try later");
			}
			
		} else {
			$this->set('reset', false);
		}
				
		$this->set('title_for_layout',"Reset Password");
		$this->set('keywords_for_layout',"");
		$this->set('description_for_layout',"");
	}
	
	function sendEmail($data,$id) {
		$this->Email->to = $data['User']['email'];
		$this->Email->subject = 'Email Confirmation';
		$this->Email->replyTo = Configure::read('MyApp.admin_email');
		$this->Email->from = Configure::read('MyApp.mail_from_name').'<'.Configure::read('MyApp.admin_email').'>';
		$this->Email->sendAs = 'html';
		$this->Email->template = 'confirmation';
		$this->set('name', $data['User']['username']);
		$this->set('server_name', $_SERVER['SERVER_NAME']);
		$this->set('id', $id);
		$this->set('code', $data['User']['email_validation_key']);
		if ($this->Email->send()) {
			$this->set('confirm_mail',"Confirmation mail sent to your email address");
		} else {
			//$this->User->delete($this->User->getLastInsertID());
			$this->set('error_message',"There is a problem in sending the confirmation email. Try later");
		}
	}
	
	function confirm($user_id=null, $code=null) {
		if(empty($user_id) || empty($code)) {
			$this->set('confirmed', false);
			$this->render();
		}
		$user = $this->User->read(null, $user_id);
		if(empty($user)) {
			$this->set('confirmed', false);
			$this->render();
		}
		if($user['User']['email_validation_key'] == $code){
			$this->User->id = $user_id;
			$this->User->saveField('email_status', 'active');
			$this->set('confirmed', true);
		} else {
			$this->set('confirmed', false);
		}
				
		$this->set('title_for_layout',"Email Confirmation");
		$this->set('keywords_for_layout',"");
		$this->set('description_for_layout',"");
	
	}
	
	function login() {	
		if(!empty($this->data)) {
			//$this->Auth->login();
		}
				
		$this->set('title_for_layout',"Login");
		$this->set('keywords_for_layout',"login");
		$this->set('description_for_layout',"login");
	
	}
	
	function isAuthorized() {
		return true;
	}
	
	function logout() {
		$this->Session->setFlash('Logout');
		$this->redirect($this->Auth->logout());
		
		if($this->Session->read('admin_user') != "") {
			$this->Session->delete('admin_user');
		}
	}
	
	function changepassword()
	{
		if($this->Auth->user('id') == "") {$this->redirect('/');} 
		$this->User->changeValidation('password');
		if(!empty($this->data)) {
			$this->data['User']['password2hashed'] = $this->Auth->password($this->data['User']['password2']);
			$this->User->set($this->data);
			if($this->User->validates())
			{
				$this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
				$this->User->create();
				$this->data['User']['id'] = $this->Auth->user('id');
				if ($this->User->save($this->data,array('validate' => false, 'fieldList' => array('password'),'callbacks' => true))) {
					$this->set('error',false);
				}
				else {
					$this->set('error',true);
				}				
			}
			else {
				$User = $this->User->invalidFields();
				$data = compact('User');
				$this->set('oerrors', compact('message', 'data'));
				
				$this->set('error',true);
				$this->set('v_error',true);
			}			
			$this->render('user_password_ajax','ajax');
		}
			$this->set('title_for_layout',"Change Password");
			$this->set('keywords_for_layout','');
			$this->set('description_for_layout',"");		
	}
	
	function admin_view($status = 'active') {
		$this->paginate = array('conditions' => array(),'limit' => Configure::read('MyApp.record_per_page'));
		$users = $this->paginate('User');
		$this->set(compact('users'));
		$this->set('path_name','users');
	}
	
	function admin_edit($id='') {	
		if(empty($id)) {
			$this->redirect(array('controller' => 'users','action'=>'view','admin' =>'admin'));
		}
		if(!empty($this->data)) {
			$this->User->changeValidation('');
			$this->User->set($this->data);
			if($this->User->validates())
			{
				$this->data['User']['id'] = $id;
				$this->User->create();
				if($this->User->save($this->data)) {
					$this->Session->setFlash('User Editted Successfully');
				}
				else {
					$this->Session->setFlash('There is a problem in editting user account');
				}
			}
			else {
				$this->Session->setFlash('Form validation failed');
			}			
		}
		$users = $this->data = $this->User->findById($id);
		$this->set(compact('users'));
		$this->set('path_name','users');
	}
	
	function admin_delete($id) {
		if(!$id) {
			$this->Session->setFlash('Invalid Access');
			$this->redirect(array('controller' => 'users','action'=>'view','admin' =>'admin'));
		}
		if($this->User->delete($id)) {
			$this->Session->setFlash('Deleted Successfully');
		}
		else {
			$this->Session->setFlash('User not deleted');
		}
		$this->redirect(array('controller' => 'users','action'=>'view','admin' =>'admin'));
	}
	
	function admin_logout() {
		$this->Session->delete('admin_user');
		$this->redirect('/');
	}
	
	function beforeFilter() {
        parent::beforeFilter();
    }
}
?>