<?php	if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Products extends CI_Controller {

	function __construct()	{
		parent::__construct();
		$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_products();
	}

	function list_products($query_id = 0, $sort_by = 'product_id', $sort_order = 'asc', $offset = 0,$sort_type='') {
		//error_reporting(E_ALL);
		admin_auth();
		$submit=check_injections_filter($this->input->post('search')); 
		$limit = LIMIT_PER_PAGE;
		
		//$p_id = $this->encrypt->decode($pro_id);

		$this->page_data['branch'] = $this->fetch_branch_name();
		$this->page_data['page_title']="List of Products";
		$this->page_data['bredcrum']=array(
										'Masters'=>'#',
										'Products'=>site_url('gc/Product_category/list_product_category'),
										'List of Products'=>'#',
										);

		
                           $condition = array();


                            //$condition[] = array('where',TABLE_COMPANY.'.company_id',$company_id);
                            $condition[] = array('join',TABLE_PRODUCT_CATEGORY,TABLE_PRODUCT.'.product_category_id='.TABLE_PRODUCT_CATEGORY.'.product_category_id','left');

                            // if ($p_id=='1') {
                            // 		$condition[] = array('where',TABLE_PRODUCT.'.product_type','Dispenser');
                            // }else if($p_id=='2'){
                            // 		$condition[] = array('where',TABLE_PRODUCT.'.product_type','Refill');
                            // }
            $this->page_data['product_name']='';
            $this->page_data['product_category_name']='';          
  //   if(isset($submit) && !empty($submit))
		// {
			
			$this->load->library('NF_Query_search');
			//echo $query_id;
		    $this->nf_query_search->load_query($query_id);

		    $query_array = array(
							'product_name' =>  $this->input->get('product_name'),
							'product_category_type' => $this->input->get('product_category_type'),
							'product_type' => $this->input->get('product_type'),
							);
		   // print_r($query_array );

		    $product_name=check_injections_filter($query_array['product_name']);
			$product_category_type=check_injections_filter($query_array['product_category_type']);
			$product_type=check_injections_filter($query_array['product_type']);

		 // $product_name=check_injections_filter($this->input->post('product_name'));
   //       $product_category_name=check_injections_filter($this->input->post('product_category_name'));

        if ($product_name!='') {
        	$condition[]=array('like',TABLE_PRODUCT.'.product_name',$product_name);
        	$this->page_data['product_name']=$product_name;
        }else{
        	$this->page_data['product_name']='';
        }
       
        if ($product_category_type>0) {
        	$condition[]=array('where',TABLE_PRODUCT.'.product_category_id',$product_category_type);
        	$this->page_data['product_category_type']=$product_category_type;
        }else{
        	$this->page_data['product_category_type']=$product_category_type;
        }
        if ($product_type!='default') {
        	if ($product_type=='1') {
        		$condition[]=array('where',TABLE_PRODUCT.'.product_type','Dispenser');
        		$this->page_data['product_type']=$product_type;
        	}else if($product_type=='2'){
        	    $condition[]=array('where',TABLE_PRODUCT.'.product_type','Refill');
        		$this->page_data['product_type']=$product_type;
        	}else if($product_type=='3'){
        	    $condition[]=array('where',TABLE_PRODUCT.'.product_type','Dispenser-FTU');
        		$this->page_data['product_type']=$product_type;
        	}else{
        		$this->page_data['product_type']='';
        	}
        	
        }else{
        	$this->page_data['product_type']='';
        
        }
           
	//}


        				$this->page_data['fields'] = array(
							'product_type' => 'Product Type',
							'product_category_id' => 'Product Category',
							'product_name' => 'Product Name',
							'stock_quantity' => 'Quantity in Hand',
							'price' => 'Price',
							
							
						);

                         $sort_columns = array(TABLE_PRODUCT.'.product_type',TABLE_PRODUCT.'.product_name',TABLE_PRODUCT.'.product_category_id',TABLE_PRODUCT.'.stock_quantity',TABLE_PRODUCT.'.price');

                            $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'=>TABLE_PRODUCT.'.is_active,product_id,product_name,product_type,product_prefix,product_name,description,price,stock_quantity,product_category_name,refill_duration',
							'table_name'=>TABLE_PRODUCT,
							'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'=>TABLE_PRODUCT.'.is_active,product_id,product_name,product_type,product_prefix,product_name,description,price,stock_quantity,product_category_name,refill_duration',
							'table_name'=>TABLE_PRODUCT,
							'condition'=> $condition,
							);
            $search_data=$this->master_model->select_data($search_full_array);	
           //dump($this->db->last_query());
		    $cnt_all_rows=count($search_data);
			
			if(!empty($results)&& is_array($results))
			{
				$this->page_data['product'] = $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/products/list_products/$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/products_list.php',$this->page_data);
	}
	
	function search_product()
	{
		$query_array = array(
						'product_name' =>check_injections_filter($this->input->post('product_name')),
						'product_category_type' =>check_injections_filter($this->input->post('product_category_type')),

						'product_type' => check_injections_filter($this->input->post('product_type')),
						
						
					);
		$this->load->library('NF_Query_search');
		$query_id = $this->nf_query_search->save_query($query_array);			
		
		redirect('gc/products/list_products/'.$query_id);		
	}
	function view_products($product_id="",$product_type='') {
		admin_auth();
		$id=$this->encrypt->decode($product_id);
		$this->_page_data['page_title']="View Product ";
		$this->_page_data['bredcrum']=array(
										'Masters'=>'#',
										'Products '=>site_url('gc/products/list_product'),
										'List of Products'=>site_url('gc/products/list_product'),
										'View Product '=>'#',
										);
		$condition[] = array('where','product_id',$id);
						//if ($product_type=='dispenser') {
		$condition[] = array('join',TABLE_PRODUCT_CATEGORY,TABLE_PRODUCT.'.product_category_id='.TABLE_PRODUCT_CATEGORY.'.product_category_id','left');
        $selected_array=array(
                                'table_name' => TABLE_PRODUCT,
                                'table_fields' => TABLE_PRODUCT.'.is_active,product_id,product_name,product_type,product_prefix,product_name,description,price,stock_quantity,refill_ids,'.TABLE_PRODUCT_CATEGORY.'.product_category_name,product_prefix,refill_duration',
                                'condition'=>$condition,
                                'limit'=>'',
                                'offset'=>''
                            );

						// } else if($product_type=='refill'){
						// 		$selected_array=array(
      //                           				'table_name'=>TABLE_PRODUCT,
      //                          					'table_fields'=>TABLE_PRODUCT.'.is_active,product_id,product_name,product_type,product_prefix,product_name,description,price,stock_quantity,product_prefix,refill_duration',
      //                          				   // 'condition'=>$condition,
      //                          				    'limit'=>'',
      //                                           'offset'=>''
      //                       );
						// }							
 						
                           // $condition[] = array('where','users.is_active');


		$product['product'] = $this->master_model->select_data($selected_array);
		// echo "<pre>";
		// print_r($product);
		// dump($this->db->last_query());
		if(!empty($product['product'] )&& is_array($product['product']))
			{				
				 $this->_page_data['product'] = $product['product'] ;			 		 
  	        }
		$this->load->view('gc/products_view.php',$this->_page_data);
	}
	
	function manage_products($product_id="") {
		admin_auth();
		
	    $this->_page_data['p_Product_Type']= $this->lang->line('p_Product_Type', FALSE);
		$this->_page_data['p_Dispenser']=$this->lang->line('p_Dispenser', FALSE);
		$this->_page_data['p_Refill']=$this->lang->line('p_Refill', FALSE);
		$this->_page_data['p_Product_Category']= $this->lang->line('p_Product_Category', FALSE);
		$this->_page_data['p_Product_Prefix']= $this->lang->line('p_Product_Prefix', FALSE);
		$this->_page_data['p_Stock_Quantity']= $this->lang->line('p_Stock_Quantity', FALSE);
		$this->_page_data['p_Dispenser_Name']= $this->lang->line('p_Dispenser_Name', FALSE);
		$this->_page_data['p_Refill_Duration']= $this->lang->line('p_Refill_Duration', FALSE);
		$this->_page_data['p_Price']= $this->lang->line('p_Price', FALSE);
		$this->_page_data['p_Refill_Name']= $this->lang->line('p_Refill_Name', FALSE);

		$id=$this->encrypt->decode($product_id);
		$this->_page_data['category'] = $this->fetch_cateogory();
		$this->_page_data['dispenser'] = $this->fetch_dispenser();
		if ($id) {
			$this->_page_data['page_title']="Edit Product ";
			$this->_page_data['bredcrum']=array(
										'Masters'=>'#',
										'List Products'=>site_url('gc/products/list_products'),
										'Edit  Product'=>'#',
										);
		}else{
			$this->_page_data['page_title']="Add Product ";
			  $this->_page_data['bredcrum']=array(
										'Masters'=>'#',
										'Products'=>'#',
										'Add  Product'=>'#',
										);
		}
		
		if (!$id) {
            
	       $this->load->view('gc/products_manage.php',$this->_page_data);

		}else{
		
                     
				 $condition = array();
				//$condition[] = array('where',TABLE_COMPANY.'.company_id',$company_id);
				 $condition[] = array('join',TABLE_PRODUCT.' as pd','p.dispenser_name = pd.product_id','left');
				 $condition[] = array('join',TABLE_PRODUCT_CATEGORY.' as pc','p.product_category_id =pc.product_category_id','left');

			     $condition[] = array('where','p.product_id',$id);

				 $selected_array=array(
					'table_name'=>TABLE_PRODUCT.' as p',
					'table_fields'=>'p.is_active,p.product_id,p.product_name,p.product_type,p.product_prefix,pd.product_name as dispenser,p.description,p.price,p.stock_quantity,pc.product_category_name,p.product_prefix,p.refill_duration,pc.product_category_id,pd.product_id as dispenser_id,p.refill_ids',
					'condition'=>$condition,
					'limit'=>'',
					'offset'=>''
				);
		        $product['product'] = $this->master_model->select_data($selected_array);
		//dump($this->db->last_query());
		       if(!empty($product['product'] )&& is_array($product['product']))
			   {
				 $this->_page_data['product'] = $product['product'] ; 
  	           }
		  	   $this->load->view('gc/products_manage.php',$this->_page_data); 
		
		}
	}
	function fetch_cateogory(){
		admin_auth();
		
		$condition[] = array('join',TABLE_PRODUCT.' as p','p.product_category_id = a.product_category_id','inner');
		$condition[] = array('where','a.is_active','1');
		$condition[] = array('where_not_in','p.product_type','Refill');
		    	$selected_array = array( 
			                   'table_name' => TABLE_PRODUCT_CATEGORY. ' as a',
			                   'table_fields' => 'a.product_category_id,a.product_category_name,a.parent_category_id',
			                   'condition'=>$condition,
			                   'order_by_field'=>'a.product_category_name',
			                   'group_by_field'=>'a.product_category_name',
			                   'order'=>'ASC',
			                   'limit'=>'',
                               'offset'=>''
		);

		return $this->master_model->select_data($selected_array);		         
    }
    function add_products(){
    	admin_auth();	
    	$id = check_injections_filter($this->input->post('hidden'));
    	$product_type=$this->input->post('form-field-radio');

    	if ($product_type =='Dispenser' || $product_type =='Dispenser-FTU') {
    		//$product_type=$this->input->post('form-field-radio');
    		$product_category =$this->input->post('product_category'); 
    		$product_name =check_injections_filter($this->input->post('product_name_dispenser'));
    		$product_prefix = check_injections_filter($this->input->post('product_prefix'));
    		$s_product_prefix=strtolower($product_prefix);
    		$description = check_injections_filter($this->input->post('description'));
    		$stock_quantity =check_injections_filter($this->input->post('stock_quantity'));
    		$price= check_injections_filter($this->input->post('price')); 
    		$refill_duration= check_injections_filter($this->input->post('refill_duration'));
           $product_dispenser ='';
    		// echo $product_type."<br>";
    		// echo "product Category"." ".$product_category."<br>";
    		// echo "product_name"." ".$product_name."<br>";
    		// echo "product_prefix"." ".$product_prefix."<br>";
    		// echo "description"." ".$description."<br>";
    		// echo "stock_quantity"." ".$stock_quantity."<br>";
    		// echo "price"." ".$price."<br>";
    		// echo "refill_duration"." ".$refill_duration."<br>";
    		// exit;
    		
   

    	$this->form_validation->set_rules('product_name_dispenser', 'Dispenser Name','required'); 
    	$this->form_validation->set_rules('product_prefix', 'Product Prefix','required');
    	$this->form_validation->set_rules('refill_duration', 'Refill Duration','required');
    	$this->form_validation->set_rules('description', 'Description','required');
    	$this->form_validation->set_rules('stock_quantity', 'Stock Quantity','required');

    	}else{
    			$stock_quantity='';
    		//$product_type=$this->input->post('form-field-radio');
			$product_dispenser1 =$this->input->post('product_dispenser');
			$product_dispenser = implode(',', $product_dispenser1);
			$product_name =check_injections_filter($this->input->post('product_name_refill'));
			$description_refill = check_injections_filter($this->input->post('description_refill'));
			$stock_quantity_refill =check_injections_filter($this->input->post('stock_quantity_refill')); 
		
		    $price_refill= check_injections_filter($this->input->post('price_refill')); 

		    	
		    // print_r($product_dispenser)."<br>";
		    // echo $product_name."<br>";
		    // echo $description_refill."<br>";
		    // echo $price_refill."<br>";
		    // exit;


		$this->form_validation->set_rules('product_dispenser', 'Dispenser Name','required'); 
    	$this->form_validation->set_rules('product_name_refill', 'Refill Name','required');
    	$this->form_validation->set_rules('description_refill', 'Description','required');
    	$this->form_validation->set_rules('stock_quantity_refill', 'Stock Quantity','required'); 
    	}  	
		   	 $user_id=$this->session->userdata('user_id');

    	    if ($id) {
    	    	if ($product_type =='Dispenser' || $product_type =='Dispenser-FTU') {
    	     	$condition[] = array('where','product_name',$product_name);
    	      	$condition[] = array('where','product_category_id',$product_category);
    	      	$condition[] = array('where','LOWER(product_prefix)',$s_product_prefix);
    	 		}else{
    	 	 	$condition[] = array('where','product_name',$product_name);
    	 		}
    	    	$condition[] = array('where_not_in','product_id',$id);
            }else{
            	if ($product_type =='Dispenser' || $product_type =='Dispenser-FTU') {   	     	
    	      	$condition[] = array('where','LOWER(product_prefix)',$s_product_prefix);
    	      	$condition[] = array('where','product_category_id',$product_category);
    	      	$condition[] = array('or_where','product_name',$product_name);
    	 		}else{
    	 	 	$condition[] = array('where','product_name',$product_name);
    	 		}
            }
    			$selected_array=array(
								'table_name' =>TABLE_PRODUCT,								
								'table_fields'=>'product_name',
								'condition'=>$condition,
								'limit'=>'',
                                'offset'=>''						
					    );
    			$product['product'] = $this->master_model->select_data($selected_array);
    		// 	dump($this->db->last_query());
						// exit;
    			if(!empty($product['product']))
				{			
					 $this->session->set_flashdata('message','Product  already present');
				     redirect('gc/products/manage_products');
				}else {
                    if(!$id){
                     	if ($product_type=='Dispenser' || $product_type =='Dispenser-FTU') {

              	   			$product_data=array(
								'product_type' => $product_type,
								'product_category_id' => $product_category,
								'product_name' => $product_name,
								'product_prefix' => $product_prefix,
								'refill_duration' => $refill_duration ,
								'description' => $description,
								'stock_quantity' => $stock_quantity,
								'price' => $price,
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>'',	
								'modified_on' => date("Y-m-d H:i:s")								
					        );
              			}else{
							
							

              				$product_data=array(
								'product_type' => $product_type,
								'product_name' => $product_name,						
								'dispenser_name'=>$product_dispenser,
								'description' => $description_refill,
								'stock_quantity' => $stock_quantity_refill,
								'price' =>  $price_refill,
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>'',	
								'modified_on' => date("Y-m-d H:i:s")	
					    	);
             			}
             			$this->session->set_flashdata('message','Product  inserted successfully');
				 		$this->master_model->insert_record(TABLE_PRODUCT,$product_data);
						$product_id = $this->db->insert_id();
						if($stock_quantity>0)
						 {
							 $i=1;
							 for($i; $i <= $stock_quantity; $i++) 
							{
								if($i<=9){
									$tracking_no =$product_prefix.'-00000'.$i;
								}else if($i>9 && $i<=99){
									$tracking_no =$product_prefix.'-0000'.$i;
								}else if($i>99 && $i<=999){
									$tracking_no =$product_prefix.'-000'.$i;
								}else if($i>999 && $i<=9999){
									$tracking_no =$product_prefix.'-00'.$i;
								}else if($i>9999 && $i<=99999){
									$tracking_no =$product_prefix.'-0'.$i;
								}else if($i>99999){
									$tracking_no =$product_prefix.'-'.$i;
								}	
								$tracking_data=array(
											'tracking_number' => $tracking_no,							
											'product_id' => $product_id								
									);
								$this->master_model->insert_record(TABLE_TRACKING_NUMBERS,$tracking_data);
							}
						 }
						$dispenser_ids=explode(',', $product_dispenser);
						 for ($i=0; $i <sizeof($dispenser_ids) ; $i++) { 
						 	# code...						 
						 $refill_ids=get_data_value(TABLE_PRODUCT,'refill_ids','product_id',$dispenser_ids[$i],'where');
						 $refill_ids=$refill_ids.",".$product_id;
						 $product_update_data=array(
								'refill_ids' => $refill_ids
					        );                        
						 $condition_prod=array('product_id'=>$dispenser_ids[$i]);
						 $this->master_model->update_record(TABLE_PRODUCT,$product_update_data,$condition_prod);
						 }
												
    	         		redirect('gc/products/list_products');

                    }else{
                     	if ($product_type=='Dispenser' || $product_type =='Dispenser-FTU') {

              	   			$product_data=array(
								'product_type' => $product_type,
								'product_category_id' => $product_category,
								'product_name' => $product_name,
								'product_prefix' => $product_prefix,
								'refill_duration' => $refill_duration,
								'description' => $description,
								'price' => $price,
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>$user_id,	
								'modified_on' => date("Y-m-d H:i:s")
					        );
                        }else{

              				$product_data=array(
								'product_type' => $product_type,
								'product_name' => $product_name,						
								'description' => $description_refill,
								'dispenser_name'=>$product_dispenser,
								'price' =>  $price_refill,
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>$user_id,	
								'modified_on' => date("Y-m-d H:i:s")
					        );
                        }
                        $this->session->set_flashdata('message',' Product updated  successfully');
						$condition=array('product_id'=>$id);
						$this->master_model->update_record(TABLE_PRODUCT,$product_data,$condition);

						 // $pre_ids=get_data_value(TABLE_PRODUCT,'product_id','product_id',$product_dispenser,'where');
						 $dispenser_product_id=get_data_value(TABLE_PRODUCT,'product_id','product_id',$id,'where');
						 // /echo $dispenser_product_id."<br>";
						
						 $product_dispenser_ids=get_data_value(TABLE_PRODUCT,'dispenser_name','product_id',$id,'where');
						 //echo $product_dispenser_ids."<br>";
						 $product_dispenser_id_single=explode(',',$product_dispenser_ids);
						 for ($k=0; $k < sizeof($product_dispenser_id_single) ; $k++) { 
						      //echo $product_dispenser_id_single[$k]."<br>";
						      $product_refill_ids=get_data_value(TABLE_PRODUCT,'refill_ids','product_id',$product_dispenser_id_single[$k],'where');
						      $product_refill_ids1=explode(',', $product_refill_ids);
						     // / print_r($product_refill_ids1);
						      if (!in_array($id,$product_refill_ids1)) {
						      	$product_refill_ids=get_data_value(TABLE_PRODUCT,'refill_ids','product_id',$product_dispenser_id_single[$k],'where');
						      	$refill_ids=$product_refill_ids.",".$id;
						      	$product_update_data_dispenser=array(
									'refill_ids' => $refill_ids
					        	); 
					        	$condition_prod_disp=array('product_id'=>$product_dispenser_id_single[$k]);
								$this->master_model->update_record(TABLE_PRODUCT,$product_update_data_dispenser,$condition_prod_disp);
						      }
						 }
						
						 //$n= strlen($product_refill_ids)-1;
						 // if ($n!=',' || $product_refill_ids[0]!=',') {

						 // 	$d_ids=$dispenser_product_id;
						 // }else{
						 	 
							
						 // }
						
						
						
						
						 
						
			     		redirect('gc/products/list_products');
                     }
						
    	        	}
			   //}
    }
    function disable_products($product_id=""){
		admin_auth();
		$id=$this->encrypt->decode($product_id);
		 $user_id=$this->session->userdata('user_id');
     $product_data=array(
								'is_active' =>'0',								
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>$user_id,	
								'modified_on' => date("Y-m-d H:i:s")								
					    );
     	$condition=array('product_id'=>$id);
     	$this->session->set_flashdata('message',' product is disable');
		$this->master_model->update_record(TABLE_PRODUCT,$product_data,$condition);
		redirect('gc/products/list_products');
    }
      function enable_products($product_id=""){
      	admin_auth();
      	$id=$this->encrypt->decode($product_id);
      	$user_id=$this->session->userdata('user_id');
      $product_data=array(
								'is_active' =>'1',								
								'created_on' => date("Y-m-d H:i:s"),
								'created_by' =>$user_id,
								'modified_by' =>$user_id,	
								'modified_on' => date("Y-m-d H:i:s")								
					    );
     	$condition=array('product_id'=>$id);
     	$this->session->set_flashdata('message','product is enable');
		$this->master_model->update_record(TABLE_PRODUCT,$product_data,$condition);
		redirect('gc/products/list_products');
    }
    function fetch_dispenser(){

		admin_auth();
        $check = "Dispenser";

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

    	$selected_array = array( 
			                   'table_name' =>TABLE_PRODUCT,
			                   'table_fields' =>'product_type,product_name as dispenser,product_id,is_active,refill_ids',
			                   'order_by_field'=>'product_name',
			                   'group_by_field'=>'product_name',
			                   'order'=>'ASC',
			                   'condition'=>$condition,
                               'limit'=>'',
                               'offset'=>''

		);
	
		return $this->master_model->select_data($selected_array);
		
    }
    
    function fetch_cateogory_types(){

		admin_auth();
       
		$cateogory_type = $this->input->post('cateogory_type'); 
		$product_category_type = $this->input->post('product_category_type'); 
		if ($cateogory_type=='1') {
			$condition[] = array('where','category_type','Dispenser');
		}else if($cateogory_type=='2'){
			$condition[] = array('where','category_type','Refil');
		}else if($cateogory_type=='3'){
			$condition[] = array('where','category_type','Dispenser');
		}else{
			$condition[] = array('where','category_type','');
		}
		//$condition = array('where','product_type',$check);
		
		// /$condition[] = array('or_where','product_type','Dispenser-FTU');
		$condition[] = array('where','is_active','1');

    	$selected_array = array( 
			                   'table_name' =>TABLE_PRODUCT_CATEGORY,
			                   'table_fields' =>'product_category_id,product_category_name,is_active,category_type',
			                   'order_by_field'=>'product_category_name',
			                   'group_by_field'=>'product_category_name',
			                   'order'=>'ASC',
			                   'condition'=>$condition,
                               'limit'=>'',
                               'offset'=>''

		);
	
		$category_data['category_data'] = $this->master_model->select_data($selected_array);
		//dump($this->db->last_query());
		$output='<option value="default">Select Product Category</option>';
		foreach($category_data['category_data'] as $row)
		{
        
         	$selected='';

             if ($row['product_category_id']==$product_category_type) 

			 {

				$selected='selected="selected"';

			 }
		 		 $output .= '<option value='.$row['product_category_id'].' '.$selected.'>'.$row['product_category_name'].'</option>';
		 

		}

          echo $output;	
		
    }
    function fetch_branch_name(){
     	admin_auth();
     	$condition[] = array('where','is_active','1');
    	$selected_array = array( 
			                   'table_name' =>TABLE_COMPANY_BRANCH,
			                   'table_fields' => 'company_branch_id,company_branch_name,is_active',
			                   'order_by_field'=>'company_branch_name',
			                   'condition'=>$condition,
			                   'group_by_field'=>'company_branch_name',
			                   'order'=>'ASC',
			                   'limit'=>'',
			                   'offset'=>''

		);

		return $this->master_model->select_data($selected_array);	
		
    }
  
    function quantity(){
    //error_reporting(E_ALL);	
  	$update_id_quanity = check_injections_filter($this->input->post('update_id_quanity'));
  	$id=$this->encrypt->decode($update_id_quanity);
  	$update_quantity = check_injections_filter($this->input->post('update_quantity'));
  	$start_number = check_injections_filter($this->input->post('start_number'));
  	$branch = check_injections_filter($this->input->post('branch'));
  		$stock_add_quanity = check_injections_filter($this->input->post('stock_add_quanity'));
  	$total_quantity=$stock_add_quanity+$update_quantity;
    // echo $update_quantity."<br>";
    // echo $start_number."<br>";
    // echo $company_branch_name."<br>";
    // $count_start_number=count($start_number);
  	//}

  	$condition[] = array('where','is_active','1');
    $condition[] = array('where','product_id',$id);
    $selected_array = array( 
			                   'table_name' =>TABLE_PRODUCT,
			                   'table_fields' =>'product_id,product_prefix',
			                   'order_by_field'=>'product_name',
			                   'group_by_field'=>'product_name',
			                   'order'=>'ASC',
			                   'condition'=>$condition,
                               'limit'=>'',
                               'offset'=>''

	);
	$result['result']=$this->master_model->select_data($selected_array);
	foreach ($result['result'] as  $value) {
		$product_prefix=$value['product_prefix'];
	}

	if($product_prefix=='')
		{
			$this->session->set_flashdata('message','product prefix is not available');
			redirect('gc/products/list_products');
  	    }

  	else{
  		$cond=array();
					    $cond[] = array('join',TABLE_PRODUCT.' as p','p.product_id = t.product_id');
  	    			    $cond[] = array('where','t.product_id',$id);

  	    			    $selected_array = array( 
			                   'table_name' =>TABLE_TRACKING_NUMBERS.' as t',
			                   'table_fields' =>'t.tracking_numbers_id,t.tracking_number,t.possessed_by,t.product_id,t.is_status,p.product_prefix',
			                   'order_by_field'=>'t.tracking_number',
			                   'order'=>'DESC',
			                   'condition'=>$cond,
                               'limit'=>'1',
                               'offset'=>''
						);
			            $track['track']=$this->master_model->select_data($selected_array);
			            foreach ($track['track'] as  $v) {
			               $tracking_number=$v['tracking_number'];
					       $id=$v['product_id'];
			            }
					    

  	       if ($update_quantity>0) {
  	       	 $i=1;
  	       	 $duplicate_count=0;
  	       	 $duplicate_values=0;
  	       		 for($i; $i <= $update_quantity; $i++) 
					{
						
				        $track_no = str_split($tracking_number);
				        $key=array_search('-',$track_no)+1;

				        $pp=array_slice($track_no,0,$key);
						$prefix=implode("",$pp);
						$result= array_slice($track_no,$key);
						$final=implode("",$result);
						$cas=(int)$final;
						$for_num=number_format($cas);
						//echo $for_num;
						$for=str_split($for_num);
						//print_r($for);
						$count=count($for);
						//echo $count;
						if ($start_number!='') {
							$for_num=$start_number;
							$count=count(str_split($for_num));
							// $c=str_split($for_num);
							// $count=$c;
						}
						$complete='';
						if ($count=='1') {
								$cat= ($for_num+1)-1;
								$complete=$product_prefix.'00000'.$cat;
						}else if($count=='2'){
							$cat= ($for_num+1)-1;
							$complete=$product_prefix.'0000'.$cat;
						}else if($count=='3'){
							$cat= ($for_num+1)-1;
							$complete=$product_prefix.'000'.$cat;
						}else if($count=='4'){
							$cat= ($for_num+1)-1;
							$complete=$product_prefix.'00'.$cat;
						}else if($count=='5'){
							$cat= ($for_num+1)-1;
							$complete=$product_prefix.'0'.$cat;
						}else if($count=='6'){
							$cat= ($for_num+1)-1;
							$complete=$product_prefix.''.$cat;
						}                      
						    //echo $complete;
						    $cond[] = array('where','t.tracking_number',$complete);
							 $selected_array = array( 
			                   'table_name' =>TABLE_TRACKING_NUMBERS.' as t',
			                   'table_fields' =>'t.tracking_number',
			                   'order_by_field'=>'t.tracking_number',
			                  'order'=>'DESC',
			                   'condition'=>$cond,
                               'limit'=>'1',
                               'offset'=>''
						    );
					    $track_rep['track_rep']=$this->master_model->select_data($selected_array);

					    //dump($this->db->last_query());
					    //print_r($track_rep['track_rep']);
					    if(empty($track_rep['track_rep'])&& is_array($track_rep['track_rep'])){
					    	$tracking_data=array(
									'tracking_number' => $complete,							
								     'product_id' => $id,
								     'possessed_by'=>$branch,
								     'is_status'=>'Company'						
							);
						    $this->master_model->insert_record(TABLE_TRACKING_NUMBERS,$tracking_data);
						    // $duplicate[]='';
						 //echo "hii";  

					    }else{
					    	$duplicate[]= array($complete);
					    	$duplicate_count=count($duplicate); 
					    	$duplicate_values = json_encode($duplicate);
					    	//print_r($duplicate);
					    	$complete='';

					    }
					    $cond=''; 
  	                    $start_number++;
            
  					}

  					$tracking_number='';
					
  					$total_quantity=$total_quantity-$duplicate_count;  					
                	if ($duplicate_values!='0') {
                	
						$this->session->set_flashdata('message','Quantity in Hand updated  successfully and  Avoided the few tracking numbers  '.$duplicate_values. '  which is duplicated');
                	}else {
                	$this->session->set_flashdata('message','Quantity in Hand updated  successfully');
                	}

  					$quantity_increase= array( 
  	        			'stock_quantity'=>$total_quantity

  	       	    	); 	        
					$condition_product=array('product_id'=>$id);
		    		$this->master_model->update_record(TABLE_PRODUCT,$quantity_increase,$condition_product);
		   		
					redirect('gc/products/list_products');
					       
	    }
					
	
    }


							
  	   		     	
 }


}