<?php
class Customer extends Person
{	
	/*
	Determines if a given person_id is a customer
	*/
	function exists($person_id)
	{
		$this->db->from('customers');	
		$this->db->join('people', 'people.person_id = customers.person_id');
		$this->db->where('customers.person_id',$person_id);
		$query = $this->db->get();
		
		return ($query->num_rows()==1);
	}

	function account_number_exists($account_number)
	{
		$this->db->from('customers');	
		$this->db->where('account_number',$account_number);
		$query = $this->db->get();
		
		return ($query->num_rows()==1);
	}
	
	function customer_id_from_account_number($account_number)
	{
		$this->db->from('customers');	
		$this->db->where('account_number',$account_number);
		$query = $this->db->get();
		
		if ($query->num_rows()==1)
		{
			return $query->row()->person_id;
		}
		
		return false;
	}
	
	/*
	Returns all the customers for saleman
	*/
	function get_all($limit=10000, $offset=0,$col='last_name',$order='asc')
	{
                $login_person_id = $this->session->userdata('person_id');
                $empl_curretn_location_id = $this->session->userdata('employee_current_location_id');
		$people=$this->db->dbprefix('people');
		$customers=$this->db->dbprefix('customers');
		if($empl_curretn_location_id==1){
                $data=$this->db->query("SELECT * FROM ".$people."
					STRAIGHT_JOIN ".$customers." ON 										                       
					".$people.".person_id = ".$customers.".person_id
					WHERE deleted =0  ORDER BY ".$col." ". $order." 
					LIMIT  ".$offset.",".$limit);
		}else{
			$login_person_id = $this->session->userdata('person_id');
                        $query = $this->db->query("select count(person_id) as total  from phppos_customers where saleman_id='$login_person_id'");
						$rows = $query->result_array();
					 	$result = $rows[0]['total'];

						if($result>0){
			$data=$this->db->query("SELECT * FROM ".$people."
					STRAIGHT_JOIN ".$customers." ON 										                       
					".$people.".person_id = ".$customers.".person_id
					WHERE deleted =0 AND ".$customers.".saleman_id = ". $login_person_id." ORDER BY ".$col." ". $order." 
					LIMIT  ".$offset.",".$limit);
						}else{
							
							$data=$this->db->query("SELECT * FROM ".$people."
					STRAIGHT_JOIN ".$customers." ON 										                       
					".$people.".person_id = ".$customers.".person_id
					WHERE deleted =0  ORDER BY ".$col." ". $order." 
					LIMIT  ".$offset.",".$limit);
							
							}
		
		}
		return $data;
	}
        /*
	Returns all the customers
	*/
	function get_all_customer($limit=10000, $offset=0,$col='last_name',$order='asc')
	{
                $login_person_id = $this->session->userdata('person_id');
                $empl_curretn_location_id = $this->session->userdata('employee_current_location_id');
		$people=$this->db->dbprefix('people');
		$customers=$this->db->dbprefix('customers');
                $data=$this->db->query("SELECT * FROM ".$people."
					STRAIGHT_JOIN ".$customers." ON 										                       
					".$people.".person_id = ".$customers.".person_id
					WHERE deleted =0 ORDER BY ".$col." ". $order." 
					LIMIT  ".$offset.",".$limit);
		
		return $data;
	}
	
	function count_all()
	{
		$this->db->from('customers');
		$this->db->where('deleted',0);
		return $this->db->count_all_results();
	}
	
	/*
	Gets information about a particular customer
	*/
	function get_info($customer_id)
	{
		$this->db->from('customers');	
		$this->db->join('people', 'people.person_id = customers.person_id');
		$this->db->where('customers.person_id',$customer_id);
		$query = $this->db->get();
		
		if($query->num_rows()==1)
		{
			return $query->row();
		}
		else
		{
			//Get empty base parent object, as $customer_id is NOT an customer
			$person_obj=parent::get_info(-1);
			
			//Get all the fields from customer table
			$fields = $this->db->list_fields('customers');
			
			//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 customers
	*/
	function get_multiple_info($customer_ids)
	{
		$this->db->from('customers');
		$this->db->join('people', 'people.person_id = customers.person_id');		
		$this->db->where_in('customers.person_id',$customer_ids);
		$this->db->order_by("last_name", "asc");
		return $this->db->get();		
	}
	
	/*
	Inserts or updates a customer
	*/
	function save(&$person_data, &$customer_data,$customer_id=false)
	{
            
		$success=false;
		//Run these queries as a transaction, we want to make sure we do all or nothing
		
		if(parent::save($person_data,$customer_id))
		{
			if (!$customer_id or !$this->exists($customer_id))
			{
				$customer_data['person_id'] = $person_data['person_id'];
				$success = $this->db->insert('customers',$customer_data);				
			}
			else
			{
				$this->db->where('person_id', $customer_id);
				$success = $this->db->update('customers',$customer_data);
			}
		}
		
		return $success;
	}
	
        
        
	/*
	Deletes one customer
	*/
	function delete($customer_id)
	{
		$customer_info = $this->Customer->get_info($customer_id);
	
		if ($customer_info->image_id !== NULL)
		{
			$this->Person->update_image(NULL,$customer_id);
			$this->Appfile->delete($customer_info->image_id);			
		}			
		
		$this->db->where('person_id', $customer_id);
		return $this->db->update('customers', array('deleted' => 1));
	}
	
	/*
	Deletes a list of customers
	*/
	function delete_list($customer_ids)
	{
		foreach($customer_ids as $customer_id)
		{
			$customer_info = $this->Customer->get_info($customer_id);
		
			if ($customer_info->image_id !== NULL)
			{
				$this->Person->update_image(NULL,$customer_id);
				$this->Appfile->delete($customer_info->image_id);			
			}			
		}
		
		$this->db->where_in('person_id',$customer_ids);
		return $this->db->update('customers', array('deleted' => 1));
 	}
	
	function check_duplicate($term)
	{
		$this->db->from('customers');
		$this->db->join('people','customers.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;
		}
		
		return false;
	}
 	/*
	Get search suggestions to find customers
	*/
	function get_search_suggestions($search,$limit=25)
	{
		$suggestions = array();
		
		$this->db->from('customers');
		$this->db->join('people','customers.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)."%' or 
		CONCAT(`last_name`,', ',`first_name`) 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->first_name;
		}
		
		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);		
		}
		
		$this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');	
		$this->db->where('deleted',0);		
		$this->db->like("email",$search);
		$this->db->limit($limit);
		$by_email = $this->db->get();
		
		$temp_suggestions = array();
		foreach($by_email->result() as $row)
		{
			$temp_suggestions[] = $row->email;
		}
		
		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);		
		}
		
		$this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');	
		$this->db->where('deleted',0);		
		$this->db->like("phone_number",$search);
		$this->db->limit($limit);	
		$by_phone = $this->db->get();
		
		$temp_suggestions = array();
		foreach($by_phone->result() as $row)
		{
			$temp_suggestions[]=$row->phone_number;		
		}
		
		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);		
		}
		
		
		$this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');	
		$this->db->where('deleted',0);		
		$this->db->like("account_number",$search);
		$this->db->limit($limit);
		$by_account_number = $this->db->get();
		
		$temp_suggestions = array();
		foreach($by_account_number->result() as $row)
		{
			$temp_suggestions[]=$row->account_number;		
		}
		
		sort($temp_suggestions);
		foreach($temp_suggestions as $temp_suggestion)
		{
			$suggestions[]=array('label'=> $temp_suggestion);		
		}
				
		$this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');	
		$this->db->where('deleted',0);		
		$this->db->like("company_name",$search);
		$this->db->limit($limit);
		$by_company_name = $this->db->get();
		
		$temp_suggestions = array();
		foreach($by_company_name->result() as $row)
		{
			$temp_suggestions[]= $row->company_name;	
		}
		
		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;
	
	}
	
