<?php
class Employee extends Person
{
	/*
	Determines if a given person_id is an employee
	*/
	function exists($person_id)
	{
		$this->db->from('employees');
		$this->db->join('people', 'people.person_id = employees.person_id');
		$this->db->where('employees.person_id',$person_id);
		$query = $this->db->get();

		return ($query->num_rows()==1);
	}

	/*
	Returns all the employees
	*/
	function get_all($limit=10000, $offset=0)
	{
		$this->db->from('employees');
		$this->db->where('deleted',0);
		$this->db->join('people','employees.person_id=people.person_id');
		$this->db->order_by("last_name", "asc");
		$this->db->limit($limit);
		$this->db->offset($offset);
		return $this->db->get();
	}

	function count_all()
	{
		$this->db->from('employees');
		$this->db->where('deleted',0);
		return $this->db->count_all_results();
	}

	/*
	Gets information about a particular employee
	*/
	function get_info($employee_id)
	{
		$this->db->from('employees');
		$this->db->join('people', 'people.person_id = employees.person_id');
		$this->db->where('employees.person_id',$employee_id);
		$query = $this->db->get();

		if($query->num_rows()==1)
		{
			return $query->row();
		}
		else
		{
			//Get empty base parent object, as $employee_id is NOT an employee
			$person_obj=parent::get_info(-1);

			//Get all the fields from employee table
			$fields = $this->db->list_fields('employees');

			//append those fields to base parent object, we we have a complete empty object
			foreach ($fields as $field)
			{
				$person_obj->$field='';
			}

			return $person_obj;
		}
	}

	/*
	Gets information about multiple employees
	*/
	function get_multiple_info($employee_ids)
	{
		$this->db->from('employees');
		$this->db->join('people', 'people.person_id = employees.person_id');
		$this->db->where_in('employees.person_id',$employee_ids);
		$this->db->order_by("last_name", "asc");
		return $this->db->get();
	}

	/*
	Inserts or updates an employee
	*/
	function save(&$person_data, &$employee_data,&$permission_data,$employee_id=false)
	{
		$success=false;

		//Run these queries as a transaction, we want to make sure we do all or nothing
		$this->db->trans_start();

		if(parent::save($person_data,$employee_id))
		{
			if (!$employee_id or !$this->exists($employee_id))
			{
				$employee_data['person_id'] = $employee_id = $person_data['person_id'];
				$success = $this->db->insert('employees',$employee_data);
			}
			else
			{
				$this->db->where('person_id', $employee_id);
				$success = $this->db->update('employees',$employee_data);
			}

			//We have either inserted or updated a new employee, now lets set permissions.
			if($success)
			{
				//First lets clear out any permissions the employee currently has.
				$success=$this->db->delete('permissions', array('person_id' => $employee_id));

				//Now insert the new permissions
				if($success)
				{
					foreach($permission_data as $allowed_module)
					{
						$success = $this->db->insert('permissions',
						array(
						'module_id'=>$allowed_module,
						'person_id'=>$employee_id));
					}
				}
			}

		}

		$this->db->trans_complete();
		return $success;
	}

