<?php
class Expence extends Person
{
	
	
	
	public function get_max_id()
	{
        $this->db->select('max(expence_id) as max_expence');
		$this->db->from('phppos_expences');
		foreach($this->db->get()->result_array() as $query){
			return $query['max_expence']+1;
		}
	}
	/*
	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);
	}
	
		
	function employee_username_exists($username)
	{
		$this->db->from('employees');	
		$this->db->join('people', 'people.person_id = employees.person_id');
		$this->db->where('employees.username',$username);
		$query = $this->db->get();
		
		
		if($query->num_rows()==1)
		{
			return $query->row()->username;
		}
	}	
	
	/*
	Returns all the employees
	*/
	function get_all($limit=10000, $offset=0,$col='expence_time',$order='desc')
	{	
                $login_person_id = $this->session->userdata('person_id');
		$expences=$this->db->dbprefix('expences');
		$people=$this->db->dbprefix('people');
                if($login_person_id == 1){
                    $data=$this->db->query("SELECT * 
						FROM ".$people."
						STRAIGHT_JOIN ".$expences." ON 										                       
						".$people.".person_id = ".$expences.".employee_id
						WHERE deleted =0 ORDER BY ".$col." ". $order." 
						LIMIT  ".$offset.",".$limit);		
                }else{
                     $data=$this->db->query("SELECT * 
						FROM ".$people."
						STRAIGHT_JOIN ".$expences." ON 										                       
						".$people.".person_id = ".$expences.".employee_id
						WHERE deleted =0 AND ".$expences.".employee_id = ".$login_person_id." ORDER BY ".$col." ". $order." 
						LIMIT  ".$offset.",".$limit);
                }				
		return $data;
	}
	
		//We create a temp table that allows us to do easy report/receiving queries
	public function create_expences_items_temp_table($params)
	{
            
		if (!$this->session->userdata('expences_report_running'))
		{
			$this->session->set_userdata('expences_report_running', TRUE);
			set_time_limit(0);
		
			$location_id = $this->Employee->get_logged_in_employee_current_location_id();

			$where = '';
			if (isset($params['start_date']) && isset($params['end_date']))
			{
                            if(isset($params['expence_type']) && $params['expence_type'] == 'all'){
				$where = '  expence_time BETWEEN "'.date('Y-m-d H:i:s',strtotime($params['start_date'])).'" and "'.date('Y-m-d H:i:s',strtotime($params['end_date'].' +24 hour')).'"'.' and '.$this->db->dbprefix('expences').'.location_id='.$this->db->escape($location_id);
                            }else{
                                $where = ' expence_type="'.$params['expence_type'].'" and expence_time BETWEEN "'.date('Y-m-d H:i:s',strtotime($params['start_date'])).'" and "'.date('Y-m-d H:i:s',strtotime($params['end_date'].' +24 hour')).'"'.' and '.$this->db->dbprefix('expences').'.location_id='.$this->db->escape($location_id);                                
                            }
                                
                            }
			else
			{
				//If we don't pass in a date range, we don't need data from the temp table
				$where = 'WHERE location_id='.$this->db->escape($location_id);
			}
			if (isset($params['paid_to']) && $params['paid_to']!=''){
				$where = $where." and paid_to='".$params['paid_to']."'";
			}
			//$this->db->query("delete from  ".$this->db->dbprefix('mros_items_temp'));
			
		$login_person_id = $this->session->userdata('person_id');
		$expences=$this->db->dbprefix('expences');
		$people=$this->db->dbprefix('people');
                if($login_person_id == 1){
                    $data=$this->db->query("CREATE TEMPORARY  TABLE ".$this->db->dbprefix('expences_items_temp')." (SELECT $expences.*, $people.first_name,$people.last_name
						FROM ".$people."
						STRAIGHT_JOIN ".$expences." ON 										                       
						".$people.".person_id = ".$expences.".employee_id
						WHERE $where  ORDER BY expence_time desc  
					 )");		
                }else{
                     $data=$this->db->query("CREATE TEMPORARY  TABLE ".$this->db->dbprefix('expences_items_temp')."SELECT $expences.*, $people.first_name,$people.last_name
						FROM ".$people."
						STRAIGHT_JOIN ".$expences." ON 										                       
						".$people.".person_id = ".$expences.".employee_id
						WHERE $where  AND ".$expences.".location_id = ".$location_id." ORDER BY  expence_time desc  
						 )");
                }	
			
			
			$this->session->set_userdata('expences_report_running', FALSE);
			
			return TRUE;
		}
		return FALSE;
	}
	
	function count_all()
	{
		$this->db->from('expences');
		$this->db->where('deleted',0);
		return $this->db->count_all_results();
	}
	
	/*
	Gets information about a particular employee
	*/
	function get_info($expence_id)
	{
		$this->db->from('expences');	
		$this->db->where('expence_id',$expence_id);
		$query = $this->db->get();
		//echo $this->db->last_query();
		if($query->num_rows()==1)
		{
			return $query->row_array();
		}
	}
	
	/*
	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();		
	}
	
	
	function save(&$expence_data,$expence_id=false)
	{
		if (!$expence_id or !$this->exists($expence_id))
		{
			if($this->db->insert('expences',$expence_data))
			{
				$expence_data['expence_id']=$this->db->insert_id();
				return $expence_data['expence_id'];
			}
			return false;
		}

		$this->db->where('expence_id', $expence_id);
		$this->db->update('expence',$expence_data);
                return $expence_id;
	}


	
	
	/*
	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();
		
		$employee_info = $this->Employee->get_info($employee_id);
	
		if ($employee_info->image_id !== NULL)
		{
			$this->Person->update_image(NULL,$employee_id);
			$this->Appfile->delete($employee_info->image_id);			
		}			
		
		//Delete permissions
		if($this->db->delete('permissions', array('person_id' => $employee_id)) && $this->db->delete('permissions_actions', 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();
		
		foreach($employee_ids as $employee_id)
		{
			$employee_info = $this->Employee->get_info($employee_id);
		
			if ($employee_info->image_id !== NULL)
			{
				$this->Person->update_image(NULL,$employee_id);
				$this->Appfile->delete($employee_info->image_id);			
			}			
		}
		
		$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;
 	}
	
		
	function check_duplicate($term)
	{
		$this->db->from('employees');
		$this->db->join('people','employees.person_id=people.person_id');	
		$this->db->where('deleted',0);		
		$query = $this->db->where("CONCAT(first_name,' ',last_name) = ".$this->db->escape($term));
		$query=$this->db->get();
		
		if($query->num_rows()>0)
		{
			return true;
		}
		
		
	}
	/*
	Get search suggestions to find employees
	*/
	function get_search_suggestions($search,$limit=5)
	{
		$suggestions = array();
		
		$this->db->from('expences');
		$this->db->join('people','expences.employee_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)."%' or 
		CONCAT(`last_name`,', ',`first_name`) LIKE '%".$this->db->escape_like_str($search)."%') or
		title LIKE '%".$this->db->escape_like_str($search)."%' or 
		expence_type LIKE '%".$this->db->escape_like_str($search)."%' or 
		amount LIKE '%".$this->db->escape_like_str($search)."%' or 
		expence_time LIKE '%".$this->db->escape_like_str($search)."%'  
		and deleted=0");
		
		$this->db->limit($limit);	
		$by_name = $this->db->get();
		$temp_suggestions = array();
		foreach($by_name->result() as $row)
		{
			$temp_suggestions[] = $row->last_name.', '.$row->first_name;
		}
		
		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);		
		}
		
		$this->db->from('expences');
		$this->db->join('people','expences.employee_id=people.person_id');
		$this->db->where('deleted', 0);
		$this->db->like("title",$search);
		$this->db->limit($limit);
		$by_email = $this->db->get();
		$temp_suggestions = array();
		foreach($by_email->result() as $row)
		{
			$temp_suggestions[] = $row->title;
		}
		
		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);		
		}
		
		$this->db->from('expences');
		$this->db->join('people','expences.employee_id=people.person_id');	
		$this->db->where('deleted', 0);
		$this->db->like("expence_type",$search);
		$this->db->limit($limit);
		$by_username = $this->db->get();
		foreach($by_username->result() as $row)
		{
			$suggestions[]=array('label'=> $row->expence_type);		
		}


		$this->db->from('expences');
		$this->db->join('people','expences.employee_id=people.person_id');	
		$this->db->where('deleted', 0);
		$this->db->like("expence_time",$search);
		$this->db->limit($limit);
		$by_phone = $this->db->get();
		$temp_suggestions = array();
		foreach($by_phone->result() as $row)
		{
			$temp_suggestions[]=$row->expence_type;		
		}
		
		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);		
		}
		
		
		//only return $limit suggestions
		if(count($suggestions > $limit))
		{
			$suggestions = array_slice($suggestions, 0,$limit);
		}
		return $suggestions;
	
	}
	
	
	
	/*
	Preform a search on employees
	*/
	function search($search, $limit=20,$offset=0,$column='expence_time',$orderby='asc')
	{
			$this->db->from('expences');
			$this->db->join('people','expences.employee_id=people.person_id');		
			$this->db->where("(title LIKE '%".$this->db->escape_like_str($search)."%' or 
			expence_type LIKE '%".$this->db->escape_like_str($search)."%' or 
			expence_time 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($column, $orderby);
			$this->db->limit($limit);
			$this->db->offset($offset);
			return $this->db->get();
			//echo $this->db->last_query();
	}
	
	function search_count_all($search, $limit=10000)
	{
			$this->db->from('expences');
			$this->db->join('people','expences.employee_id=people.person_id');		
			$this->db->where("(title LIKE '%".$this->db->escape_like_str($search)."%' or 
			expence_type LIKE '%".$this->db->escape_like_str($search)."%' or 
			expence_time 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->limit($limit);
			$result=$this->db->get();	
			//echo $this->db->last_query();			
			return $result->num_rows();
	}
	
	/*
	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), 'deleted'=>0), 1);
		if ($query->num_rows() ==1)
		{
                    
			$row=$query->row();
			$this->session->set_userdata('person_id', $row->person_id);
                        $row = $this->is_employee_location($row->person_id);
                        $this->session->set_userdata('employee_current_location_id',$row->location_id);
                        $this->session->set_userdata('default_location_id', "1");
			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;
	}
	
	/*
	Gets the current employee's location. If they have more than 1, then a user can change during session
	*/
	function get_logged_in_employee_current_location_id()
	{
		if($this->is_logged_in())
		{
			//If we have a location in the session
			if ($this->session->userdata('employee_current_location_id')!==FALSE)
			{
				return $this->session->userdata('employee_current_location_id');
			}
			
			//Return the first location user is authenticated for
			return current($this->get_authenticated_location_ids($this->session->userdata('person_id')));
		}
		
		return FALSE;
	}
	
	function get_current_location_info()
	{
		return $this->Location->get_info($this->get_logged_in_employee_current_location_id());
	}
	function get_current_location_id()
	{
		return $this->get_logged_in_employee_current_location_id();
	
	}
	function get_current_location_name()
	{
		$location_data =  $this->Location->get_info($this->get_logged_in_employee_current_location_id());
		return $location_data->name;
	}
		
	function set_employee_current_location_id($location_id)
	{
		if ($this->is_location_authenticated($location_id))
		{
			$this->session->set_userdata('employee_current_location_id', $location_id);
		}
	}
	
	/*
	Determins whether the employee specified employee has access the specific module.
	*/
	function has_module_permission($module_id,$person_id)
	{
		//if no module_id is null, allow access
		if($module_id==null)
		{
			return true;
		}
		
		$query = $this->db->get_where('permissions', array('person_id' => $person_id,'module_id'=>$module_id), 1);
		return $query->num_rows() == 1;
	}
	
	function has_module_action_permission($module_id, $action_id, $person_id)
	{
		//if no module_id is null, allow access
		if($module_id==null)
		{
			return true;
		}
		
		$query = $this->db->get_where('permissions_actions', array('person_id' => $person_id,'module_id'=>$module_id,'action_id'=>$action_id), 1);
		return $query->num_rows() == 1;
	}
	
	function get_employee_by_username_or_email($username_or_email)
	{
		$this->db->from('employees');	
		$this->db->join('people', 'people.person_id = employees.person_id');
		$this->db->where('username',$username_or_email);
		$this->db->or_where('email',$username_or_email);
		$query = $this->db->get();
		
		if ($query->num_rows() == 1)
		{
			return $query->row();
		}
		
		return false;
	}
	
	function update_employee_password($employee_id, $password)
	{
		$employee_data = array('password' => $password);
		$this->db->where('person_id', $employee_id);
		$success = $this->db->update('employees',$employee_data);
		
		return $success;
	}
		
	function cleanup()
	{
		$employee_data = array('username' => null);
		$this->db->where('deleted', 1);
		return $this->db->update('employees',$employee_data);
	}
		
	function get_employee_id($username)
	{
		$query = $this->db->get_where('employees', array('username' => $username, 'deleted'=>0), 1);
		if ($query->num_rows() ==1)
		{
			$row=$query->row();
			return $row->person_id;
		}
		return false;
	}
	
	function get_authenticated_location_ids($employee_id)
	{
		$this->db->select('employees_locations.location_id');
		$this->db->from('employees_locations');
		$this->db->join('locations', 'locations.location_id = employees_locations.location_id');
		$this->db->where('employee_id', $employee_id);
		$this->db->where('locations.deleted', 0);
		$this->db->where('deleted', 0);
		$this->db->order_by('location_id', 'asc');
		
		$location_ids = array();
		
		foreach($this->db->get()->result_array() as $location)
		{
			$location_ids[] = $location['location_id'];
		}
		
		return $location_ids;
	}
	
	function is_location_authenticated($location_id)
	{
		if ($employee = $this->get_logged_in_employee_info())
		{
			$this->db->select('location_id');
			$this->db->from('employees_locations');
			$this->db->where('employee_id', $employee->person_id);
			$this->db->where('location_id', $location_id);
			$result = $this->db->get();

			return $result->num_rows() == 1;
		}
		
		return FALSE;
	}
        function is_employee_location($employee_id){
            $this->db->from('employees_locations');	
		$this->db->join('locations', 'employees_locations.location_id = locations.location_id');
		$this->db->where('employees_locations.employee_id',$employee_id);
		$query = $this->db->get();
		return $query->row();
        }
}
?>
