<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class login extends CI_Controller {
	protected $noemail = FALSE;
	public function __construct() {
		parent::__construct();
		checkFront();
		$this->session->set_userdata('enter_uri', 'welcome');
		$this->noemail = FALSE;
	}
	
	public function index()	{
		$data = $this->templates->getData();
		$data['error'] = NULL;
		if($post = $_POST) {
			$this->load->model('general','general');
			$email = $post['useremail'];
			$password = $post['userpassword'];
			$redirect = $post['redirect'];
			$redirect = ($redirect == 'login') ? NULL : $redirect;
			
			if(!$email) {
				$data['error'] = 'Please enter your email';
			} elseif(!$password) {
				$data['error'] = 'Please enter your password';
			} else {
				if($result = $this->general->fetchSingle('tbl_usermaster',array('fldid','username','email','password','language','role'),array('email'=>$email, 'is_delete'=>0))) {
					
					$result = json_decode(json_encode($result),true);
					$password = md5($password);
					
					if($password == $result['password']) {
					
						$session['userID'] = $result['fldid'];
						$session['username'] = $result['username'];
						$session['email'] = $result['email'];
						$session['language'] = ($result['language']) ? strtolower($result['language']) : 'en';
						$session['role'] = strtolower($result['role']);
						
						$this->session->set_userdata('logged_in', $session);
						$redirect = ($redirect) ? $redirect : base_url()."project";
						
						redirect($redirect, 'refresh');
						exit();
					} else {
						$data['error'] = 'Incorrect password';
					}
				} else {
					$data['error'] = 'Account does not exist';
				}
			}
		}
		
		$vars = func_get_args();
		if($vars && !empty($vars)) {
			$data['redirect'] = base_url();		
			foreach($vars as $item) {
				$data['redirect'] .= ($item !== NULL) ? $item."/" : NULL;				
			}
		} else {
			$data['redirect'] = base_url()."project";
		}
		
		$this->templates->setLayout('front');
		$this->templates->setView('login/index')->setData($data)->render();
	}
	
	public function logout(){
		$this->session->sess_destroy();
		
		redirect(base_url(), 'refresh');
	}

	public function forgotpassword() {
		$data['error'] = NULL;
		if($post = $_POST) {			
			$this->load->model('general','general');
			$this->load->model('setup/Setupsystem','setup');
			$this->load->model('account/accountmain','accmain');
			$email = (isset($_POST['email']) && trim($_POST['email'])) ? trim($_POST['email']) : NULL;
			
			if(!$email) {
				$data['error'] = 'Please enter your email';
			} elseif(!$this->accmain->checkEmailExists($email)) {
				$data['error'] = 'Email has not been registered.';
			} else {
				if($account = $this->accmain->getAccountByEmail($email)) {					
					$param = md5(	sha1($account['ID'])	."|".	sha1($this->generateRandomString()) ."|". sha1(date('Ymd'))	);
					if($this->accmain->saveResetPassword($account['ID'], $param)) {
						$tosend['url'] = base_url()."login/resetpassword/".(rtrim(base64_encode($param),"="));				
						$tosend['from']['email'] = $this->setup->getSetupValue('EMAILSENDER');
						$tosend['from']['name'] = $this->setup->getSetupValue('EMAILSENDERNAME');
						$tosend['to']['email'] = $email;
						$tosend['to']['name'] = $account['username'];
						$tosend['view'] = "login/email/email_reset_password";
						
						$this->sendEmail($tosend);
						$data['message'] = "Request to reset has been saved. Please check your email for the link to reset your password";
					} else {
						$data['error'] = 'Fail to save request to reset password due to technical issue';
					}
				} else {
					$data['error'] = 'Account does not exist';
				}
			}
		}
		
		$this->templates->setLayout('front');
		$this->templates->setView('login/forgotpassword')->setData($data)->render();
	}
	
	public function resetpassword($code) {		
		$this->load->model('account/accountmain','accmain');
		$parsed = base64_decode($code);
		
		$data['error'] = NULL;
		$data['account'] = NULL;
		$data['code'] = $code;
		
		if(!empty($_POST)) {
			$user = trim($_POST['user']);
			$newpassword = trim($_POST['newpassword']);
			$confirmpassword = trim($_POST['confirmpassword']);
			
			if($this->accmain->checkAccountExists($user)) {
				if(trim($newpassword) == trim($confirmpassword)) {
					if($this->accmain->savePassword($user, $newpassword)) {
						$this->accmain->processReset($user, $code);
						$data['success'] = TRUE;
					} else {
						$data['error'] = "Fail to save account detail due to technical issue";
					}
				} else {
					$data['error'] = "Password confirmation not matched.";
				}
			} else {
				$data['error'] = "Account does not exist.";
			}
		} else {
			if($reset = $this->accmain->getResetInfo($parsed)) {
				if($reset['elapsed']['y'] || $reset['elapsed']['m'] || $reset['elapsed']['w'] || $reset['elapsed']['d']) {
					$data['error'] = 'Request has already expired';
				} else {
					if($reset['elapsed']['h'] > 23) {
						$data['error'] = 'Request has already expired';
					} else {
						$data['account'] = $reset['user'];
					}
				}
			} else {
				$data['error'] = 'Request to reset password does not exist in our record.';
			}
		}
		
		$this->templates->setLayout('front');
		$this->templates->setView('login/resetpassword')->setData($data)->render();
	}
	
	public function confirmreset() {
		$user = trim($_POST['user']);
		$newpassword = trim($_POST['newpassword']);
		$confirmpassword = trim($_POST['confirmpassword']);
		
		$proceed = TRUE;
		$message = NULL;
		if(trim($newpassword) != trim($confirmpassword)) {
			$proceed = FALSE;
			$message[] = "Password confirmation not matched.";
		} else {
			unset($confirmpassword);
		}
		
		if($proceed) {			
			if($accid = $this->accmain->savePassword($user, $password)) {
				$proceed = TRUE;
				$message = NULL;
			} else {
				$proceed = FALSE;
				$message[] = "Fail to save account detail due to technical issue";
			}
		}
		
		if(!$proceed && $message && !empty($message)) {
			$this->flashdata->clear();
			$this->flashdata->set(implode("<br />",$message),'message');
			$this->flashdata->set('FAIL','type');
			$url = base_url()."login/forgotpassword";
		} else {
			$this->flashdata->clear();
			$this->flashdata->set('SUCCESS','message');
			$this->flashdata->set('SUCCESS','type');
			$url = base_url()."login/index";
		}
		
		redirect($url);
	}
	
	/**
	* AJAX
	*/
	public function checkemailexistsajax() {
		$this->load->model('account/accountmain','accmain');
		$email = (isset($_POST['email']) && trim($_POST['email'])) ? trim($_POST['email']) : NULL;
		echo ($this->accmain->checkEmailExists($email)) ? 1 : 0;
	}
	
	/**
	* HELPER
	*/
	private function sendEmail($data) {
		if($this->noemail) return true;
		if(!trim($data['from']['email'])) return true;
		if(!trim($data['to']['email'])) return true;
		
		$this->load->library('email');
		
		$this->email->from($data['from']['email'], $data['from']['name']);
		$this->email->to($data['to']['email'], $data['to']['name']);
		$this->email->set_newline("\r\n");
		
		$this->email->subject('SPS E-Voting: Request to reset password.');
		$this->email->message($this->load->view($data['view'], $data, true));
		
		return($this->email->send()) ? TRUE : FALSE;
	}
	
	private function generateRandomString($length = 10) {
		// http://stackoverflow.com/a/4356295
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
				$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	
	
	
}
?>