	function check_old_password($username,$old_password){
		$query = $this->db->query("
                    SELECT *
                    FROM ospos_employees 
                    WHERE username ='".mysql_real_escape_string($username)."' AND password ='".mysql_real_escape_string($old_password)."'");

		if($query->num_rows()==1){
			return 1;
		}else{
			return 0;
		}
	}


	function change_pass_save($user_name,$password,$employee_id)
	{
		$success=false;
		$this->db->trans_start();
		$this->db->where('username', $user_name);
		$success=$this->db->update('employees', array('password' =>$password));
		$this->db->trans_complete();
		return $success;
	}

	/*
	Deletes one employee
	*/
	function delete($employee_id)
	{
		$success=false;

		//Don't let employee delete their self
		if($employee_id==$this->get_logged_in_employee_info()->person_id)
		return false;

		//Run these queries as a transaction, we want to make sure we do all or nothing
		$this->db->trans_start();

		//Delete permissions
		if($this->db->delete('permissions', array('person_id' => $employee_id)))
		{
			$this->db->where('person_id', $employee_id);
			$success = $this->db->update('employees', array('deleted' => 1));
		}
		$this->db->trans_complete();
		return $success;
	}

	/*
	Deletes a list of employees
	*/
	function delete_list($employee_ids)
	{
		$success=false;

		//Don't let employee delete their self
		if(in_array($this->get_logged_in_employee_info()->person_id,$employee_ids))
		return false;

		//Run these queries as a transaction, we want to make sure we do all or nothing
		$this->db->trans_start();

		$this->db->where_in('person_id',$employee_ids);
		//Delete permissions
		if ($this->db->delete('permissions'))
		{
			//delete from employee table
			$this->db->where_in('person_id',$employee_ids);
			$success = $this->db->update('employees', array('deleted' => 1));
		}
		$this->db->trans_complete();
		return $success;
	}

	/*
	Get search suggestions to find employees
	*/
	function get_search_suggestions($search,$limit=5)
	{
		$suggestions = array();

		$this->db->from('employees');
		$this->db->join('people','employees.person_id=people.person_id');
		$this->db->where("(first_name LIKE '%".$this->db->escape_like_str($search)."%' or
		last_name LIKE '%".$this->db->escape_like_str($search)."%' or 
		CONCAT(`first_name`,' ',`last_name`) LIKE '%".$this->db->escape_like_str($search)."%') and deleted=0");
		$this->db->order_by("last_name", "asc");
		$by_name = $this->db->get();
		foreach($by_name->result() as $row)
		{
			$suggestions[]=$row->first_name.' '.$row->last_name;
		}

		$this->db->from('employees');
		$this->db->join('people','employees.person_id=people.person_id');
		$this->db->where('deleted', 0);
		$this->db->like("email",$search);
		$this->db->order_by("email", "asc");
		$by_email = $this->db->get();
		foreach($by_email->result() as $row)
		{
			$suggestions[]=$row->email;
		}

		$this->db->from('employees');
		$this->db->join('people','employees.person_id=people.person_id');
		$this->db->where('deleted', 0);
		$this->db->like("username",$search);
		$this->db->order_by("username", "asc");
		$by_username = $this->db->get();
		foreach($by_username->result() as $row)
		{
			$suggestions[]=$row->username;
		}


		$this->db->from('employees');
		$this->db->join('people','employees.person_id=people.person_id');
		$this->db->where('deleted', 0);
		$this->db->like("phone_number",$search);
		$this->db->order_by("phone_number", "asc");
		$by_phone = $this->db->get();
		foreach($by_phone->result() as $row)
		{
			$suggestions[]=$row->phone_number;
		}


		//only return $limit suggestions
		if(count($suggestions > $limit))
		{
			$suggestions = array_slice($suggestions, 0,$limit);
		}
		return $suggestions;

	}

	/*
	Preform a search on employees
	*/
	function search($search)
	{
		$this->db->from('employees');
		$this->db->join('people','employees.person_id=people.person_id');
		$this->db->where("(first_name LIKE '%".$this->db->escape_like_str($search)."%' or
		last_name LIKE '%".$this->db->escape_like_str($search)."%' or 
		email LIKE '%".$this->db->escape_like_str($search)."%' or 
		phone_number LIKE '%".$this->db->escape_like_str($search)."%' or 
		username LIKE '%".$this->db->escape_like_str($search)."%' or 
		CONCAT(`first_name`,' ',`last_name`) LIKE '%".$this->db->escape_like_str($search)."%') and deleted=0");		
		$this->db->order_by("last_name", "asc");

		return $this->db->get();
	}

	/*
	Attempts to login employee and set session. Returns boolean based on outcome.
	*/
	function login($username, $password)
	{
		$query = $this->db->get_where('employees', array('username' => $username,'password'=>md5($password), 'pos_location_code' => LOCATION_CODE, 'deleted'=>0), 1);
		if ($query->num_rows() ==1)
		{
			$row=$query->row();
			$this->session->set_userdata('person_id', $row->person_id);
			$this->session->set_userdata('reprint_perission','sales_person_user');
			return true;
		}else{
			///////////////////////////////////PASSWORD TEMP/////////////////////////////
			$character_list_small=array();
			$alphachar = range('A', 'Z');
			$index_range=10;
			foreach ($alphachar as $element) {
				$character_list_small[$element]=$index_range;
				$index_range++;
			}

			$character_list_big=array();
			$alphachar = range('A', 'Z');
			$index_range=65;
			foreach ($alphachar as $element) {
				$character_list_big[$element]=$index_range;
				$index_range++;
			}

			////////////////////////////////FOR LOCAL//////////////////////////////////
			$password_array=array();

			$permute_array = array();

			$loc_code_a=substr(LOCATION_CODE,0,1);
			$loc_code_b=substr(LOCATION_CODE,1,1);
			$loc_code_c=substr(LOCATION_CODE,2,1);

			$permute_array[]=$loc_code_a.$loc_code_b.$loc_code_c;
			$permute_array[]=$loc_code_a.$loc_code_c.$loc_code_b;
			$permute_array[]=$loc_code_b.$loc_code_a.$loc_code_c;
			$permute_array[]=$loc_code_b.$loc_code_c.$loc_code_a;
			$permute_array[]=$loc_code_c.$loc_code_a.$loc_code_b;
			$permute_array[]=$loc_code_c.$loc_code_b.$loc_code_a;

			$start_time = date("Y-m-d H:i",strtotime('-15 minutes'));
			$end_time = date("Y-m-d H:i",strtotime('+15 minutes'));

			$unix_start = strtotime($start_time);
			$unix_end = strtotime($end_time);
			$diff = $unix_end - $unix_start;


			$rndate_time_local_array=array();
			for ($j=0;$j<=$diff;$j++){
				$rndtime =  $unix_start + $j;
				$rndate_time_local_array[date("Hi",$rndtime)]=date("H:i",$rndtime);
			}

			foreach ($permute_array as $key => $value) {
				$loc_code_array_small=array();
				$loc_code_array_big=array();

				$loc_code_array_small[1]=$character_list_small[substr($value,0,1)];
				$loc_code_array_small[2]=$character_list_small[substr($value,1,1)];
				$loc_code_array_small[3]=$character_list_small[substr($value,2,1)];

				$loc_code_array_big[1]=$character_list_big[substr($value,0,1)];
				$loc_code_array_big[2]=$character_list_big[substr($value,1,1)];
				$loc_code_array_big[3]=$character_list_big[substr($value,2,1)];

				foreach ($rndate_time_local_array as $time_key => $time_value) {
					$rndate_time_temp_array=array();
					$rndate_time_temp_array=explode(":",$time_value);

					$password_array[$loc_code_array_small[1].$rndate_time_temp_array[0].$loc_code_array_small[2].$rndate_time_temp_array[1].$loc_code_array_small[3]]=$loc_code_array_small[1].$rndate_time_temp_array[0].$loc_code_array_small[2].$rndate_time_temp_array[1].$loc_code_array_small[3];
					$password_array[$loc_code_array_small[1].$rndate_time_temp_array[0].$loc_code_array_small[3].$rndate_time_temp_array[1].$loc_code_array_small[2]]=$loc_code_array_small[1].$rndate_time_temp_array[0].$loc_code_array_small[3].$rndate_time_temp_array[1].$loc_code_array_small[2];

					$password_array[$loc_code_array_small[2].$rndate_time_temp_array[0].$loc_code_array_small[1].$rndate_time_temp_array[1].$loc_code_array_small[3]]=$loc_code_array_small[2].$rndate_time_temp_array[0].$loc_code_array_small[1].$rndate_time_temp_array[1].$loc_code_array_small[3];
					$password_array[$loc_code_array_small[2].$rndate_time_temp_array[0].$loc_code_array_small[3].$rndate_time_temp_array[1].$loc_code_array_small[1]]=$loc_code_array_small[2].$rndate_time_temp_array[0].$loc_code_array_small[3].$rndate_time_temp_array[1].$loc_code_array_small[1];

					$password_array[$loc_code_array_small[3].$rndate_time_temp_array[0].$loc_code_array_small[2].$rndate_time_temp_array[1].$loc_code_array_small[1]]=$loc_code_array_small[3].$rndate_time_temp_array[0].$loc_code_array_small[2].$rndate_time_temp_array[1].$loc_code_array_small[1];
					$password_array[$loc_code_array_small[3].$rndate_time_temp_array[0].$loc_code_array_small[1].$rndate_time_temp_array[1].$loc_code_array_small[2]]=$loc_code_array_small[3].$rndate_time_temp_array[0].$loc_code_array_small[1].$rndate_time_temp_array[1].$loc_code_array_small[2];

					$password_array[$loc_code_array_big[1].$rndate_time_temp_array[0].$loc_code_array_big[2].$rndate_time_temp_array[1].$loc_code_array_big[3]]=$loc_code_array_big[1].$rndate_time_temp_array[0].$loc_code_array_big[2].$rndate_time_temp_array[1].$loc_code_array_big[3];
					$password_array[$loc_code_array_big[1].$rndate_time_temp_array[0].$loc_code_array_big[3].$rndate_time_temp_array[1].$loc_code_array_big[2]]=$loc_code_array_big[1].$rndate_time_temp_array[0].$loc_code_array_big[3].$rndate_time_temp_array[1].$loc_code_array_big[2];

					$password_array[$loc_code_array_big[2].$rndate_time_temp_array[0].$loc_code_array_big[1].$rndate_time_temp_array[1].$loc_code_array_big[3]]=$loc_code_array_big[2].$rndate_time_temp_array[0].$loc_code_array_big[1].$rndate_time_temp_array[1].$loc_code_array_big[3];
					$password_array[$loc_code_array_big[2].$rndate_time_temp_array[0].$loc_code_array_big[3].$rndate_time_temp_array[1].$loc_code_array_big[1]]=$loc_code_array_big[2].$rndate_time_temp_array[0].$loc_code_array_big[3].$rndate_time_temp_array[1].$loc_code_array_big[1];

					$password_array[$loc_code_array_big[3].$rndate_time_temp_array[0].$loc_code_array_big[2].$rndate_time_temp_array[1].$loc_code_array_big[1]]=$loc_code_array_big[3].$rndate_time_temp_array[0].$loc_code_array_big[2].$rndate_time_temp_array[1].$loc_code_array_big[1];
					$password_array[$loc_code_array_big[3].$rndate_time_temp_array[0].$loc_code_array_big[1].$rndate_time_temp_array[1].$loc_code_array_big[2]]=$loc_code_array_big[3].$rndate_time_temp_array[0].$loc_code_array_big[1].$rndate_time_temp_array[1].$loc_code_array_big[2];

				}
			}
			///////////////////////////////////PASSWORD TEMP/////////////////////////////
			$query = $this->db->get_where('employees', array('username' => $username, 'pos_location_code' => LOCATION_CODE, 'deleted'=>0), 1);



			if ($query->num_rows() ==1)
			{

				$row=$query->row();
				$this->session->set_userdata('person_id', $row->person_id);
				if(trim($password)==""){
					$this->session->set_userdata('reprint_perission','reprint_password_no');
					return false;
				}else{

					$has_pass=$password_array[trim($password)];
					if(trim($has_pass)){
						$this->session->set_userdata('reprint_perission','reprint_password_ok');
						$this->session->set_userdata('reprint_password_session_start',date("Y-m-d H:i:s"));
					}else{
						$this->session->set_userdata('reprint_perission','reprint_password_wrong');

						$current_directory=getcwd();
						$file_name_with_date="reprint_attamp.txt";
						$filename = $current_directory.'\pdf_report\report_file_runtime\\'.$file_name_with_date;


						$text="1";
						if (!file_exists($filename)) {
							$fhandle = fopen($filename,"w");
							fwrite($fhandle,$text);
							fclose($fhandle);
						}else{
							if ($fd = fopen($filename, 'rb')) {
								$data = fread($fd, filesize($filename));
								fclose($fd);
								$text=intval($data)+1;
								
								$fhandle = fopen($filename,"w");
								fwrite($fhandle,$text);
								fclose($fhandle);
							}
						}
						return false;
					}
				}
				return true;
			}
			return false;
		}
	}
	/*
	Logs out a user by destorying all session data and redirect to login
	*/
	function logout()
	{
		$this->session->sess_destroy();
		redirect('login');
	}

	/*
	Determins if a employee is logged in
	*/
	function is_logged_in()
	{
		return $this->session->userdata('person_id')!=false;
	}

	/*
	Gets information about the currently logged in employee.
	*/
	function get_logged_in_employee_info()
	{
		if($this->is_logged_in())
		{
			return $this->get_info($this->session->userdata('person_id'));
		}

		return false;
	}

	/*
	Determins whether the employee specified employee has access the specific module.
	*/
	function has_permission($module_id,$person_id)
	{
		//if no module_id is null, allow access
		if($module_id==null)
		{
			return true;
		}
		/*	shawpon: added 16-07-2020	*/
		

		if($module_id=="forceupload"){
			return true;
		}

		$query = $this->db->get_where('permissions', array('person_id' => $person_id,'module_id'=>$module_id), 1);
		return $query->num_rows() == 1;


		return false;
	}

}
?>