	/*
	Get search suggestions to find customers
	*/
	function get_customer_search_suggestions($search,$limit=25)
	{
                $suggestions = array();
		$employee_id = $this->session->userdata('person_id');
                $store_id = $this->session->userdata('employee_current_location_id');
               $this->db->from('customers');
		$this->db->join('people','customers.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->limit($limit);	
		$by_name = $this->db->get();
		$temp_suggestions = array();
		foreach($by_name->result() as $row)
		{
			$temp_suggestions[$row->person_id] = $row->last_name.', '.$row->first_name;
		}
		
		asort($temp_suggestions);
		
		foreach($temp_suggestions as $key => $value)
		{
			$suggestions[]=array('value'=> $key, 'label' => $value);		
		}
		$this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');
                $this->db->where("`deleted` = 0 ");
                $this->db->like("account_number",$search);
		$this->db->limit($limit);
		$by_account_number = $this->db->get();
		
		$temp_suggestions = array();
		
		foreach($by_account_number->result() as $row)
		{
			$temp_suggestions[$row->person_id] = $row->account_number;
		}
		
		asort($temp_suggestions);
		
		foreach($temp_suggestions as $key => $value)
		{
			$suggestions[]=array('value'=> $key, 'label' => $value);		
		}
		
		$this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');
                $this->db->where("deleted = 0 "); 
		$this->db->like("email",$search);
		$this->db->limit($limit);
		$by_email = $this->db->get();
		$temp_suggestions = array();
		
		foreach($by_email->result() as $row)
		{
			$temp_suggestions[$row->person_id] = $row->email;
		}
		
		asort($temp_suggestions);
		
		foreach($temp_suggestions as $key => $value)
		{
			$suggestions[]=array('value'=> $key, 'label' => $value);		
		}
                $this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');	
		$this->db->where("deleted = 0 ");
                $this->db->like("phone_number",$search);
		$this->db->limit($limit);
		$by_phone_number = $this->db->get();
		
		$temp_suggestions = array();
		
		foreach($by_phone_number->result() as $row)
		{
			$temp_suggestions[$row->person_id] = $row->phone_number;
		}
		
		asort($temp_suggestions);
		
		foreach($temp_suggestions as $key => $value)
		{
			$suggestions[]=array('value'=> $key, 'label' => $value);		
		}
                //print_r($suggestions); exit;
		
		//only return $limit suggestions
		if(count($suggestions > $limit))
		{
			$suggestions = array_slice($suggestions, 0,$limit);
		}
		return $suggestions;

	}
        
    function get_customer_without_store_search_suggestions_new($search,$limit=25)
	{
		$employee_id = $this->session->userdata('person_id');

		 $query = $this->db->query("select count(person_id) as total  from phppos_customers where saleman_id='$employee_id'");
						$rows = $query->result_array();
					 	$result_customers_count = $rows[0]['total'];

		
                $suggestions = array();
                $store_id = $this->session->userdata('employee_current_location_id');
                $this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');	
		if($result_customers_count>0){

                $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 email LIKE '%".$this->db->escape_like_str($search)."%'"." "
                            . "or account_number LIKE '%".$this->db->escape_like_str($search)."%'"
                            ." or phone_number LIKE '%".$this->db->escape_like_str($search)."%'"
                            . ") and deleted=0 "
                            . "and `saleman_id` = '$employee_id' "
                           // . "and `is_store_account` = 'no'
							//"
							);
		}else{
				$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 email LIKE '%".$this->db->escape_like_str($search)."%'"." "
                            . "or account_number LIKE '%".$this->db->escape_like_str($search)."%'"
                            ." or phone_number LIKE '%".$this->db->escape_like_str($search)."%'"
                            . ") and deleted=0 "
                           // . "and `is_store_account` = 'no'
							//"
							);
		
		
		}
		$this->db->limit($limit);	
		$by_name = $this->db->get();
                
