<?php
class Users extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('usersmodel');
		$this->load->model('tokenmodel');
		$this->load->model('auditmodel');
		$this->load->model('captchamodel');
		$this->load->model('msgmodel');
		$this->load->library('form_validation');
	}

	public function index()
	{
		show_404();
	}

	function checkUser()
	{
		$userCode = $this->input->get('email');

		$users = $this->usersmodel->get(array('UserCode' => $userCode, 'recordstate' => 0));

		if ($users->num_rows() > 0)
			echo json_encode(array('result' => 'FAIL', 'message' => 'Username Already exists in the system'));
		else
			echo json_encode(array('result' => 'OK', 'message' => ''));
	}

	function checkPhone()
	{
		$userCode = $this->input->get('phone');
		$users = $this->usersmodel->get(array('phone' => $userCode, 'recordstate' => 0));
		if ($users->num_rows() > 0)
			echo json_encode(array('result' => 'FAIL', 'message' => 'Username Already exists in the system'));
		else
			echo json_encode(array('result' => 'OK', 'message' => ''));
	}

	function disableThis()
	{
		$tid = $this->input->get('usercode');
		$action = $this->input->get('action');

		$tid = base64_decode(urldecode($tid));
		
		$result = $this->usersmodel->update(array('recordstate' => 0, 'UserEnabled' => $action), array('tid' => $tid));
		$this->auditmodel->insert("Changed user access status to ". $action ." for user id ". $tid, $result, "", json_encode($this->input->get()));
			
		if ($this->db->affected_rows() > 0)
			echo "Selected user ". ($action==0?"disabled from" : "enabled on") ." system access.";
		else
			echo "Sorry failed to ". ($action==0?"disable" : "enable" ) ." user.Please try again.";
	}

	private function generatePass()
	{
		$word = "";
		$pick = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$length = 6;
		while (strlen($word) < $length) {
			$word .= substr($pick, mt_rand() % (strlen($pick)), 1);
		}
		return $word;
	}
 

	public function addUser()
	{
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('phoneno', 'Phone Number', 'required');
		$this->form_validation->set_rules('firstname', 'First name', 'required');
		$this->form_validation->set_rules('secondname', 'Second name', 'required');
		$this->form_validation->set_rules('usertype', 'User role', 'required');

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('tempdata', "Sorry there is an error on your data. Please fix the issues addressed and try again.<br>" . validation_errors());
			redirect(APP_BASE . "users");
		} else {
			//validation OK
			$username = $this->input->post('email');
			$phoneno = $this->input->post('phoneno');
			$email = $this->input->post('email');
			$firstname = $this->input->post('firstname');
			$secondname = $this->input->post('secondname');
			$usertype = $this->input->post('usertype');

			$username = trim($username);
			$usersexist = $this->usersmodel->get(array('UserCode' => $username, 'recordstate' => 0));
			if ($usersexist->num_rows() > 0) {
				$flashdata = 'Sorry the username already exists in the system';
			} else {
				$password = $this->generatePass();
				$merchantId = $this->session->userdata('merchantid');
				$result = $this->usersmodel->insert($password, $merchantId);
				if ($result > 0) {
					$msg = '<p>Your account has been created. Use the following credentials to access your account.</p>
									<table border="0" cellpadding="0" cellspacing="0">
									<tbody>
										<tr><td>Username: ' . $username . '</td></tr>
										<tr><td>Password: ' . $password . '</td></tr>
									</tbody>
									</table>
									<br>
									<table border="0" cellpadding="0" cellspacing="0"  class="btn btn-primary">
									<tbody>
									<tr><td> <a href="' . base_url() . '" target="_blank">Log in now</a> </td> </tr>
									</tbody>
									</table>';

					$sms = $firstname . ", your account has been created on " . APP_NAME . ". Visit " .  base_url() . " and log in with Username: " . $username . " Password " . $password;

					if (!empty($email))
						$this->msgmodel->insert_comm($email, "email", $msg, "Account Created", $firstname);

					if (!empty($phoneno))
						$this->msgmodel->insert_comm($phoneno, "sms", $sms, "Account Created", $firstname);

					$flashdata = 'User details added in the system and an email sent out with the credentials.';
				} else
					$flashdata = 'Sorry please supply the information required and follow the set registration rules.';
				$this->auditmodel->insert("Added local user details: Email: " . $email . " name : " . $firstname . $secondname, $result, "", json_encode($this->input->post()));
			}
			$this->session->set_flashdata('tempdata', $flashdata);
			redirect(APP_BASE . "users");
		}
	}
 
	function login()
	{

		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		$this->form_validation->set_rules('userCaptcha', 'User Captcha', 'required');

		$username = $this->input->post('username');
		$password = $this->input->post('password');
		$captcha = $this->input->post("userCaptcha");

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('tempdata', "Sorry there is an error on your data. Please fix the issues addressed and try again.<br>" . validation_errors());
			redirect(base_url());
		} else {
			//validation OK
			$systemCaptcha = $this->captchamodel->get(array('word' => $captcha, 'origin' => 'login', 'deleted' => 0));
			if ($systemCaptcha->num_rows() > 0 && $captcha == $systemCaptcha->row()->word) {
				//captcha ok
				$captcharow = $systemCaptcha->row();
				$this->captchamodel->update($captcharow->captcha_id);
				//check logins
				$data = array('UserCode' => $username, 'UserEnabled' => 1, 'recordstate' => 0);
				$result = $this->usersmodel->get($data);
				if ($result->num_rows() > 0) {
					$row = $result->row();
					$dbPassword = $row->Password;
					if (password_verify($password, $dbPassword)) {
						$token = do_hash(uniqid($row->UserCode . '$$@#FRW$%YHRTEW748@fh!()_+ETERT^%$^&*0dhaa!`', true));
						$this->session->set_userdata('username', $row->UserCode);
						$this->session->set_userdata('role', $row->Usertype);
						$this->session->set_userdata('merchantid', $row->BusinessID);
						$this->session->set_userdata('names', $row->Firstname);
						$this->session->set_userdata('token', $token);
						$this->tokenmodel->insert($token, $row->UserCode);
						$this->auditmodel->insert("Logged into the sytem ", 1, $row->UserCode);

						redirect(APP_BASE . "dashboard");
					} else {
						$this->auditmodel->insert("Tried to Log in the sytem, invalid username / password combination", 0, $username);
						$this->session->set_flashdata('tempdata', 'Sorry your please supply the correct username - password pair combination');
						redirect(base_url());
					}
				} else {
					$this->auditmodel->insert("Tried to Log in the sytem,  account is does not exist", 0, $username);
					$this->session->set_flashdata('tempdata', 'Sorry your account is does not exist. Contact IT for further details.');
					redirect(base_url());
				}
			} else {
				//invalid captcha
				$this->session->set_flashdata('tempdata', 'Sorry could not log you in, please enter the correct captcha code and try again.');
				$this->auditmodel->insert("Tried to log in, Invalid captcha was entered.", -1, $username);
				redirect(base_url());
			}
		}
	} 

	public function reset()
	{
		$this->form_validation->set_rules('password', 'Current Password', 'required');
		$this->form_validation->set_rules('newpassword', 'New Password', 'required');
		$this->form_validation->set_rules('cpassword', 'Confirmation password', 'required');

		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('tempdata', "Sorry there is an error on your data. Please fix the issues addressed and try again.<br>" . validation_errors());
			redirect(APP_BASE . "changepassword");
		} else {
			$currentPassword = $this->usersmodel->get(array('UserCode' => $this->session->userdata('username'), 'recordstate' => 0))->row();

			$password = $this->input->post('password');
			$new = $this->input->post('newpassword');
			$retype = $this->input->post('cpassword');

			if (password_verify($password, $currentPassword->Password)  && $new == $retype) {
				$mpass = password_hash($new, PASSWORD_BCRYPT);
				$this->usersmodel->update(array('Password' => $mpass), array('tid' => $currentPassword->tid));
				$this->session->set_flashdata('tempdata', "Password successfully changed. During the next login use your new password.");
			} else
				$this->session->set_flashdata('tempdata', "Sorry ensure your current password is correct and that the new password matches the retype password.");
			redirect(APP_BASE . 'changepassword');
		}
	}

	public function confirm_password($token)
	{

		$username = base64_decode(urldecode($token));
		$username = trim($username);

		$musers = $this->usersmodel->get(array('UserCode' => $username, 'recordstate' => 0));

		if ($musers->num_rows() > 0) {
			$user = $this->usersmodel->get(array('UserCode' => $username))->row();
			$datetime1 = strtotime(date('Y-m-d H:i:s'));
			$datetime2 = strtotime($user->resettime);

			$interval =  round(abs($datetime1 - $datetime2) / 60, 0);

			if ($interval > 15 || $user->isreset == 0)
				$flashdata = 'Sorry the confirmation link has expired! Reset password again.';
			else {
				$update = array(
					'Password' => $user->resetpass,
					'isreset' => '0',
					'resettime' => date('Y-m-d H:i:s')
				);
				$status  = $this->usersmodel->update($update, array('UserCode' => $username));
				if ($status > 0)
					$flashdata = 'Password reset done. Log in with your new password specified during reset request.';
				else
					$flashdata = 'Password reset failed. Please try again.';
				$this->auditmodel->insert("Confirmed password reset for : usercode " . $username, $status, $username);
			}
		} else {
			$flashdata = 'Sorry no account exists with the provided email address.';
		}
		$this->session->set_flashdata('tempdata', $flashdata);
		redirect(base_url());
	}

	public function reset_password()
	{
		$username = $this->input->post('email');
		$username = trim($username);

		$users = $this->usersmodel->get(array('UserCode' => $username, 'recordstate' => 0));

		if ($users->num_rows() > 0) {
			$mpassword = $this->input->post('password');
			$cpassword = password_hash($mpassword, PASSWORD_BCRYPT);
			$update = array(
				'resetpass' => $cpassword,
				'isreset' => '1',
				'resettime' => date('Y-m-d H:i:s')
			);

			$status  = $this->usersmodel->update($update, array('UserCode' => $username));
			$this->auditmodel->insert("Initiated password reset for : usercode " . $username, $status, $username);
			$url = base_url() . 'users/confirm_password/' . urlencode(base64_encode($username));
			if ($status > 0) {
				$msg = '<p>Please confirm your password change request.</p>
				<p>If this is not you please contact us and report this issue.</p>
				<p>If you have initiated this request, confirm your request by clicking the button below:</p>
				<br>
				<table border="0" cellpadding="0" cellspacing="0"  class="btn btn-primary">
				<tbody>
				<tr><td> <a href="' . $url . '" target="_blank">Confirm Password Reset</a> </td> </tr>
				</tbody>
				</table>';
				$this->msgmodel->insert_comm($username, "email", $msg, "No-reply:: Password Reset", $username, $username);
				$flashdata = 'Password reset request submitted. An email has been sent to you with the confirmation link. Click the link to confirm change.';
			} else
				$flashdata = 'Sorry the reset account, ensure the details are correct and try again.';
		} else {
			$flashdata = 'Sorry no account exists with the provided email address.';
		}
		$this->session->set_flashdata('tempdata', $flashdata);
		redirect($status > 0 ? base_url() : '/home/reset_password');
	}

	function timeout()
	{
		$this->session->set_flashdata('tempdata', "Sorry your previous session has expired. Please log in to continue.");
		redirect(base_url());
	}

	function terminateaccess()
	{
		$this->session->sess_destroy();
		redirect(base_url());
	}
}
