<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Change extends Controller /*_Website*/ {
	
	# Errors which are related to posted values and will be checked
	protected $_rules = array
	(
		'username'			=> array
		(
			'not_empty'		=> NULL,
			'min_length'		=> array(4),
			'max_length'		=> array(32),
			'regex'			=> array('/^[-\pL\pN_.]++$/uD'),
		),
		'password'			=> array
		(
			'not_empty'		=> NULL,
			'min_length'		=> array(5),
			'max_length'		=> array(42),
		),
		'password_confirm'	=> array
		(
			'matches'		=> array('password'),
		),
		'email'				=> array
		(
			'not_empty'		=> NULL,
			'min_length'		=> array(4),
			'max_length'		=> array(127),
			'validate::email'	=> NULL,
		),
		'image'				=> array
		(
			'Upload::valid' 		=> array(),
			'Upload::not_empty' 		=> array(),
			'Upload::type' 			=> array('Upload::type' => array('jpg','png','gif','jpeg')),
			'Upload::size' 			=> array('1M')
		),
	);
	
	# Additional errors caused by complex checks like already available in database
	protected $_callbacks = array
	(
		'username'			=> array('username_available'),
		'email'				=> array('email_available'),
	);
	
	public function action_change_password(){
            
		#Check if value is posted or not
		if ($_POST){
				
			#Create validation so that any inappropriate input can be caught  
			$array = Validate::factory($_POST)
				 ->filter(TRUE, 'trim')
				 ->rules('password', $this->_rules['password'])
				 ->rules('password_confirm', $this->_rules['password_confirm']);
			
			#Check if validation caused an error or not
			if($array->check()){
				
				# If no problem with the validation, then change password
				$username = Auth::instance()->get_user();
				$user = ORM::factory('user')->where('username', '=', $username)->find();
				if($user){
					$user->password = $_POST['password'];
					$user->save();
				}
				#Add Successful Message
				$data   = array(
						'successfulp'    => array('success'    	=> "Your Password Change is Successful")
						);
				$view   = View::factory("settings",$data);
				$this->request->response = $view;
			}
			else{
				# If validation has problems, then fetch those fault messages and resend with data
				$errors = $array->errors('form_error_message');
				$data   = array(
						'errors'    	=> $errors
						);
				$view   = View::factory("settings", $data);
				$this->request->response = $view;
			}
		}
	}
        
	public function action_change_username(){
		
		#Check if value is posted or not
		if ($_POST){
			
			#Create validation so that any inappropriate input can be caught  
			$array = Validate::factory($_POST)
				 ->filter(TRUE, 'trim')
				 ->rules('username', $this->_rules['username'])
				 ->callback('username', array($this, 'username_available'));
			
			#Check if validation caused an error or not
			if($array->check()){
				
				# If no problem with the validation, then change username
				$username = Auth::instance()->get_user();
				$user = ORM::factory('user')->where('username', '=', $username)->find();
				if($user){
					$user->username = $_POST['username'];
					$user->save();
				}
				#Add Successful Message
				$data   = array(
						'successfulu'    => array('success'    	=> "Your Username Change is Successful")
						);
				$view   = View::factory("settings",$data);
				$this->request->response = $view;
			}
			else{
				# If validation has problems, then fetch those fault messages and resend with data
				$errors = $array->errors('form_error_message');
				$data   = array(
						'errors'    	=> $errors,
						);
				$view   = View::factory("settings", $data);
				$this->request->response = $view;
			}
		}
	}
	
	public function action_change_email(){
		#Check if value is posted or not
		if ($_POST){
			
			#Create validation array so that any inappropriate input can be caught
			$array = Validate::factory($_POST)
				->filter(TRUE, 'trim')
				->rules('email', $this->_rules['email'])
				->callback('email', array($this, 'email_available'));
			
			#Check if validation caused an error or not
			if($array->check()){
				
				# If no problem with the validation, then change email
				$username = Auth::instance()->get_user();
				$user = ORM::factory('user')->where('username', '=', $username)->find();
				$user->email = $_POST['email'];
				$user->save();
				#Add Successful Message
				$data   = array(
						'successfule'    => array('success'    	=> "Your Email Change is Successful")
						);
				$view   = View::factory("settings",$data);
				$this->request->response = $view;
			}
			else{
				# If validation has problems, then fetch those fault messages and resend with data
				$errors = $array->errors('form_error_message');
				$data   = array(
						'errors'    	=> $errors
						);
				$view   = View::factory("settings", $data);
				$this->request->response = $view;
			}
		}
	}
	
	public function action_change_image(){
		
		$array = Validate::factory($_FILES)
			->rules('image', $this->_rules['image']);
		 
		if ($array->check())
		{
			$me    = Auth::instance()->get_user()->id;
			$filename = Upload::save($_FILES['image'],$me.'.jpg','./',0777);
			Image::factory($filename)	->resize(70, 70, Image::WIDTH)
							->save(DOCROOT."userimages/".basename($filename));
			
			$message_model 	= Model::factory('user');
			$message_model->userImageUpload(basename($filename), $me);
			
			unlink($filename);
			
			$data   = array('successfuli'    => array('success'	=> "Your Photo Change is Successful"));
			$view   = View::factory("settings", $data);
		}
		else{
			$errors = $array->errors('form_error_message');
			$data   = array('errors'    	=> $errors);
			$view   = View::factory("settings", $data);
		}
		$this->request->response = $view;
	}
	
	public function username_available(Validate $array, $field){
		
		#Check is the posted username conflicts with another one
		$users_returned = ORM::factory('user')->where('username', '=', $_POST['username'])->find();
		if($users_returned->id) {
			
			#Add error of this into $errors object
			$array->error($field, 'username_available', array($array[$field]));
		}
	}
	
	public function email_available(Validate $array, $field){
		
		#Check is the posted email conflicts with another one
		$users_returned = ORM::factory('user')->where('email', '=', $_POST['email'])->find();
		if($users_returned->id) {
			
			#Add error of this into $errors object
			$array->error($field, 'email_available', array($array[$field]));
		}
	}
	
	public function action_register(){
		
		if(Auth::instance()->get_user()){
			Request::instance()->redirect("main/act");
		}
		else{
			#If there is a post and $_POST is not empty
			if ($_POST)
			{
				#Instantiate a validation for new registration
				$array = Validate::factory($_POST)
					->rules('username', $this->_rules['username'])
					->rules('email', $this->_rules['email'])
					->rules('password', $this->_rules['password'])
					->rules('password_confirm', $this->_rules['password_confirm'])
					->filter('username', 'trim')
					->filter('email', 'trim')
					->filter('password', 'trim')
					->filter('password_confirm', 'trim')
					->callback('email', array($this, 'email_available'))
					->callback('username', array($this, 'username_available'));
					
				//throw new Exception($_POST["university"]);
				#If the post data validates using the rules setup in the user model
				if ($array->check())
				{
					$array["university_id"]=$_POST["university"];
					$array["department_id"]=$_POST["department"];
					$user_model 	= Model::factory('user');
					$user_model->registerUser($array);	
	 
					#sign the user in
					Auth::instance()->login($array['username'], $array['password']);
	 
					#redirect to the user account
					gen::re_back();
				}
				else
				{
					$department_model 	= Model::factory('department');
					$university_model 	= Model::factory('university');
					
					$universities_arr 	= $university_model->getUniversities();
					$departments_arr  	= $department_model->getDepartments();
					
					$errors = $array->errors('form_error_message');
					$data = array(
							"universities_arr" 	=> $universities_arr,
							"departments_arr"	=> $departments_arr,
							"errors"    		=> $errors);
					
					$outerdata = array("data" => $data);
					$view   = View::factory("signin", $outerdata);
					$this->request->response = $view;
				}
			}
		}
		
	}

}