                $temp_suggestions = array();
		foreach($by_name->result() as $row)
		{
			$temp_suggestions[$row->person_id] = $row->last_name.', '.$row->first_name;
		}
		
		asort($temp_suggestions);
		
		foreach($temp_suggestions as $key => $value)
		{
			$suggestions[]=array('value'=> $key, 'label' => $value);		
		}
		
	
		
		//only return $limit suggestions
		if(count($suggestions > $limit))
		{
			$suggestions = array_slice($suggestions, 0,$limit);
		}
		return $suggestions;

	}        
        
        function get_customer_search_suggestions_new($search,$limit=25)
	{
		$employee_id = $this->session->userdata('person_id');

				 $query = $this->db->query("select count(person_id) as total  from phppos_customers where saleman_id='$employee_id'");
						$rows = $query->result_array();
					 	$result_customers_count = $rows[0]['total'];

                $suggestions = array();
                $store_id = $this->session->userdata('employee_current_location_id');
                $this->db->from('customers');
		$this->db->join('people','customers.person_id=people.person_id');	
		if($result_customers_count>0){
                $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 email LIKE '%".$this->db->escape_like_str($search)."%'"." "
                            . "or account_number LIKE '%".$this->db->escape_like_str($search)."%'"
                            ." or phone_number LIKE '%".$this->db->escape_like_str($search)."%'"
                            . ") and deleted=0 "
                            . "and `saleman_id` = $employee_id");
		}else{
			$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 email LIKE '%".$this->db->escape_like_str($search)."%'"." "
                            . "or account_number LIKE '%".$this->db->escape_like_str($search)."%'"
                            ." or phone_number 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->person_id] = $row->last_name.', '.$row->first_name;
		}
		
		asort($temp_suggestions);
		
		foreach($temp_suggestions as $key => $value)
		{
			$suggestions[]=array('value'=> $key, 'label' => $value);		
		}
		
	
		
		//only return $limit suggestions
		if(count($suggestions > $limit))
		{
			$suggestions = array_slice($suggestions, 0,$limit);
		}
		return $suggestions;

	}
	/*
	Preform a search on customers
	*/
	function search($search, $limit=20,$offset=0,$column='last_name',$orderby='asc')
	{
                        $login_person_id = $this->session->userdata('person_id');
                        $query = $this->db->query("select count(person_id) as total  from phppos_customers where saleman_id='$login_person_id'");
						$rows = $query->result_array();
					 	$result = $rows[0]['total'];

						if($result>0){
                        $this->db->from('customers');
			$this->db->join('people','customers.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 
                            account_number LIKE '%".$this->db->escape_like_str($search)."%' or 
                            company_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)."%') and deleted=0 and phppos_customers.saleman_id =".$login_person_id);
						}else{
						$this->db->from('customers');
			$this->db->join('people','customers.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 
                            account_number LIKE '%".$this->db->escape_like_str($search)."%' or 
                            company_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)."%') 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('customers');
			$this->db->join('people','customers.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 
			account_number LIKE '%".$this->db->escape_like_str($search)."%' or 
			company_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->limit($limit);
			$result=$this->db->get();
			//echo $this->db->last_query().'<br>';
			return $result->num_rows();
	}
		
	function cleanup()
	{
		$customer_data = array('account_number' => null);
		$this->db->where('deleted', 1);
		return $this->db->update('customers',$customer_data);
	}
        
        function get_store_balance($location_id){
            $this->db->from('customers');
            $this->db->where('customers.store_id',$location_id);
            $query = $this->db->get();
            if($query->num_rows()==1){
		return $query->row();
            }else{
                //Get empty base parent object, as $customer_id is NOT an customer
                $person_obj=parent::get_info(-1);

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

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

                return $person_obj;
            }
        }
        /*
         SAVE customer thruogh Location
         */
        
        function checkLocation($location_id){
            $this->db->from('customers');
            $this->db->where('customers.store_id',$location_id);
            $query = $this->db->get();
            return ($query->num_rows());
        }
        
        function saveCust_by_location(&$person_data, &$customer_data,$location_id=false){
            if($this->checkLocation($location_id) == 0){
                //Save
                $customer_id = false;
            }else{
                $location = $this->get_store_balance($location_id);
                $customer_id = $location->person_id;
            }
            $success=false;
            //Run these queries as a transaction, we want to make sure we do all or nothing
            
            if(parent::save($person_data,$customer_id))
            {
                    if (!$customer_id or !$this->exists($customer_id))
                    {
                            $customer_data['person_id'] = $person_data['person_id'];
                            $success = $this->db->insert('customers',$customer_data);				
                    }
                    else
                    {
                            $this->db->where('person_id', $customer_id);
                            $success = $this->db->update('customers',$customer_data);
                    }
            }

            return $success;
            
        }
        function get_person_info($store_id){
            $this->db->from('customers');
            $this->db->where('customers.store_id',$store_id);
            $query = $this->db->get();
            return $query->result();
        }
        function getSpecificCustomeSummaryData($customer_id,$start_date,$end_date){
                $this->db->select('sales.sale_id, sales_payments.payment_type, SUM(payment_amount) as Total');
		$this->db->from('sales');
		$this->db->join('sales_payments', 'sales.sale_id = sales_payments.sale_id');
		$this->db->where('sales.customer_id =',$customer_id);
                $this->db->where('sales_payments.payment_type =','Credit Account');
                $this->db->where('sales_payments.payment_date <=',$end_date);
                $this->db->where('sales_payments.payment_date >=',$start_date);
                $query = $this->db->get();
                
                return $query->row();
                
        }
        function getSpecificCustomeCashData($customer_id,$start_date,$end_date){
                $this->db->select('sales.sale_id, sales_payments.payment_type, SUM(payment_amount) as Total');
		$this->db->from('sales');
		$this->db->join('sales_payments', 'sales.sale_id = sales_payments.sale_id');
		$this->db->where('sales.customer_id =', $customer_id);
                $this->db->where('sales_payments.payment_type =','Cash');
                $this->db->where('sales_payments.payment_date <=',$end_date);
                $this->db->where('sales_payments.payment_date >=',$start_date);
                $query = $this->db->get();
               
                return $query->row();
        }
}
?>
