<?php	if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dispenser_sale_data extends CI_Controller {
	
	function __construct()	{
		parent::__construct();	
		//$this->lang->load('masters', '');
		$language = $this->session->userdata('language'); 
    		if ($language=='hindi') {
      	       $this->lang->load('hindi', '');
   			}else{
      		    $this->lang->load('masters', '');
            }
            //error_reporting(E_ALL);	
	}

	function index()	{	
		$this->list_dispenser_sale_data();
	}
	function list_dispenser_sale_data() {
		admin_auth();
		$this->_page_data['page_title']="List of Dispenser Sale Data";
		$this->_page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										' Manage Dispenser Sales'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
										'List Dispenser Sale Data'=>'#',
										);
		 
		$condition[] = array('join',TABLE_COMPANY_BRANCH.' as c','a.company_branch_id=c.company_branch_id','inner');
        $condition[] = array('join',TABLE_PRODUCT.' as d','a.product_id=d.product_id','inner');
        $condition[] = array('join',TABLE_CUSTOMER.' as b','a.customer_id = b.customer_id','inner');
        $selected_array=array(
                              'table_name'=>TABLE_DISPENSER_SALES.' as a',
                              'table_fields'=>'a.dispenser_sales_id,a.sales_person_name, a.dispenser_quantity, a.installation_date,a.sales_type, b.customer_name, d.product_name, c.company_branch_name',
                               'condition'=>$condition,
                               'limit'=>'',
                               'offset'=>''
                              );
        $dispenser['dispenser'] = $this->master_model->select_data($selected_array);
        if(!empty($dispenser['dispenser'] )&& is_array($dispenser['dispenser'] ))
		{
			$this->_page_data['dispenser'] = $dispenser['dispenser'];		 	
  	    }
	
		$this->load->view('gc/dispenser_sale_data_list.php',$this->_page_data);
	}
	
	function view_dispenser_sale_data() {
		admin_auth();
		$this->_page_data['page_title']="View Dispenser Sale Data";
		$this->_page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										' Manage Dispenser Sales'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
										'List Dispenser Sale Data'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
										'View Dispenser Sale Data'=>'#',
										);
		$this->load->view('gc/dispenser_sale_data_view.php',$this->_page_data);
	}
	
	function manage_dispenser_sale_data($purpose=NULL,$dispenser_sales_id='') {
		admin_auth();
		if($purpose=='')
			$purpose='Add';


		$this->_page_data['product_category'] =$this->fetch_product_category();
		$company_cond = array();
		$company_cond[] = array('where','is_active','1');
		$select_array = array(
								'table_name'=>TABLE_COMPANY_BRANCH,
								'table_fields'=>'company_branch_name,company_branch_id',
								'condition'=>$company_cond,
								'sort_by'=>'company_branch_id',
								'order_by_field'=>'company_branch_name',
								'group_by_field'=>'company_branch_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$company_data=$this->master_model->select_data($select_array);
		$company_cnt_data=count($company_data);
		$this->_page_data['company_branch_array'] = array();
		if($company_cnt_data > 0)
		{
			foreach($company_data as $cKey => $cValue)
			{
				$this->_page_data['company_branch_array'][''] = 'Select Company Branch';
				$this->_page_data['company_branch_array'][$cValue['company_branch_id']] = $cValue['company_branch_name'];
			}
		}
		
		/*
			Shreyas changed this customer to ajax on 8/16/2019
		*/
		// $customer_cond = array();
		// $customer_cond[] = array('where','is_active','1');
		// $select_array = array(
		// 						'table_name'=>TABLE_CUSTOMER,
		// 						'table_fields'=>'customer_name,customer_id',
		// 						'condition'=>$customer_cond,
		// 						'sort_by'=>'customer_id',
		// 						'order_by_field'=>'customer_name',
		// 						'group_by_field'=>'customer_name',
		// 						'order'=>'ASC',
		// 						'limit'=>'',
		// 						'offset'=>''
		// 						);
		// $customer_data=$this->master_model->select_data($select_array);
		// //dump($this->db->last_query());
		// $customer_cnt_data=count($customer_data);
		// $this->_page_data['customer_array'] = '';
		// if($customer_cnt_data > 0)
		// {
		// 	foreach($customer_data as $cKey => $cValue)
		// 	{
		// 		$this->_page_data['customer_array'][''] = 'Select Customer Name';
		// 		$this->_page_data['customer_array'][$cValue['customer_id']] = $cValue['customer_name'];
		// 	}
		// }
		
		$refill_cond = array();
		$refill_cond[] = array('where','is_active','1');
		$refill_cond[] = array('where','product_type','dispenser');
		$select_array = array(
								'table_name'=>TABLE_PRODUCT,
								'table_fields'=>'product_name,product_id',
								'condition'=>$refill_cond,
								'sort_by'=>'product_id',
								'order_by_field'=>'product_name',
								'group_by_field'=>'product_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$refill_data=$this->master_model->select_data($select_array);
		$refill_cnt_data=count($refill_data);
		$this->_page_data['refill_array'] = array();
		if($refill_cnt_data > 0)
		{
			foreach($refill_data as $cKey => $cValue)
			{
				$this->_page_data['refill_array'][''] = 'Select Dispenser Name';
				$this->_page_data['refill_array'][$cValue['product_id']] = $cValue['product_name'];
			}
		}
		
			
		/* if($dispenser_sales_id!="")
		{
			$condition=array();		
			$condition[]=array('where','a.dispenser_sales_id',$dispenser_sales_id);
			$condition[] = array('join',TABLE_COMPANY_BRANCH.' as c','a.company_branch_id=c.company_branch_id','inner');
			$condition[] = array('join',TABLE_PRODUCT.' as d','a.product_id=d.product_id','inner');
			$condition[] = array('join',TABLE_CUSTOMER.' as b','a.customer_id = b.customer_id','inner');
			$selected_array=array(
								  'table_name'=>TABLE_DISPENSER_SALES.' as a',
								  'table_fields'=>'a.dispenser_sales_id,a.sales_person_name, a.dispenser_quantity, a.installation_date,a.sales_type, b.customer_name, d.product_name, c.company_branch_name',
								   'condition'=>$condition,
								   'limit'=>'',
								   'offset'=>''
								  );
			$dispenser = $this->master_model->select_data($selected_array);
			if(!empty($dispenser )&& is_array($dispenser ))
			{
				$this->_page_data['dispenser'] = $dispenser;		 	
			}
		} */		
		$lable_dispenser_sale_data=$this->lang->line('lable_dispenser_sale_data', FALSE);
		$lable_customer_name=$this->lang->line('lable_customer_name', FALSE);
		$lable_branch_name=$this->lang->line('lable_branch_name', FALSE);
		$lable_salse_person_name=$this->lang->line('lable_salse_person_name', FALSE);
		$lable_customer_name=$this->lang->line('lable_customer_name', FALSE);
		$lable_dispenser_name=$this->lang->line('lable_dispenser_name', FALSE);
		$lable_dispenser_quantity=$this->lang->line('lable_dispenser_quantity', FALSE);
		$lable_instalaltion_date=$this->lang->line('lable_instalaltion_date', FALSE);
		$lable_sales_type=$this->lang->line('lable_sales_type', FALSE);
		$lable_is_contract_signed=$this->lang->line('lable_is_contract_signed', FALSE);
		$lable_customer_details=$this->lang->line('lable_customer_details', FALSE);
		$this->_page_data['lable_dispenser_details']=$this->lang->line('lable_dispenser_details', FALSE);
		$this->_page_data['lable_contract_details']=$this->lang->line('lable_contract_details', FALSE);
		$this->_page_data['lable_contract_start_date']=$this->lang->line('lable_contract_start_date', FALSE);
		$this->_page_data['lable_contract_end_date']=$this->lang->line('lable_contract_end_date', FALSE);
		$this->_page_data['lable_contract_attachment']=$this->lang->line('lable_contract_attachment', FALSE);
		$this->_page_data['lable_comments']=$this->lang->line('lable_comments', FALSE);
		
		$this->_page_data['lable_customer_name']=$lable_customer_name;
		$this->_page_data['lable_branch_name']=$lable_branch_name;
		$this->_page_data['lable_salse_person_name']=$lable_salse_person_name;
		$this->_page_data['lable_customer_name']=$lable_customer_name;
		$this->_page_data['lable_dispenser_name']=$lable_dispenser_name;
		$this->_page_data['lable_dispenser_quantity']=$lable_dispenser_quantity;
		$this->_page_data['lable_instalaltion_date']=$lable_instalaltion_date;
		$this->_page_data['lable_sales_type']=$lable_sales_type;
		$this->_page_data['lable_is_contract_signed']=$lable_is_contract_signed;
		$this->_page_data['lable_customer_details']=$lable_customer_details;

		$this->_page_data['lable_Product_Category']=$this->lang->line('lable_Product_Category', FALSE);
		$this->_page_data['lable_Price']=$this->lang->line('lable_Price', FALSE);		
		
		$this->_page_data['purpose']=$purpose;
		$this->_page_data['page_title']=$purpose." ".$lable_dispenser_sale_data;
		$this->_page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										' Manage Dispenser Sales'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
										$purpose.' '.$lable_dispenser_sale_data=>'#',
										);
										
		$this->_page_data['form_action'] = 'gc/dispenser_sale_data/submit_dispenser_sale_data';
		$this->load->view('gc/dispenser_sale_data_manage.php',$this->_page_data);
	}
	
	function submit_dispenser_sale_data()
	{
		admin_auth();
		
		$session_admin_id = $this->session->userdata('admin_id');
		$session_company_id=$this->session->userdata('company_id');
		$admin_type=$this->session->userdata('admin_type');
		$btn_confirm=check_injections_filter($this->input->post('btn_confirm')); 
		$branch_name=check_injections_filter($this->input->post('company_branch_id')); 
		$customer_id=check_injections_filter($this->input->post('customer_id')); 
		$sale_person_name=check_injections_filter($this->input->post('sale_person_name')); 
		$dispenser_id=check_injections_filter($this->input->post('dispenser_id')); 
		$dispenser_quantity=check_injections_filter($this->input->post('dispenser_quantity')); 
		$sale_date=check_injections_filter($this->input->post('sale_date')); 
		$contract_sign=check_injections_filter($this->input->post('contract_sign')); 
		$contract_start_date=check_injections_filter($this->input->post('contract_start_date')); 
		$contract_end_date=check_injections_filter($this->input->post('contract_end_date')); 
		$comments=check_injections_filter($this->input->post('comments')); 
		$sales_type=check_injections_filter($this->input->post('sales_type'));

		$product_category_id=check_injections_filter($this->input->post('product_category_id'));
	
		/*Name :- Shreyas Vispute
		  Date:- 8 August 2019
		  Client Requirement
		*/
		$price=check_injections_filter($this->input->post('c_price'));  

		// echo $branch_name."<br>";
		// echo $customer_id."<br>";
		// echo $sale_person_name."<br>";
		// echo $dispenser_id."<br>";
		// echo $dispenser_quantity."<br>";
		// echo $sale_date."<br>";
		// echo $comments."<br>";
		// echo $sales_type."<br>";
	 //    exit;

		
		if($contract_sign==1)
		{
			$contract_start_date=date("Y-m-d",strtotime($contract_start_date));
			$contract_end_date=date("Y-m-d",strtotime($contract_end_date));
		}
		else
		{
			$contract_start_date='';
			$contract_end_date='';
		}
		$sale_date=date("Y-m-d",strtotime($sale_date));
		
		
		
		if(isset($btn_confirm) && !empty($btn_confirm))
		{
			/* $this->load->library('form_validation');
			$this->form_validation->set_rules('branch_id', 'Branch Name','required'); 
			$this->form_validation->set_rules('customer_id', 'Customer Name','required'); 
			$this->form_validation->set_rules('sale_person_name', 'Company','required'); 
			$this->form_validation->set_rules('dispenser_id', 'Dispenser','required'); 			
			$this->form_validation->set_message('required', '* %s required');
			$this->form_validation->set_message('isset', '* required');
			$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
			if ($this->form_validation->run() == FALSE)
			{
				
				$this->_page_data['purpose']=$purpose;
				$this->_page_data['page_title']=$purpose." Dispenser Sale Data";
				$this->_page_data['bredcrum']=array(
												'Dispenser Sales'=>'#',
												' Manage Dispenser Sales'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
												$purpose.' Dispenser Sale Data'=>'#',
												);
												
				$this->_page_data['form_action'] = 'gc/dispenser_sale_data/submit_dispenser_sale_data';
				$this->load->view('gc/dispenser_sale_data_manage.php',$this->_page_data);
			}
			else
			{ */	
				$AssociatehDocument='';
				if($_FILES['attachment']['name']!="")
				{
					$upload_path = CONTRACT_PATH.'/'.$company_id.'/';
					$upload_research_target_dir = CONTRACT_PATH;
					$associateUploadDocument = $_FILES['attachment']['name'];
					if (!file_exists($upload_research_target_dir.'/'.$customer_id)) {
						mkdir($upload_research_target_dir.'/'.$customer_id, 0777,TRUE);
					}
					
					$upload_research_target_dir = CONTRACT_PATH.$customer_id."/";
					$userfile_extn = explode(".", strtolower($_FILES['attachment']['name']));	
					$AssociatehDocument=$userfile_extn[0].time().".".$userfile_extn[1];
					
					$imageFileTypeUpload = strtolower(pathinfo($associateUploadDocument,PATHINFO_EXTENSION));
					$main_research_target_file = $upload_research_target_dir .$AssociatehDocument;
					$main_research_target_file_send =$AssociatehDocument;
					$uploadOk = 1;	
					// Check file size					  
					if ($_FILES["attachment"]["size"] > 5242880) {
						$err_msg =  "Sorry, your file is large. File size of the document should be less than 5 MB";
						$uploadOk = 0;
					}
					
					// Allow certain file formats
					 if($imageFileTypeUpload != "png" && $imageFileTypeUpload != "jpeg" && $imageFileTypeUpload != "jpg" && $imageFileTypeUpload != "pdf") {
						$err_msg =  "Sorry, only JPEG,JPG,PNG,PDF files are allowed.";
						$uploadOk = 0;
					}
					
					if ($uploadOk == 1)			 
					{
						 if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $main_research_target_file)) 
						 {					 
							//echo $err_msg="uploded ";
						} else {
							//echo $err_msg =  "Sorry, there was an error uploading your file.";
							$uploadOk = 0;
						}
					}
				}
				
			
				 $data_log = array(
									'company_branch_id'=>$branch_name,
									'customer_id'=>$customer_id,
									'sales_person_id'=>$sale_person_name,
									'product_id'=>$dispenser_id,
									'dispenser_quantity'=>$dispenser_quantity,
									'installation_date'=>$sale_date,
									'sales_type'=>$sales_type,
									'price'=>$price,
									'is_contract_signed'=>$contract_sign,
									'contract_start_date'=>$contract_start_date,
									'contract_end_date'=>$contract_end_date,
									'contract_attachment'=>$AssociatehDocument,
									'comments'=>$comments,
									'product_category_id'=>$product_category_id,
									'is_active'=>'1',
									'created_on' =>date("Y-m-d H:i:s")							
								); 
				// $this->master_model->insert_record(TABLE_DISPENSER_SALES,$data_log);
				$this->master_model->insert_record(TABLE_DISPENSER_SALES_TEMP,$data_log);				
				$dispenser_sales_id = $this->db->insert_id();				
			//	$dispenser_sales_id = $this->encrypt->encode(($dispenser_sales_id));
				$dispenser_sales_id=encrypt_decrypt_parameters($dispenser_sales_id,'encrypt');
				redirect(DISPENSER_SALES_DATA."/refill_and_track_data/".$dispenser_sales_id);
			//}
		}
		
	}

	function refill_and_track_data($dispenser_sales_id,$action=null) {
		admin_auth();
		
	
		if($purpose=='')
			$purpose='Add';
				
		 //$dispenser_sales_id = $this->encrypt->decode(($dispenser_sales_id));
		  $dispenser_sales_id=encrypt_decrypt_parameters($dispenser_sales_id,'decrypt');
		$cond=array();		
		$cond[]=array('where','dispenser_sales_id',$dispenser_sales_id);
		$cond[]=array('join',TABLE_CUSTOMER.' as C','A.customer_id=C.customer_id','left');
		$cond[]=array('join',TABLE_COMPANY_BRANCH.' as D','A.company_branch_id=D.company_branch_id','left');		
		$cond[]=array('join',TABLE_PRODUCT.' as B','A.product_id=B.product_id','left');		
		$cond[]=array('join',TABLE_USERS.' as E','A.sales_person_id=E.user_id','left');
		$cond[]=array('join',TABLE_PRODUCT_CATEGORY.' as pc','pc.product_category_id=A.product_category_id','left');			
		// $company_array=array(
		// 					'table_name'=>TABLE_DISPENSER_SALES." as A",
		// 					'table_fields'=>'A.company_branch_id,A.customer_id,E.first_name,E.last_name, A.dispenser_quantity,A.installation_date,C.customer_name, D.company_branch_name, B.product_name ,B.stock_quantity, B.product_prefix,A.product_id,A.sales_type',
		// 					'condition'=>$cond,
		// 					'sort_by' => 'dispenser_sales_id', 
		// 					'limit'=>'',
		// 					'offset'=>''
		// 					);	
		$company_array=array(
							'table_name'=>TABLE_DISPENSER_SALES_TEMP." as A",
							'table_fields'=>'A.dispenser_sales_id,A.company_branch_id,A.customer_id,E.first_name,E.last_name, A.dispenser_quantity,A.installation_date,C.customer_name, D.company_branch_name, B.product_name ,B.stock_quantity, B.product_prefix,A.product_id,A.sales_type,A.product_category_id,pc.product_category_name',
							'condition'=>$cond,
							'sort_by' => 'dispenser_sales_id', 
							'limit'=>'',
							'offset'=>''
							);	
											
		$company_data=$this->master_model->select_data($company_array);
		
		$company_cnt_data=count($company_data);
		
		
		if($company_cnt_data >0){
			$this->_page_data['sales_person_name']= isset($company_data[0]['sales_person_name']) && !empty($company_data[0]['sales_person_name']) ? $company_data[0]['sales_person_name'] :'';
			$this->_page_data['company_name']= isset($company_data[0]['company_name']) && !empty($company_data[0]['company_name']) ? $company_data[0]['company_name'] :'';
			$this->_page_data['sales_type']= isset($company_data[0]['sales_type']) && !empty($company_data[0]['sales_type']) ? $company_data[0]['sales_type'] :'';

			$this->_page_data['temp_dispenser_sale_id']= isset($company_data[0]['dispenser_sales_id']) && !empty($company_data[0]['dispenser_sales_id']) ? $company_data[0]['dispenser_sales_id'] :'';

			$this->_page_data['first_name']= isset($company_data[0]['first_name']) && !empty($company_data[0]['first_name']) ? $company_data[0]['first_name'] :'';
			$this->_page_data['last_name']= isset($company_data[0]['last_name']) && !empty($company_data[0]['last_name']) ? $company_data[0]['last_name'] :'';
			$this->_page_data['dispenser_quantity']= isset($company_data[0]['dispenser_quantity']) && !empty($company_data[0]['dispenser_quantity']) ? $company_data[0]['dispenser_quantity'] :'';
			$this->_page_data['installation_date']= isset($company_data[0]['installation_date']) && !empty($company_data[0]['installation_date']) ? $company_data[0]['installation_date'] :'';
			$this->_page_data['product_name']= isset($company_data[0]['product_name']) && !empty($company_data[0]['product_name']) ? $company_data[0]['product_name'] :'';
			$this->_page_data['product_prefix']= isset($company_data[0]['product_prefix']) && !empty($company_data[0]['product_prefix']) ? $company_data[0]['product_prefix'] :'';
			$this->_page_data['stock_quantity']= isset($company_data[0]['stock_quantity']) && !empty($company_data[0]['stock_quantity']) ? $company_data[0]['stock_quantity'] :'';
			$this->_page_data['customer_id']= isset($company_data[0]['customer_id']) && !empty($company_data[0]['customer_id']) ? $company_data[0]['customer_id'] :'';

			$this->_page_data['company_branch_id']= isset($company_data[0]['company_branch_id']) && !empty($company_data[0]['company_branch_id']) ? $company_data[0]['company_branch_id'] :'';
			$product_id= isset($company_data[0]['product_id']) && !empty($company_data[0]['product_id']) ? $company_data[0]['product_id'] :'';
			$this->_page_data['customer_name']= isset($company_data[0]['customer_name']) && !empty($company_data[0]['customer_name']) ? $company_data[0]['customer_name'] :'';
			$this->_page_data['company_branch_name']= isset($company_data[0]['company_branch_name']) && !empty($company_data[0]['company_branch_name']) ? $company_data[0]['company_branch_name'] :'';

			$this->_page_data['product_category_name']= isset($company_data[0]['product_category_name']) && !empty($company_data[0]['product_category_name']) ? $company_data[0]['product_category_name'] :'';


		}
		
		$refill_cond = array();
		$refill_cond[] = array('where','is_active','1');
		$refill_cond[] = array('where','product_type','Refill');
		//$refill_cond[] = array('where','dispenser_name',$product_id);
		$refill_ids=get_data_value(TABLE_PRODUCT,'refill_ids','product_id',$product_id,'where');
		$refill_id=explode(",",$refill_ids);
		// $refill_cond[] = array('where','product_id IN ('.$refill_ids.')',null,false);
		$refill_cond[] = array('where_in','product_id',$refill_id);

		$select_array = array(
								'table_name'=>TABLE_PRODUCT,
								'table_fields'=>'product_name,product_id',
								'condition'=>$refill_cond,
								'sort_by'=>'product_id',
								'order_by_field'=>'product_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$refill_data=$this->master_model->select_data($select_array);
		//dump($this->db->last_query());
		$refill_cnt_data=count($refill_data);
		$this->_page_data['refill_array'] = array();
		if($refill_cnt_data > 0)
		{
			foreach($refill_data as $cKey => $cValue)
			{
				$this->_page_data['refill_array'][''] = 'Select Refill Name';
				$this->_page_data['refill_array'][$cValue['product_id']] = $cValue['product_name'];
			}
		}
		//dump($this->db->last_query());
		
		$tracking_cond = array();
		
		//$tracking_cond[] = array('where','is_status','Not Allocated');
		/*
          Shreyas Vispute changed to this condition on 31/7/19 because tracking number is not showing which is possed by company 
		*/
		$tracking_cond[] = array('where_not_in','is_status','Customer');
		$tracking_cond[] = array('where','product_id',$product_id);
		//$tracking_cond[] = array('where','possessed_by',$this->_page_data['company_branch_id']);
		//$tracking_cond[] = array('or_where','possessed_by',0);
		$tracking_cond[] = array('where','(possessed_by = "'.$this->_page_data['company_branch_id'].'" OR possessed_by = "0")',NULL,FALSE);
		
		$select_array = array(
								'table_name'=>TABLE_TRACKING_NUMBERS,
								'table_fields'=>'tracking_numbers_id,tracking_number',
								'condition'=>$tracking_cond,
								'sort_by'=>'tracking_numbers_id',
								'order_by_field'=>'tracking_number',
								'order'=>'ASC',
								'limit'=>'40000',
								'offset'=>''
								);
		$tracking_data=$this->master_model->select_data($select_array);
		//dump($this->db->last_query());
		$tracking_cnt_data=count($tracking_data);
		$this->_page_data['tracking_array'] = array();
		if($tracking_cnt_data > 0)
		{
			foreach($tracking_data as $cKey => $cValue)
			{
				//$this->_page_data['tracking_array'][''] = 'Select Traking Numbers';
				$this->_page_data['tracking_array'][$cValue['tracking_numbers_id']] = $cValue['tracking_number'];
			}
		}
		
		
		
		
		$this->_page_data['purpose']=$purpose;
		$this->_page_data['dispenser_sales_id']=$dispenser_sales_id;
		$this->_page_data['page_title']=$purpose." Dispenser Sale Data";
		$this->_page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										' Manage Dispenser Sales'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
										$purpose.' Dispenser Sale Data'=>'#',
										'Refill Data'=>'#',
										);
		$this->_page_data['form_action'] = 'gc/dispenser_sale_data/submit_refill_details';
		
		
		if($action=="change")
		{
						
			$this->load->view('gc/change_refill_details.php',$this->_page_data);
		}
		else
		{
			$this->load->view('gc/add_refill_details.php',$this->_page_data);
		}
		
		
	}
	
	function submit_refill_details()
	{
		admin_auth();
//error_reporting(E_ALL);
		$temp_dispenser_sale_id = $this->input->post('temp_dispenser_sale_id');
		
		$cond_temp_add=array();		
		$cond_temp_add[]=array('where','dispenser_sales_id',$temp_dispenser_sale_id);

	    $company_array=array(
							'table_name'=>TABLE_DISPENSER_SALES_TEMP,
							'table_fields'=>'dispenser_sales_id,company_branch_id,customer_id,sales_person_id,product_id,dispenser_quantity,installation_date,sales_type,price,is_contract_signed,contract_start_date,contract_end_date,contract_attachment,comments,is_active,created_on,created_by,modified_on,modified_by,old_enduser_product_transaction_id',
							'sort_by' => 'dispenser_sales_id',
							'condition'=>$cond_temp_add,
							'limit'=>'',
							'offset'=>'',
		);	
											
		$company_data['data']=$this->master_model->select_data($company_array);
		
		if(!empty($company_data['data'] )&& is_array($company_data['data'])){
		foreach ($company_data['data'] as  $value) {
        	$company_branch_id=$value['company_branch_id'];
        	$customer_id=$value['customer_id'];
        	$sales_person_id=$value['sales_person_id'];
        	$product_id=$value['product_id'];
        	$dispenser_quantity=$value['dispenser_quantity'];
        	$installation_date=$value['installation_date'];
        	$sales_type=$value['sales_type'];
        	$price=$value['price'];
        	$is_contract_signed=$value['is_contract_signed'];
        	$contract_start_date=$value['contract_start_date'];
        	$contract_end_date=$value['contract_end_date'];
        	$contract_attachment=$value['contract_attachment'];
        	$comments=$value['comments'];
        	$is_active=$value['is_active'];
        	$created_on=$value['created_on'];
        	$created_by=$value['created_by'];
        	$modified_on=$value['modified_on'];
        	$modified_by=$value['modified_by'];
        	$old_enduser_product_transaction_id=$value['old_enduser_product_transaction_id'];
        }
       
 	
        $datas_log = array(
									'company_branch_id'=>$company_branch_id,
									'customer_id'=>$customer_id,
									'sales_person_id'=>$sales_person_id,
									'product_id'=>$product_id,
									'dispenser_quantity'=>$dispenser_quantity,
									'installation_date'=>$installation_date,
									'sales_type'=>$sales_type,
									'price'=>$price,
									'is_contract_signed'=>$is_contract_signed,
									'contract_start_date'=>$contract_start_date,
									'contract_end_date'=>$contract_end_date,
									'contract_attachment'=>$contract_attachment,
									'comments'=>$comments,
									'is_active'=>'1',
									'created_on' =>$created_on,
									'created_by'=>$created_by,
									'modified_on' =>$modified_on,
									'modified_by' =>$modified_by,						
								); 
		 $this->master_model->insert_record(TABLE_DISPENSER_SALES,$datas_log);
		 $dispenser_sales_id = $this->db->insert_id();
		  if ($dispenser_sales_id!='') {
        	$con_delete = 'dispenser_sales_id = 0' ;
       	  	$this->master_model->delete_record(TABLE_DISPENSER_SALES_TEMP,$con_delete);  
        }
     }
		$user_id = $this->session->userdata('user_id');
		


		// /$dispenser_sales_id=check_injections_filter($this->input->post('dispenser_sales_id'));
		$refill_location=($this->input->post('refill_location'));
		$refill_date=($this->input->post('refill_date'));
		$refill_comments=($this->input->post('refill_comments'));
		
		$programming_days=($this->input->post('programming_days'));
		
		$tracking_no=($this->input->post('tracking_no'));
		
		$refill_product_id=($this->input->post('refill_product_id'));
		$tracking_no=($this->input->post('tracking_no'));
		
		$refill_quantity=($this->input->post('refill_quantity'));
		$refill_uom=($this->input->post('uom'));
		
		$customer_id=check_injections_filter($this->input->post('customer_id'));
		$company_branch_id=check_injections_filter($this->input->post('company_branch_id'));
//shreyas changed to sales type validation
		if($sales_type=='FTU'){
			foreach($tracking_no as $cKey => $cVal){
				$tracking_no = isset($cVal) && !empty($cVal) ? ($cVal) : '';			
				$tracking_nos=  implode(",",$tracking_no);
				$refill_location1 = isset($refill_location[$cKey]) && !empty($refill_location[$cKey]) ? check_injections_filter($refill_location[$cKey]) : ''; 
				$refill_date1 = isset($refill_date[$cKey]) && !empty($refill_date[$cKey]) ? check_injections_filter($refill_date[$cKey]) :'';

				$refill_comment1= isset($refill_comments[$cKey]) && !empty($refill_comments[$cKey]) ? check_injections_filter($refill_comments[$cKey]) :'';

				$programming_days1 = isset($programming_days[$cKey]) && !empty($programming_days[$cKey]) ? check_injections_filter($programming_days[$cKey]) :'';
				$refill_product_id1 = isset($refill_product_id[$cKey]) && !empty($refill_product_id[$cKey]) ? check_injections_filter($refill_product_id[$cKey]) :'';
				$refill_quantity1 = isset($refill_quantity[$cKey]) && !empty($refill_quantity[$cKey]) ? check_injections_filter($refill_quantity[$cKey]) :'';
				$refill_uom1 = isset($refill_uom[$cKey]) && !empty($refill_uom[$cKey]) ? check_injections_filter($refill_uom[$cKey]) :'';
 			    
				
				$des_refill_date=date("Y-m-d",strtotime($refill_date1));
				$cur_date=date("Y-m-d");
				$next_refill_date=date('Y-m-d', strtotime($des_refill_date. ' + '.$programming_days1.' day'));
				$data_log = array(
									'dispenser_sales_id'=>$dispenser_sales_id,
									'tracking_numbers'=>$tracking_nos,
									'product_id'=>$refill_product_id1,
									'duration_days'=>$programming_days1,
									'quantity'=>$refill_quantity1,
									'unit_of_measurment'=>$refill_uom1,
									'refill_date'=>$des_refill_date,
									'next_refill_date'=>$next_refill_date,
									'refill_location'=>$refill_location1,
									'comments'=>$refill_comment1,
									'created_by'=>$user_id,
									'is_active'=>'1',
									'created_on' =>date("Y-m-d H:i:s")							
								); 
				 $dispenser_refill_details_id=$this->master_model->insert_record(TABLE_DISPENSER_REFILL_DETAILS,$data_log);
			
				    foreach($tracking_no as $cKey1 => $cVal1){
					
					$tracking_num = isset($cVal1) && !empty($cVal1) ? ($cVal1) : '';
					
					$tracking_num_name=get_data_value(TABLE_TRACKING_NUMBERS,'tracking_number','tracking_numbers_id',$tracking_num,'where');
					$data_log = array(
									'tracking_numbers_id'=>$tracking_num,
									'tracking_number'=>$tracking_num_name,
									'company_branch_id'=>$company_branch_id,
									'customer_id'=>$customer_id,
									'dispenser_sales_id'=>$dispenser_sales_id,
									'dispenser_refill_details_id'=>$dispenser_refill_details_id,
									'refill_date'=>$des_refill_date,
									'next_refill_date'=>$next_refill_date,
									'created_by'=>$user_id,
									'created_on' =>date("Y-m-d H:i:s")							
								); 

					   $this->master_model->insert_record(TABLE_TRACKING_DETAILS,$data_log);
						$this->session->set_flashdata('message','Sales data added successfully');
					
					$tack_data_log = array(
									'is_status'=>'Customer',				
									'possessed_by'=>$customer_id					
								);
				
					$condition=array('tracking_numbers_id'=>$tracking_num);
					$this->master_model->update_record(TABLE_TRACKING_NUMBERS,$tack_data_log,$condition);

					$update_customer_status = array(
									'sales_status'=>'won',									
								);
					$condition_customer=array('customer_id'=>$customer_id);
					$this->master_model->update_record(TABLE_CUSTOMER,$update_customer_status,$condition_customer);
				}
			}
		}else{

			foreach($refill_product_id as $cKey => $cVal){

				$tracking_no = isset($cVal) && !empty($cVal) ? ($cVal) : '';			
				$tracking_nos=  implode(",",$tracking_no);
				$refill_location1 = isset($refill_location[$cKey]) && !empty($refill_location[$cKey]) ? check_injections_filter($refill_location[$cKey]) : ''; 
				$refill_date1 = isset($refill_date[$cKey]) && !empty($refill_date[$cKey]) ? check_injections_filter($refill_date[$cKey]) :'';

				$refill_comment1= isset($refill_comments[$cKey]) && !empty($refill_comments[$cKey]) ? check_injections_filter($refill_comments[$cKey]) :'';

				$programming_days1 = isset($programming_days[$cKey]) && !empty($programming_days[$cKey]) ? check_injections_filter($programming_days[$cKey]) :'';
				$refill_product_id1 = isset($refill_product_id[$cKey]) && !empty($refill_product_id[$cKey]) ? check_injections_filter($refill_product_id[$cKey]) :'';
				$refill_quantity1 = isset($refill_quantity[$cKey]) && !empty($refill_quantity[$cKey]) ? check_injections_filter($refill_quantity[$cKey]) :'';
 			    $refill_uom1 = isset($refill_uom[$cKey]) && !empty($refill_uom[$cKey]) ? check_injections_filter($refill_uom[$cKey]) :'';
				
				$des_refill_date=date("Y-m-d",strtotime($refill_date1));
				$cur_date=date("Y-m-d");
				$next_refill_date=date('Y-m-d', strtotime($des_refill_date. ' + '.$programming_days1.' day'));
				$data_log = array(
									'dispenser_sales_id'=>$dispenser_sales_id,
									'tracking_numbers'=>$tracking_no,
									'product_id'=>$refill_product_id1,
									'duration_days'=>$programming_days1,
									'quantity'=>$refill_quantity1,
									'unit_of_measurment'=>$refill_uom1,
									'refill_date'=>$des_refill_date,
									'next_refill_date'=>$next_refill_date,
									'refill_location'=>$refill_location1,
									'comments'=>$refill_comment1,
									'created_by'=>$user_id,
									'is_active'=>'1',
									'created_on' =>date("Y-m-d H:i:s")							
								); 
				 $dispenser_refill_details_id=$this->master_model->insert_record(TABLE_DISPENSER_REFILL_DETAILS,$data_log);
				 $this->session->set_flashdata('message','Sales data added successfully');



				 	 $update_customer_status = array(
									'sales_status'=>'won',									
								);
					$condition_customer=array('customer_id'=>$customer_id);
					$this->master_model->update_record(TABLE_CUSTOMER,$update_customer_status,$condition_customer);
		  }

		}
		//if(isset) close
		redirect(DISPENSER_SALES_DATA."manage_dispenser_sale_data/");
		
	}
	
	function search_return_dispenser($purpose=NULL) {
		admin_auth();
		if($purpose=='')
			$purpose='Add';
		
		$this->_page_data['purpose']=$purpose;
		$this->_page_data['page_title']="Return Dispenser";
		//$this->_page_data['dispenser']=$this->fetch_dispenser();
		$this->_page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										//'Manage Dispenser Sales'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
										'Return Dispenser'=>'#',
										///'Refill Data'=>'#',
										);

		// $customer_cond = array();
		// $customer_cond[] = array('where','is_active','1');
		// $select_array = array(
		// 						'table_name'=>TABLE_CUSTOMER,
		// 						'table_fields'=>'customer_name,customer_id',
		// 						'condition'=>$customer_cond,
		// 						'sort_by'=>'customer_id',
		// 						'order_by_field'=>'customer_name',
		// 						'order'=>'ASC',
		// 						'limit'=>'',
		// 						'offset'=>''
		// 						);
		// $customer_data=$this->master_model->select_data($select_array);
		// $customer_cnt_data=count($customer_data);
		// $this->_page_data['customer_array'] = '';
		// if($customer_cnt_data > 0)
		// {
		// 	foreach($customer_data as $cKey => $cValue)
		// 	{
		// 		$this->_page_data['customer_array'][''] = 'Select Customer Name';
			// 		$this->_page_data['customer_array'][$cValue['customer_id']] = $cValue['customer_name'];
		// 	}
		// }

		$this->load->view('gc/search_return_dispenser.php',$this->_page_data);
	}
	
	function return_dispenser_list($customer_id='',$export='') {
		admin_auth();
	//error_reporting(E_ALL);

		$this->_page_data['page_title']="Return Dispenser Details";
		$this->_page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										//'Manage Dispenser Sales'=>site_url('gc/dispenser_sale_data/list_dispenser_sale_data'),
										'Return Dispenser'=>'#',
										'Return Dispenser Details'=>'#',
										);

		if ($export=='export') {
			$customer_id=$customer_id;
		}else{
			$customer_id = check_injections_filter($this->input->post('customer_id'));
		}
    	

  //   	$cond[] = array('where','tracking_number',$tracking_number);
  //   	$selected_array=array(
		// 						'table_name' =>TABLE_TRACKING_NUMBERS,								
		// 						'table_fields'=>'tracking_number',
		// 						'condition'=>$cond,
		// 						'limit' => '',
		// 						'offset' => ''						
		// 			    );
		// $track['track'] = $this->master_model->select_data($selected_array);
		// if(!empty($track['track']))
		// {	

		/*
			Shreyas 
			8/9/2019
			Client want Customer  Name and make listing of all tracking number related to Customer Name
		*/	
    	$this->_page_data['customer_id']  =  $customer_id;
    	$condition[] = array('join',TABLE_COMPANY_BRANCH.' as b','b.company_branch_id = d.company_branch_id','inner');
    	$condition[] = array('join',TABLE_USERS.' as u','u.user_id = d.sales_person_id','left');
		$condition[] = array('join',TABLE_CUSTOMER.' as c','c.customer_id = d.customer_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_DETAILS.' as t','t.dispenser_sales_id = d.dispenser_sales_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_NUMBERS.' as tr','tr.tracking_numbers_id = t.tracking_numbers_id','inner');
    	$condition[] = array('join',TABLE_PRODUCT.' as p','p.product_id = d.product_id','inner');
		   if ($customer_id!='') {
			$condition[] = array('where','c.customer_id',$customer_id);
		   }
    	
    	$condition[] = array('where','d.sales_type','FTU');
    	$condition[] = array('where','t.is_returned','no');

  	
    	//$condition[] = array('where','p.product_type','dispenser');

        $select_array=array(
                             'table_name'=>TABLE_DISPENSER_SALES.' as d',
                              'table_fields'=>'p.product_id,d.sales_type, p.product_name AS dispenser, c.customer_name, b.company_branch_name, tr.tracking_number, t.refill_date, t.next_refill_date,u.first_name,u.last_name,tr.tracking_numbers_id,b.company_branch_id,t.is_returned,d.dispenser_sales_id,t.tracking_details_id,t.comments',
                              'condition'=>$condition,
                              'limit'=>'',
                              'offset'=>'',
                              'order_by_field'=>'t.refill_date',
                              'group_by_field'=>'tr.tracking_number',
                              'order'=>'DESC'
                            );
        $return['return']=$this->master_model->select_data($select_array);
		
		if($_SERVER['REMOTE_ADDR']=="116.73.6.137")
		{
			//dump($this->db->last_query());  
		}
        $this->_page_data['return'] ='';      
        if(!empty($return['return'])&& is_array($return['return'])){

        	foreach ($return['return'] as $value) {
        	//  $this->_page_data['sales_type']= $value['sales_type'];
        	//  $this->_page_data['dispenser']= $value['dispenser'];
        	  $this->_page_data['customer_name']= $value['customer_name'];
        	//  $this->_page_data['company_branch_name']= $value['company_branch_name'];
        	//  $this->_page_data['tracking_number']= $value['tracking_number'];
        	//  $this->_page_data['refill_date']= $value['refill_date'];
        	//  $this->_page_data['next_refill_date']= $value['next_refill_date'];
        	//  $this->_page_data['first_name']= $value['first_name'];
        	//  $this->_page_data['last_name']= $value['last_name'];
        	//  $this->_page_data['product_id']= $value['product_id'];
        	//  $this->_page_data['tracking_numbers_id']= $value['tracking_numbers_id'];
        	//  $this->_page_data['company_branch_id']= $value['company_branch_id'];
        	//  $this->_page_data['returned']= $value['is_returned'];
             }
							
	        $this->_page_data['return'] =  $return['return'];
		 	
  	    }else{
  	    	$return['return']='';
  	    }
		if ($export=='export') {
			$this->load->view('gc/return_dispenser_list_excel.php',$this->_page_data);
		}else{
			$this->load->view('gc/return_dispenser_list.php',$this->_page_data);
		}
		
			
					 
	    // }else{

	    // 	$this->session->set_flashdata('message','Tracking Number is not present');
		   //  redirect('gc/dispenser_sale_data/search_return_dispenser');
	    // }

    	

    	
	}
	
	function return_dispenser()
	{
		
		admin_auth();
		$user_id = $this->session->userdata('user_id'); 
		// $product_id=check_injections_filter($this->input->post('product_id')); 
		// $comments=check_injections_filter($this->input->post('comments')); 
		// $company_branch_id=check_injections_filter($this->input->post('company_branch_id')); 
		// $tracking_numbers_id=check_injections_filter($this->input->post('tracking_numbers_id')); 
		// $tracking_number=check_injections_filter($this->input->post('tracking_number'));
		$tracking_details_id=check_injections_filter($this->input->post('dispenser_sales_id'));
		$d_id = explode( ',' ,$tracking_details_id);
		$return_comments=check_injections_filter($this->input->post('return_comments'));

		$condition[] = array('join',TABLE_COMPANY_BRANCH.' as b','b.company_branch_id = d.company_branch_id','inner');
    	$condition[] = array('join',TABLE_USERS.' as u','u.user_id = d.sales_person_id','left');
		$condition[] = array('join',TABLE_CUSTOMER.' as c','c.customer_id = d.customer_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_DETAILS.' as t','t.dispenser_sales_id = d.dispenser_sales_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_NUMBERS.' as tr','tr.tracking_numbers_id = t.tracking_numbers_id','inner');
    	$condition[] = array('join',TABLE_PRODUCT.' as p','p.product_id = d.product_id','inner');
   		
    	$condition[] = array('where','d.sales_type','FTU');
    	//$condition[] = array('where_in','d.dispenser_sales_id',$d_id);
    	$condition[] = array('where_in','t.tracking_details_id',$d_id);
    	// $condition[] = array('where_in','t.is_returned','no');

  	
    	//$condition[] = array('where','p.product_type','dispenser');

        $select_array=array(
                             'table_name'=>TABLE_DISPENSER_SALES.' as d',
                              'table_fields'=>'p.product_id,d.sales_type, p.product_name AS dispenser,c.customer_name,c.customer_id, b.company_branch_name, tr.tracking_number, t.refill_date, t.next_refill_date,u.first_name,u.last_name,tr.tracking_numbers_id,b.company_branch_id,t.is_returned,d.dispenser_sales_id,d.comments,t.dispenser_refill_details_id',
                              'condition'=>$condition,
                              'limit'=>'',
                              'offset'=>'',
                              'order_by_field'=>'t.refill_date',
                              'order'=>'DESC'
                            );

        $return_d_list['return_d_list']=$this->master_model->select_data($select_array);
        //dump($this->db->last_query()); 
		
        foreach ($return_d_list['return_d_list'] as  $value) {
        	$company_branch_id=$value['company_branch_id'];
        	$tracking_numbers_id=$value['tracking_numbers_id'];
        	$dispenser_sales_id=$value['dispenser_sales_id'];
        	$customer_id=$value['customer_id'];
        	$dispenser=$value['dispenser'];
    
        	$dispenser_refill_details_id=$value['dispenser_refill_details_id'];

			$dispenser_quantity=get_data_value(TABLE_DISPENSER_SALES,'dispenser_quantity','dispenser_sales_id',$dispenser_sales_id,'where');
			$dispenser_quantity=intval($dispenser_quantity)-1;
			
			
			$return_data_disp =array(
								'dispenser_quantity' =>$dispenser_quantity
					    );
			$condition_disp=array('dispenser_sales_id'=>$dispenser_sales_id);
			$this->master_model->update_record(TABLE_DISPENSER_SALES,$return_data_disp,$condition_disp);
			
			
        	$return_data =array(
								'possessed_by' =>$company_branch_id,
								'is_status'=>'Company'
					    );
			$condition_track=array('tracking_numbers_id'=>$tracking_numbers_id);
			$this->master_model->update_record(TABLE_TRACKING_NUMBERS,$return_data,$condition_track);
			
			$return_details	    = array(
									'refill_date' =>'0000-00-00',
									'next_refill_date' =>'0000-00-00',
									'is_returned'=>'yes',
									'comments'=>$return_comments,
									'modified_on'=>date("Y-m-d H:i:s"),
									'modified_by'=>$user_id
														
								  );
			$add_return_history = array(
									'tracking_number_id'=>$tracking_numbers_id,
									'customer_id'=>$customer_id,
									'comments'=>$return_comments,
									'dispenser_name'=>$dispenser,
									'dispenser_sales_id'=>$dispenser_sales_id,
									'created_on'=>date("Y-m-d H:i:s"),
									'created_by'=>$user_id
								   );
					
			$condition=array('tracking_numbers_id'=>$tracking_numbers_id);
			$this->master_model->update_record(TABLE_TRACKING_DETAILS,$return_details,$condition);
			$this->master_model->insert_record(TABLE_RETURNED_DISPENSER_HISTORY,$add_return_history);
			//added by shreyas
	        $cond[] = array('where','dispenser_refill_details_id',$dispenser_refill_details_id);
			$select_array = array(
									'table_name'=>TABLE_DISPENSER_REFILL_DETAILS,
									'table_fields'=>'dispenser_refill_details_id,dispenser_sales_id,tracking_numbers,product_id,duration_days,quantity,refill_date,next_refill_date,is_damaged,stop_refill,next_has_been_refilled,refill_location,comments,is_active,old_enduser_refill_transaction_id',
									'condition'=>$cond,
									'sort_by'=>'dispenser_sales_id',
									'order_by_field'=>'',
									'order'=>'ASC',
									'limit'=>'',
									'offset'=>''
									);
			$refill_data=$this->master_model->select_data($select_array);
			
			if (!empty($refill_data)) {
				$dispenser_sales_id1              =$refill_data[0]['dispenser_sales_id'];
				$tracking_numbers                 =$refill_data[0]['tracking_numbers'];
				$product_id                       =$refill_data[0]['product_id'];
				$duration_days                    =$refill_data[0]['duration_days'];
				$quantity                         =$refill_data[0]['quantity'];
				$refill_date                      =$refill_data[0]['refill_date'];
				$next_refill_date         		  =$refill_data[0]['next_refill_date'];
				$is_damaged                       =$refill_data[0]['is_damaged'];
				$stop_refill                      =$refill_data[0]['stop_refill'];
				$next_has_been_refilled           =$refill_data[0]['next_has_been_refilled'];
				$refill_location                  =$refill_data[0]['refill_location'];
				$is_active                        =$refill_data[0]['is_active'];
				$comments                         =$refill_data[0]['comments'];
				$old_enduser_refill_transaction_id=$refill_data[0]['old_enduser_refill_transaction_id'];

				$insert_refill_array=array(

				  'dispenser_sales_id'                =>$dispenser_sales_id1,
				  'tracking_numbers'                  =>$tracking_numbers,
				  'product_id'                        =>$product_id,
				  'duration_days'                     =>$duration_days,
				  'quantity'                          =>$quantity,
				  'refill_date'                       =>$refill_date,
				  'next_refill_date'                  =>$next_refill_date,
				  'is_damaged'            			  =>$is_damaged,
				  'stop_refill'           			  =>'yes',
				  'refill_location'         	      =>$refill_location,
				  'comments'              			  =>$comments,
				  'created_on'            			  => date("Y-m-d H:i:s"),
				  'old_enduser_refill_transaction_id' =>$old_enduser_refill_transaction_id

				);
				$this->master_model->insert_record(TABLE_DISPENSER_REFILL_DETAILS,$insert_refill_array);

				$condition_next_refill=array('dispenser_refill_details_id'=>$dispenser_refill_details_id);
				$next_data=array(
				           'next_has_been_refilled'=>'yes',
				           'modified_on' => date("Y-m-d H:i:s"),
				           'modified_by' =>$user_id
				          );            
				$this->master_model->update_record(TABLE_DISPENSER_REFILL_DETAILS,$next_data,$condition_next_refill);
			}

				
        }
        //added by shreyas
			$this->session->set_flashdata('message','Dispenser returned successfully');
			redirect('gc/dispenser_sale_data/search_return_dispenser');

		
	}
	
	function fetch_salse_person()
	{
		$company_branch_id=$this->input->post('company_branch_id');
       
	    $salse_person_cond = array();
		$salse_person_cond[] = array('where','company_branch_id',$company_branch_id);
		$salse_person_cond[] = array('where','is_active','1');
		$salse_person_cond[] = array('where','user_type_id','2');
		$select_array = array(
								'table_name'=>TABLE_USERS,
								'table_fields'=>'first_name,last_name,user_id',
								'condition'=>$salse_person_cond,
								'sort_by'=>'first_name',
								'order_by_field'=>'first_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$salse_person_data = $this->master_model->select_data($select_array);
		$output='<option value="">Select Sales Person</option>';
		
		foreach($salse_person_data as $row)
		{
		  $output .= '<option value='.$row['user_id'].'>'.$row['first_name'].' '.$row['last_name'].'</option>';

		}
          echo $output;	
    }
  //   function fetch_dispenser(){

		
  //       $check = "dispenser";

		// //$condition = array('where','product_type',$check);
		// $condition[] = array('where','product_type',$check);
		// $condition[] = array('where','is_active',1);

  //   	$selected_array = array( 
		// 	                   'table_name' =>TABLE_PRODUCT,
		// 	                   'table_fields' =>'product_type,product_name,product_id,is_active',
		// 	                   //'order_by_field'=>'Asc',
		// 	                   'condition'=>$condition,
  //                              'limit'=>'',
  //                              'offset'=>''

		// );

		// return $this->master_model->select_data($selected_array);

  //   }
    function fetch_product_category(){

		admin_auth();

		
		
		
		$condition[] = array('join',TABLE_PRODUCT.' as p','p.product_category_id = a.product_category_id','inner');
		$condition[] = array('where_not_in','p.product_type','Refill');
		$condition[] = array('where','a.is_active','1');
    	$selected_array = array( 
			                   'table_name' =>TABLE_PRODUCT_CATEGORY. ' as a',
			                   'table_fields' =>'a.product_category_id,a.product_category_name,a.is_active',
			                   'condition'=>$condition,
							   'sort_by'=>'a.product_category_name',
								'order_by_field'=>'a.product_category_name',
								'order'=>'ASC',
                               'limit'=>'',
                               'group_by_field'=>'a.product_category_id',
                               'offset'=>''

		);

		return $this->master_model->select_data($selected_array);
		//\dump($this->db->last_query());

    }
    function get_dispenser()
	{
		$dispenser_id=$this->input->post('dispenser_id');
		//$access_branch= $this->session->userdata('access_branch');
       
	    $salse_person_cond = array();
		$salse_person_cond[] = array('where','product_category_id',$dispenser_id);
		$salse_person_cond[] = array('where','is_active','1');
		$salse_person_cond[] = array('where_not_in','product_type','Refill');
		$select_array = array(
								'table_name'=>TABLE_PRODUCT,
								'table_fields'=>'product_id,product_name',
								'condition'=>$salse_person_cond,
								'sort_by'=>'product_name',
								'order_by_field'=>'product_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$salse_person_data = $this->master_model->select_data($select_array);
		$output='<option value="default">Select Dispenser Name</option>';
		
		foreach($salse_person_data as $row)
		{
		  $output .= '<option value='.$row['product_id'].'>'.$row['product_name'].'</option>';

		}
          echo $output;	
    }
    
     function fetch_state(){
    

        $country_id=$this->input->post('country_id');


	    $state_cond = array();
		
		$state_cond[] = array('where','country_id',$country_id);
		$state_cond[] = array('where','is_active','1');
		$select_array = array(
								'table_name'=>TABLE_STATE,
								'table_fields'=>'state_name,state_id,country_id,is_active',
								'condition'=>$state_cond,
								'sort_by'=>'state_id',
								'order_by_field'=>'state_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$state_data = $this->master_model->select_data($select_array);
		$output='';
		 foreach($state_data as $row)
                     {
                  		 // $output .= '<option value="'.$row->state_id.'">'.$row->state_name.'</option>';
                  		  $output .= '<option value='.$row['state_id'].'>'.$row['state_name'].'</option>';

                     }

          echo $output;
          // /echo $state_data;


    }
    function customer(){
    	$customer_cond = array();
    	$access_branch= $this->session->userdata('access_branch');
    	if ($access_branch!='') {
    		$customer_cond[] = array('where_in','company_branch_id',$acb);
    	}
		$acb =  explode( ',',$access_branch);
		$customer_cond[] = array('where','is_active','1');
		$select_array = array(
								'table_name'=>TABLE_CUSTOMER,
								'table_fields'=>'customer_name,customer_id',
								'condition'=>$customer_cond,
								'sort_by'=>'customer_id',
								'order_by_field'=>'customer_name',
								'group_by_field'=>'customer_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$customer_data=$this->master_model->select_data($select_array);
		//dump($this->db->last_query());
		$customer_cnt_data=count($customer_data);
		if($customer_cnt_data > 0)
		{
			$output='';
		 		foreach($customer_data as $row)
                     {
                  		 // $output .= '<option value="'.$row->state_id.'">'.$row->state_name.'</option>';
                  		  $output .= '<option value='.$row['customer_id'].'>'.$row['customer_name'].'</option>';

                     }

          echo $output;
		}
    }
    function branch(){

    	$branch_cond = array();
    	$from_branch_id=$this->input->post('from_branch_id');
    	if ($from_branch_id>"0") {
    		$branch_cond[] = array('where_not_in','company_branch_id',$from_branch_id);
    	}
    	$access_branch= $this->session->userdata('access_branch');
    	if ($access_branch!='') {
    		$acb =  explode( ',',$access_branch);
    		$branch_cond[] = array('where_in','company_branch_id',$acb);
    	}		
    	
		$branch_cond[] = array('where','is_active','1');
		$select_array = array(
								'table_name'=>TABLE_COMPANY_BRANCH,
								'table_fields'=>'company_branch_name,company_branch_id',
								'condition'=>$branch_cond,
								'sort_by'=>'company_branch_id',
								'order_by_field'=>'company_branch_name',
								'group_by_field'=>'company_branch_id',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$branch_data=$this->master_model->select_data($select_array);
		//dump($this->db->last_query());
		$branch_cnt_data=count($branch_data);
		if($branch_cnt_data > 0)
		{
			$output='';
			$output .='<option value="default">Select from Branch </option>';
		 		foreach($branch_data as $row)
                     {
                  		 // $output .= '<option value="'.$row->state_id.'">'.$row->state_name.'</option>';
                  		  $output .= '<option value='.$row['company_branch_id'].'>'.$row['company_branch_name'].'</option>';

                     }

          echo $output;
		}
    }
    function branch_all(){
    	$branch_cond = array();
    	$from_branch_id=$this->input->post('from_branch');
    	if ($from_branch_id>"0") {
    		$branch_cond[] = array('where_not_in','company_branch_id',$from_branch_id);
    	}
    	$access_branch= $this->session->userdata('access_branch');
    	if ($access_branch!='') {
    		$acb =  explode( ',',$access_branch);
    		$branch_cond[] = array('where_in','company_branch_id',$acb);
    	}		
    	
		$branch_cond[] = array('where','is_active','1');
		$select_array = array(
								'table_name'=>TABLE_COMPANY_BRANCH,
								'table_fields'=>'company_branch_name,company_branch_id',
								'condition'=>$branch_cond,
								'sort_by'=>'company_branch_id',
								'order_by_field'=>'company_branch_name',
								'group_by_field'=>'company_branch_name',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$branch_data=$this->master_model->select_data($select_array);
		//dump($this->db->last_query());
		$branch_cnt_data=count($branch_data);
		if($branch_cnt_data > 0)
		{
			$output='';
			$output .='<option value="default">Select Transfer To Branch</option>';
		 		foreach($branch_data as $row)
                     {
                  		 // $output .= '<option value="'.$row->state_id.'">'.$row->state_name.'</option>';
                  		  $output .= '<option value='.$row['company_branch_id'].'>'.$row['company_branch_name'].'</option>';

                     }

          echo $output;
		}
    }

    function transfer_dispenser(){
    	admin_auth();

    	$this->_page_data['lable_branch_from']=$this->lang->line('lable_branch_from', FALSE);
    	//$lable_dispenser_sale_data=$this->lang->line('lable_dispenser_sale_data', FALSE);
    	$this->_page_data['page_title']="Transfer Dispenser";
    	
		$this->_page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										'Transfer Dispenser'=>'#',
										);
    	$this->page_data['lable_branch_from']=$this->lang->line('lable_branch_from', FALSE);
 		
       
    	$this->load->view('gc/transfer_dispenser_manage.php',$this->_page_data);
    }

    function fetch_dispenser_track($query_id = 0, $sort_by = 'dispenser_sales_id', $sort_order = 'asc', $offset = 0,$sort_type=0){
        admin_auth();
		$limit = LIMIT_PER_PAGE;
    	$this->page_data['lable_branch_To']=$this->lang->line('lable_branch_To', FALSE);
 		$this->page_data['lable_transfer_comments']=$this->lang->line('lable_transfer_comments', FALSE);
 		$this->_page_data['page_title']="Transfer Dispenser";
		$this->page_data['bredcrum']=array(
										'Dispenser Sales'=>'#',
										'Transfer Dispenser'=>'#',
										'List of Dispensers'=>'#',
										);
    	
		$this->load->library('NF_Query_search');
		$this->nf_query_search->load_query($query_id);

		$query_array = array(
 				'from_branch'=>$this->input->get('from_branch'),
 				'tracking_number'=>$this->input->get('tracking_number')
 				
 				
		);

		$from_branch=check_injections_filter($query_array['from_branch']);
		$tracking_number=check_injections_filter($query_array['tracking_number']);
		
		if ($from_branch!='') {
			$get_company_name=get_data_value(TABLE_COMPANY_BRANCH,'company_branch_name','company_branch_id',$from_branch,'where');
			$this->page_data['get_company_name']=$get_company_name;
			$this->page_data['get_company_id']=$from_branch;
		}
		//$from_branch_id=$this->input->post('from_branch');
		$this->page_data['fields'] = array(
							// 'customer_name' => 'Customer Name',
							'tracking_number' => 'Tracking Number',
							'dispenser' => 'Dispenser Name',
							'company_branch_name' => 'Branch Name',
							
							// 'sales_type' => 'Sale Type',							
							// 'first_name' => 'Sale Person Name',
							// 'refill_date' => 'Refill Date',
							// 'next_refill_date' => 'Next Refill Date',
							
						);

    	
    	$condition[] = array('join',TABLE_USERS.' as u','u.user_id = d.sales_person_id','left');
		$condition[] = array('join',TABLE_CUSTOMER.' as c','c.customer_id = d.customer_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_DETAILS.' as t','t.dispenser_sales_id = d.dispenser_sales_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_NUMBERS.' as tr','tr.tracking_numbers_id = t.tracking_numbers_id','inner');
    	$condition[] = array('join',TABLE_COMPANY_BRANCH.' as b','b.company_branch_id = tr.possessed_by','inner');
    	$condition[] = array('join',TABLE_PRODUCT.' as p','p.product_id = d.product_id','inner');
		$condition[] = array('where_not_in','tr.is_status','Customer');
  		$condition[] = array('where','tr.possessed_by',$from_branch);
    	$condition[] = array('where','d.sales_type','FTU');
    	if ($tracking_number!='') {
			$condition[] = array('like','tr.tracking_number',$tracking_number);	
		}

  		$sort_columns = array('company_branch_name','tracking_number','product_name');
    	$search_array=array(
							'limit' => $limit,
							'offset' => $offset,
							'sort_by' => $sort_by,
							'sort_type' => $sort_type,
							'sort_order' => $sort_order,
							'sort_columns'=> $sort_columns,
							'table_fields'=>'p.product_id,d.sales_type, p.product_name AS dispenser, c.customer_name, b.company_branch_name, tr.tracking_number, t.refill_date, t.next_refill_date,u.first_name,u.last_name,tr.tracking_numbers_id,b.company_branch_id,t.is_returned,d.dispenser_sales_id',
							'order_by_field'=>'tr.tracking_number',
							'group_by_field'=>'tr.tracking_number',
							'table_name'=>TABLE_DISPENSER_SALES.' as d',
							'cond'=> $condition,
							);
		
			$results = $this->master_model->search($search_array);


			$search_full_array=array(
							'limit' => '',
							'offset' =>'',
							'sort_by' => $sort_by,
							'sort_type' => $sort_type,
							'sort_order' => $sort_order,
							'sort_columns'=> $sort_columns,
							'table_fields'=>'p.product_id,d.sales_type, p.product_name AS dispenser, c.customer_name, b.company_branch_name, tr.tracking_number, t.refill_date, t.next_refill_date,u.first_name,u.last_name,tr.tracking_numbers_id,b.company_branch_id,t.is_returned,d.dispenser_sales_id',
							'order_by_field'=>'tr.tracking_number',
							'group_by_field'=>'tr.tracking_number',
							'table_name'=>TABLE_DISPENSER_SALES.' as d',
							'condition'=> $condition,
							);
			$returned=$this->master_model->select_data($search_full_array);	
			//dump($this->db->last_query());	
		    $cnt_all_rows=count($returned);

		    if(!empty($results)&& is_array($results))
			{
				$this->page_data['return'] = $results['rows'];
				$this->page_data['num_results'] = $cnt_all_rows;
			}
			else
			{
				$results='';
			}
			$this->page_data['offset'] = $offset;
			/// pagination
			$this->load->library('pagination');
			$config = array();
			$config['base_url'] = site_url("gc/dispenser_sale_data/fetch_dispenser_track/$query_id/$sort_by/$sort_order");
			$config['total_rows'] = $this->page_data['num_results'];
			$config['per_page'] = $limit;
			$config['uri_segment'] = 7;
			$config['full_tag_open'] = '<span class=\'paging\'>';
			$config['full_tag_close'] = '</span>';
			$config['first_link'] = 'First';
			$config['prev_link'] = '<<';
			$config['next_link'] = '>>';
			$config['last_link'] = 'Last';
			$this->pagination->initialize($config);
			
			$this->page_data['pagination'] = $this->pagination->create_links();
			$this->page_data['sort_by'] = $sort_by;
			$this->page_data['sort_order'] = $sort_order;
			$this->page_data['sort_type'] = $sort_type;
			//$data['purpose'] = $purpose;
			$this->page_data['query_id'] = $query_id;

		   $this->load->view('gc/transfer_dispenser_list',$this->page_data);

       
    }
    function search_transfer_list()
	{
		$query_array = array(
						'from_branch' =>check_injections_filter($this->input->post('from_branch')),
						'tracking_number' =>check_injections_filter($this->input->post('tracking_number')),
						
					
					   );
		$this->load->library('NF_Query_search');
		$query_id = $this->nf_query_search->save_query($query_array);			
		
		redirect('gc/dispenser_sale_data/fetch_dispenser_track/'.$query_id);		
	}
	
    function transfer_to_branch(){
    	
    	$from_branch_hidden=check_injections_filter($this->input->post('from_branch_hidden'));
    	$to_branch_name=check_injections_filter($this->input->post('to_branch_name'));
    	$tranfer_comments=check_injections_filter($this->input->post('tranfer_comments'));
    	//$transer_comments=check_injections_filter($this->input->post('transer_comments'));
    	$dispenser_sales_id=check_injections_filter($this->input->post('hidden_transfer'));
		$d_id = explode( ',' ,$dispenser_sales_id);
		$user_id = $this->session->userdata('user_id');

	
		// echo $from_branch;

		// echo $dispenser_sales_id;
    	
    	$condition[] = array('join',TABLE_COMPANY_BRANCH.' as b','b.company_branch_id = d.company_branch_id','inner');
    	$condition[] = array('join',TABLE_USERS.' as u','u.user_id = d.sales_person_id','left');
		$condition[] = array('join',TABLE_CUSTOMER.' as c','c.customer_id = d.customer_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_DETAILS.' as t','t.dispenser_sales_id = d.dispenser_sales_id','inner');
    	$condition[] = array('join',TABLE_TRACKING_NUMBERS.' as tr','tr.tracking_numbers_id = t.tracking_numbers_id','inner');
    	$condition[] = array('join',TABLE_PRODUCT.' as p','p.product_id = d.product_id','inner');
   		
    	$condition[] = array('where','d.sales_type','FTU');
    	$condition[] = array('where_in','tr.tracking_numbers_id',$d_id);
    	
        $select_array=array(
                             'table_name'=>TABLE_DISPENSER_SALES.' as d',
                              'table_fields'=>'p.product_id,d.sales_type, p.product_name AS dispenser, c.customer_name, b.company_branch_name, tr.tracking_number, t.refill_date, t.next_refill_date,u.first_name,u.last_name,tr.tracking_numbers_id,b.company_branch_id,t.is_returned,d.dispenser_sales_id',
                              'condition'=>$condition,
                              'limit'=>'',
                              'offset'=>'',
                              'order_by_field'=>'t.refill_date',
                              'order'=>'DESC'
                            );

        $return_d_list['return_d_list']=$this->master_model->select_data($select_array);
      
        foreach ($return_d_list['return_d_list'] as  $value) {
        	$tracking_numbers_id=$value['tracking_numbers_id'];
        

        	$return_data =array(
								//'tracking_number' =>$tracking_number,
								//'product_id' =>$product_id,
								'possessed_by' =>$to_branch_name,
								'is_status'=>'Company'
										
					    );
        	$condition_track=array('tracking_numbers_id'=>$tracking_numbers_id);
			$this->master_model->update_record(TABLE_TRACKING_NUMBERS,$return_data,$condition_track);
			$tracking_number=get_data_value(TABLE_TRACKING_NUMBERS,'tracking_number','tracking_numbers_id',$tracking_numbers_id,'where');
			$tranfer_history_data=array(
								'tracking_number_id'=>$tracking_numbers_id,
								'tracking_number' => $tracking_number,
								'from_branch' =>$from_branch_hidden,
								'to_branch'=>$to_branch_name,
								'comments'=>$tranfer_comments,
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								
					    );
		    $this->master_model->insert_record(TABLE_TRANSFER_DISPENSER_HISTORY,$tranfer_history_data);
			
			}
			
			$this->session->set_flashdata('message','Dispenser transfer successfully');
			redirect("gc/dispenser_sale_data/transfer_dispenser");
        }
}
