<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Test extends CI_Controller {
    

	function __Construct(){ 
		parent::__Construct();
		$this->load->library('ts_functions');
		

    }

	/**************** login  **********************/	
		public function signIn(){

			$mobile = trim($this->input->post('mobile'));
			$password  = md5(trim($this->input->post('password')));
			
			$where = array(
			               'userMobile'    => $mobile, 
						   'userPassword'  => $password,
						   'userType !=' => 1
						   );
			$result  = $this->my_model->select_data('*','users', $where);
			
			$where = array(
						   'userType' => 1
						   );
			$admin  = $this->my_model->select_data('*','users', $where);
			
			 if(isset($result) && !empty($result)){	
			        if($result[0]['status']==1){
			            $userType = $result[0]['userType'];
			            $userId = $result[0]['userId'];
			            if($userType==3){
			                 $condd="partyId = $userId";
                             $sub_catData = $this->my_model->select_data('*' , 'sub_categories',$condd,'',array('itemDate','DESC'));   
			            }else{
			                $sub_catData=0;
			            }
			        
					$resp   = array(
					          'status'   => '1', 
					          'msg' => $this->ts_functions->getlanguage_msg('login_success'),
					          'data' =>$result[0],
					          'itemData'=>$sub_catData
					           );
			        }else{
			            
			            $resp = array(
					       'status' => '0', 
					       'msg' => $this->ts_functions->getlanguage_msg('account_disabled')
					       );
					
			        }          
					
				}else{  
				    
					$resp = array(
					       'status' => '0', 
					       'msg' => $this->ts_functions->getlanguage_msg('login_failure'));
					
				}   
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	    	die();
		}
	
	/**************** Register Email STARTS **********************/
	function register_user(){
	    
		if(isset($_POST['u_mobile'])) {
			$res = $this->my_model->select_data('userId','users',array('userMobile'=>$_POST['u_mobile']),1); 
			
			
			if(empty($res)) {
				$resEmail = $this->my_model->select_data('userId','users',array('userEmail'=>$_POST['u_email']),1);
				if(!empty($resEmail)){
				    $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('register_emailexists'));
				}else{
    				$randomstr	= substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 9);
    				$fourdigitrandom = rand(1000,9999); 
                    $fourdigitrandom; 
    				$param = array(	'userName'=>$_POST['u_name'],
    				                'userMobile'=>$_POST['u_mobile'],
    				                'userEmail'	=>	$_POST['u_email'],
    								'userPassword'	=>	md5($_POST['u_pwd']),
    								'verifyCode'	=>$fourdigitrandom,
    								'userType'	=>isset($_POST['user_type'])?$_POST['user_type']:'2',
    								'address'	=>	isset($_POST['address'])?$_POST['address']:'',
    								'latitude'	=>	isset($_POST['u_latitude'])?$_POST['u_latitude']:'',	
    								'longitude'	=>	isset($_POST['u_longitude'])?$_POST['u_longitude']:'',
    								);
    								
    				$userid = $this->my_model->insert_data('users',$param);
    				
    				if($userid) {
    				    
    			    	$mobile_no = $_POST['u_mobile'];
    				    $message = $fourdigitrandom.' is the One Time Password (OTP) for verifying  your mobile number.';
    				
    				    $this->ts_functions->send_msg($mobile_no,$message);
    				    
    				    // return data user 
    				    $where = array(
    			               'userId'    => $userid
    						   );
    		        	$result  = $this->my_model->select_data('*','users', $where);
    				    $resp = array('status' => 1 , 'msg' =>$this->ts_functions->getlanguage_msg('ragiter_success'),'data' =>$result[0]); 
    				    
    				}else{
    				    
    				    $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('ragister_failed')); 
    				}
				}
				
			}
			else {
				$resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('register_mobileexists')); 
			}
		}
		else {
			$resp = array('status' => 0 , 'msg' => $this->ts_functions->getlanguage_msg('register_mobilefiled'));
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
		die();
	}
	
	/**************************** Register Email ENDS **********************/
	
		/**************** usser update STARTS **********************/
	function user_update(){
	    
		if(isset($_POST['user_id'])) {
			$res = $this->my_model->select_data('userId','users',array('userId'=>$_POST['user_id']),1); 
			$mobile ="";
			if(!empty($res)) {
			    $Invoice_data =array();
			    
			    if(!empty($_POST['u_name'])){
			        $Invoice_data['userName'] = $_POST['u_name'];
			    }
			    
			    if(!empty($_POST['u_mobile'])){
			        $Invoice_data['userMobile'] = $_POST['u_mobile'];
		        	$mobile = $this->my_model->select_data('userId','users',array('userId !='=>$_POST['user_id'],'userMobile'=>$_POST['u_mobile']),1);
			    }
			    
			    if(!empty($_POST['u_email'])){
			        $Invoice_data['userEmail'] = $_POST['u_email'];
			    }
			    
			    if(!empty($_POST['u_pwd'])){
			        $Invoice_data['userPassword'] = md5($_POST['u_pwd']);
			    }
			    
			    if(!empty($_POST['address'])){
			        $Invoice_data['address'] = $_POST['address'];
			    }
			    
			    if(!empty($_POST['u_latitude'])){
			        $Invoice_data['latitude'] = $_POST['u_latitude'];
			    }
			    if(!empty($_POST['u_longitude'])){
			        $Invoice_data['longitude'] = $_POST['u_longitude'];
			    }
			    
			    if(isset($_FILES['u_image']['name']) && !empty($_FILES['u_image']['name'])){
				$usersImage = $this->upload_image('/assets/uploads/users/' , 'u_image' );	
				$Invoice_data['userImage'] = $usersImage; 
		    	}
		    
								
				$userup = $this->my_model->update_data('users' ,$Invoice_data , array('userId'=>$_POST['user_id']));
				
			
				if(empty($mobile)){
    				if($userup) {
    				     
    				    $where = array(
    			               'userId'    => $_POST['user_id']
    						   );
    		        	$result  = $this->my_model->select_data('*','users', $where);
    				    $resp = array('status' => 1 , 'msg' =>$this->ts_functions->getlanguage_msg('update_success'),'data' =>$result[0]); 
    				    
    				 }else{
    				    
    				    $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('update_failed')); 
    				 }
				}else{
				    $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('register_mobileexists'));
				}
				
			}else {
				$resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('update_failed')); 
			}
		}
		else {
			$resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('update_failed'));
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
		die();
	}
	
	/**************************** update ENDS **********************/
	
	
	/**************************** Verify Mobile STARTS **********************/
	
	function verify_mobile(){
	    
	    if(isset($_POST['verify_code']) && $_POST['verify_code'] != '') {
	        
			$verify_code = $_POST['verify_code'];
			$userDetails = $this->my_model->select_data('userId,userName,status','users',array('verifyCode'=>$verify_code),1); 
			
			if(!empty($userDetails)) {
				
				$userid = $userDetails[0]['userId'];
				if(isset($_POST['new_password']) && $_POST['new_password'] != ''){
				    $pwd = md5(trim($_POST['new_password']));
			    	$this->my_model->update_data('users',array('userPassword'=>$pwd,'verifyCode'=>''),array('userId'=>$userid));
				}else{
			        $this->my_model->update_data('users',array('status'=>1,'verifyCode'=>''),array('userId'=>$userid));
				}
			    // return data user 
			    $where = array(
		               'userId'    => $userid
					   );
	        	$result  = $this->my_model->select_data('*','users', $where);
				$resp = array('status' => 1 , 'msg' => $this->ts_functions->getlanguage_msg('verify_success'),'data'=>$result[0]);
			}
			else {
				$resp = array('status' => 0 , 'msg' => $this->ts_functions->getlanguage_msg('verify_failed'));
			}
		}
		else {
			$resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('verify_fequired'));
		}
		
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	/**************************** Verify Mobile ENDS **********************/
	

	/**************************** Get Categories STARTS **********************/
	public function get_item_category(){
	 
			$catData = $this->my_model->select_data('*' ,'categories'); 
			if(!empty($catData)){			
				$resp = array('status' => 1 , 'categoryData' =>$catData); 
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('category_failed'));
			}  
		 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	/**************************** Get unit start **********************/
	
	public function get_item_unit(){
	 
			$catData = $this->my_model->select_data('*' ,'item_unit'); 
			if(!empty($catData)){			
				$resp = array('status' => 1 , 'unitData' =>$catData); 
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('item_unit'));
			}  
		 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	/**************************** Get unit ENDS **********************/
	
	
	/**************************** Get Subcategories STARTS **********************/
	
	public function get_item_subcategory(){
	  
       $vendorId     = trim($this->input->post('vendorId'));
       $catId        = trim($this->input->post('catId'));
       $itemName     = trim($this->input->post('itemName'));
    	
    	$item=0;
    	if(empty($vendorId) && empty($catId) && empty($itemName)){
    	   
   		    $condd ="itemStatus = 1";
    	    $item  = $this->my_model->select_data('*' , 'sub_categories',$condd,'',array('itemDate','DESC'));
		   
    	}else if(empty($itemName) && empty($catId) && !empty($vendorId)){
    	    
    	    $condd = "partyId = $vendorId AND itemStatus = 1";
		    $item  = $this->my_model->select_data('*' , 'sub_categories',$condd,'',array('itemDate','DESC'));
    	    
    	}else if(empty($itemName) && !empty($catId) && !empty($vendorId)){
    	    
    	    $condd = "partyId = $vendorId AND mainCatId = $catId AND itemStatus = 1";
		    $item  = $this->my_model->select_data('*' , 'sub_categories',$condd,'',array('itemDate','DESC'));
    	    
    	}else if(!empty($itemName) && !empty($catId) && !empty($vendorId)){
    	    
		    $condd = "partyId = $vendorId AND mainCatId = $catId AND subCatName LIKE '%$itemName%' AND itemStatus = 1";
		    $item  = $this->my_model->select_data('*' , 'sub_categories',$condd,'',array('itemDate','DESC'));
    	    
    	}else if(!empty($itemName) && empty($catId) && !empty($vendorId)){
    	    
		    $where = array(
			               'catName'    => $itemName
						   );
			$cat_id  = $this->my_model->select_data('*','categories', $where);
    	    if($cat_id){
    	       $c_id = $cat_id[0]['catId'];
		        $condd = "partyId = $vendorId  AND (subCatName LIKE '%$itemName%' OR mainCatId = $c_id) AND itemStatus = 1";
    	    }else{
    	        $condd = "partyId = $vendorId  AND subCatName LIKE '%$itemName%' AND itemStatus = 1";  
    	    }
		    $item  = $this->my_model->select_data('*' , 'sub_categories',$condd,'',array('itemDate','DESC'));
    	    
    	}
    
    	$sub_catData=0;
    	 if($item){
		        foreach($item as $key=>$value){
		            $id = $value['partyId'];
		            if($id){
		                 $where = array(
            			  'userId'    => $id,
            			  'status' =>1,
            			  'userType'=>3
            						   );
		               $user = $this->my_model->select_data('*','users', $where);
		               if($user){
		                   $item[$key]['userName'] = $user[0]['userName'];
		               }else{
		                   $item[$key]['userName']=0; 
		               }
		            }else{
		                $item[$key]['userName']=0;
		            }
		            
		            $catId = $value['mainCatId'];
		            
		            if($catId){
		                 $where = array(
            			  'catId'    => $catId
            						   );
		               $category = $this->my_model->select_data('*','categories', $where);
		               if($category){
		                   $item[$key]['catName'] = $category[0]['catName'];
		                   $item[$key]['catImage'] = $category[0]['catImage'];
		               }else{
		                   $item[$key]['catName']=0; 
		                   $item[$key]['catImage']=0; 
		               }
		            }else{
		                $item[$key]['catName']=0; 
		                $item[$key]['catImage']=0;
		            }
		            
		        }
		         $sub_catData=$item;
		    }else{
		       $sub_catData=0; 
		    }
		   
    	
        if($sub_catData){
		       $resp = array('status' => 1 , 'subCategoryData' =>$sub_catData); 
		}else{
			$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('item_failed'));
		}  
	    
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	
	/**************************** Get Subcategories ENDS **********************/

    
    
    
    

	/* generate sales invoice items order costumer */ 
	public function Create_saleinvoice(){
		
		
		if(isset($_POST['item_Arr'])){
			
			$Item_Arr = json_decode($_POST['item_Arr'],true);

			if(!empty($Item_Arr) && $Item_Arr['invoice_total'] !=0 && $Item_Arr['invoice_total'] !='')
			{
				$party_name = isset($Item_Arr['party_name']) ? $Item_Arr['party_name'] : '';
				$_POST['mfwSaleItemId'] = $Item_Arr['item_id'];
				$_POST['mfwSaleItem_qty'] = $Item_Arr['qty'];
				$_POST['mfwSaleItemRate'] = $Item_Arr['rate'];
				$_POST['mfwSaleItemAmount'] = $Item_Arr['amount'];	
				
				$invoice_total=(trim($Item_Arr['invoice_total']) !='') ? trim($Item_Arr['invoice_total']) : '0';
				$payment_type = isset($_POST['payment_type']) ? $_POST['payment_type'] : '';
				$transaction_id= isset($_POST['transaction_id']) ? $_POST['transaction_id'] : '';
			    $invoice_date = date('Y-m-d');
				$OLD_INVOICE_ID = $Item_Arr['old_invoiceid'];
				$user_id =(trim($Item_Arr['user_id']) !='') ? trim($Item_Arr['user_id']) : '0';
				$vendor_id =(trim($Item_Arr['vendor_id']) !='') ? trim($Item_Arr['vendor_id']) : '0';
				
				$Invoice_data = array( 
						 'saleDate'=>$invoice_date,
						 'partyName'=>$party_name,
						 'totalAmount'=>$invoice_total,
						 'userId'=>$user_id,
						 'paymentType'=>$payment_type,
						 'transactionId'=>$transaction_id,
						 'vendorId'=>$vendor_id
						 );
				 
				if(!empty($OLD_INVOICE_ID) &&  $OLD_INVOICE_ID !=0)
				{ 
					$mainSaleId = $OLD_INVOICE_ID;
					
					$this->my_model->update_data('wholesale_item_invoice' ,$Invoice_data , array('id'=>$mainSaleId));
			
					if(!empty($mainSaleId) && isset($_POST['mfwSaleItemId']))
					{	
					    
						
						
						foreach($_POST['mfwSaleItemId'] as $key=>$value)
						{								
							$new_item_id = $_POST['mfwSaleItemId'][$key];
							
                            $InvoiceItemData =  $this->my_model->select_data('*' ,'wholesales_item',array('salesInvoiceId'=>$mainSaleId,'itemId'=>$_POST['mfwSaleItemId'][$key]));	
							if(!empty($InvoiceItemData))
							{
							    $UpdateSaleItemid =	$InvoiceItemData[0]['id'];
							}else{
								$UpdateSaleItemid ='';
							}
                        
						if(isset($UpdateSaleItemid) && $UpdateSaleItemid !=''){	
					
								$itemqty = (trim($_POST['mfwSaleItem_qty'][$key]) !='') ? trim($_POST['mfwSaleItem_qty'][$key]) : 0 ;
						
									$SaleItem_data = array('salesInvoiceId'=>$mainSaleId,
													           'itemId'=>$_POST['mfwSaleItemId'][$key],  
													           'quantity'=>$itemqty,
													           'rate'=>$_POST['mfwSaleItemRate'][$key],
													           'amount'=>$_POST['mfwSaleItemAmount'][$key]
													            );
										
							
								$this->my_model->update_data('wholesales_item' ,$SaleItem_data , array('id'=>$UpdateSaleItemid,'salesInvoiceId'=>$mainSaleId));	
								//update item store vendor
										$item_id = $_POST['mfwSaleItemId'][$key];
										$condd = "subCatId = $item_id";
										$item_m  = $this->my_model->select_data('*' , 'sub_categories',$condd,'');
										if($item_m){
										    $item_r = $item_m[0]['stockQnt'] - $itemqty;
										    
										    $SaleItem_data =array('stockQnt'=>$item_r);
										    $this->my_model->update_data('sub_categories' ,$SaleItem_data , array('subCatId'=>$item_id));
										}
								
							}else{
									if(!empty($_POST['mfwSaleItemId'][$key]))
									{
									   
									    $itemqty = (trim($_POST['mfwSaleItem_qty'][$key]) !='') ? trim($_POST['mfwSaleItem_qty'][$key]) : 0 ;
							
								
										$SaleItem_data = array('salesInvoiceId'=>$mainSaleId,
													           'itemId'=>$_POST['mfwSaleItemId'][$key],  
													           'quantity'=>$itemqty,
													           'rate'=>$_POST['mfwSaleItemRate'][$key],
													           'amount'=>$_POST['mfwSaleItemAmount'][$key]
													            );
										$this->my_model->insert_data('wholesales_item' , $SaleItem_data);
								
									}
							}
						}
						 
						}
						$resp = array('status' => 1 ,'last_invoiceid'=>$mainSaleId,'msg'=>$this->ts_functions->getlanguage_msg('order_update'));
						
					}else{
						
						// new item insert 
						// check wholesaler 
						$condd = "userId = $vendor_id AND userType = 3 AND status = 1";
						$whouser  = $this->my_model->select_data('*' , 'users',$condd,'');
	                        if(!empty($whouser)){
	                            
	                            //check item id for wholesaler
	                            $condd = "partyId = $vendor_id";
					        	$whitems  = $this->my_model->select_data('*' , 'sub_categories',$condd,'');
					        	if(!empty($whitems)){
					        	    
            						foreach($_POST['mfwSaleItemId'] as $keyi=>$value)
            						{	
            							if(!empty($_POST['mfwSaleItemId'][$keyi]))
            							{	
            							$id =$_POST['mfwSaleItemId'][$keyi];
            							$qnty = $_POST['mfwSaleItem_qty'][$keyi];
            							
            							$condd = "partyId = $vendor_id AND subCatId = $id AND stockQnt!=0";
				        	            $whitems  = $this->my_model->select_data('*' , 'sub_categories',$condd,'');	
					        	            if(empty($whitems)){
					        	                $resp = array('status'=>0 ,'msg'=>$this->ts_functions->getlanguage_msg('outof_stock'));
                 						        echo json_encode($resp , JSON_UNESCAPED_SLASHES);
                 						       die();
					        	            }
            							} 						
            						}
					        	  
					        	  
        							$mainSaleId = $this->my_model->insert_data('wholesale_item_invoice' , $Invoice_data); 
                					
                					if(!empty($mainSaleId) && isset($_POST['mfwSaleItemId']))
                					{	
                						foreach($_POST['mfwSaleItemId'] as $key=>$value)
                						{	
                							if(!empty($_POST['mfwSaleItemId'][$key]))
                							{	
                								
                								$itemqty = (trim($_POST['mfwSaleItem_qty'][$key]) !='') ? trim($_POST['mfwSaleItem_qty'][$key]) : 0 ;
                						
                								$SaleItem_data = array('salesInvoiceId'=>$mainSaleId,	
                												   'itemId'=>$_POST['mfwSaleItemId'][$key],
                												   'quantity'=>$itemqty,
                												   'rate'=>$_POST['mfwSaleItemRate'][$key],
                												   'amount'=>$_POST['mfwSaleItemAmount'][$key]
                												   );
                										   
                								$this->my_model->insert_data('wholesales_item' , $SaleItem_data);
                							  
                							} 						
                						} 
                					
                						$resp = array('status'=>1 ,'last_invoiceid'=>$mainSaleId, 'date'=>$invoice_date, 'msg'=>$this->ts_functions->getlanguage_msg('order_success')); 
                					    
                					    //send notice your email users
                					    $condd = "userId = $user_id AND userType = 2 AND status = 1";
						                $custuser  = $this->my_model->select_data('*' , 'users',$condd,'');
						                if(!empty($custuser)){
						                    $to =$custuser[0]['userEmail'];
                    					    $msg=str_replace("[order_number]",$mainSaleId,str_replace("[username]",$party_name,str_replace("[break]","<br />",$this->ts_functions->getsettings('bookorder','text'))));
                                    		$msg=str_replace("[order_date]",$invoice_date,$msg);
                                    		$this->ts_functions->email2('bookorder',$to,$msg);
						                }
                					
                					}else{
                						$resp = array('status'=>0 ,'msg'=>$this->ts_functions->getlanguage_msg('order_failed')); 
                					}
					        	}else{
					        	    $resp = array('status'=>0 ,'msg'=>$this->ts_functions->getlanguage_msg('wholesalerid_required'));
					        	}	
	                        }else{
	                             $resp = array('status'=>0 ,'msg'=>$this->ts_functions->getlanguage_msg('wholesalerid_required'));
	                        }
        				
				
					}
			
				}else{
                    
				    $resp = array('status'=>0 ,'msg'=>$this->ts_functions->getlanguage_msg('order_failed'));
				}	
			
		    
		}else{
				
		    $resp = array('status' =>0 ,'msg'=>$this->ts_functions->getlanguage_msg('order_failed')); 
	    }
		
		
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	public function get_app_version(){
	    
            $where = array(
			               'id'    => 1
						   );
			$result  = $this->my_model->select_data('*','app_version', $where);
			
			 if(isset($result) && !empty($result)){	
			        
					$resp   = array(
					          'status'   => '1', 
					          'version'   => $result[0]['version'], 
					          'msg' => 'App version show.'
					           );
					
				}else{  
				    
					$resp = array(
					       'status' => '0', 
					       'msg' => $this->ts_functions->getlanguage_msg('version_error'));
					
				}  
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);	
		    
		}
	
		/**************************** Get oders STARTS **********************/
    	public function get_all_oders(){
    	       $start     = trim($this->input->post('start'));
               $limit     = trim($this->input->post('limit'));
               $user_id     = trim($this->input->post('user_id'));
            	
               if($start==0){
                       $start = 0; 
                }else{
                        
                    $limit = $limit - $start;
                }
                if($user_id){
			        $condd ="userId = $user_id";
    	    	    $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
                }else{	 
    		    	$allOders = $this->my_model->select_data('*' ,'wholesale_item_invoice'); 
                }
    			if(!empty($allOders) && !empty($limit)){
    			    $tatalOders = count($allOders);
    			    $i =0;
    			    $allInform = array();
    			    foreach($allOders as $key=>$value){
    			        $sales_invoice_id = $value['id'];
    			        $user_id = $value['vendorId'];
    			        $allInform[$key]['id'] = $sales_invoice_id;
    			        $allInform[$key]['userId'] = $user_id;
    			        $datef = str_replace('/', '-', $value['saleDate']);
                        $sale_date = date('d/m/Y', strtotime($datef));
    			        $allInform[$key]['saleDate'] = $sale_date;
    			        $allInform[$key]['partyName'] = $value['partyName'];
    			        $allInform[$key]['totalAmount'] = $value['totalAmount'];
    			        $allInform[$key]['createdAt'] = $value['createdAt'];
    			        $allInform[$key]['updateAt'] = $value['updateAt'];
    			        $allInform[$key]['deliveryStatus'] = $value['deliveryStatus'];
    			        $allInform[$key]['status'] = $value['status'];
    			        $allInform[$key]['deliveryDate'] = $value['deliveryDate'];
    			        $allInform[$key]['paymentType'] = $value['paymentType'];
    			        $allInform[$key]['userName']= "";
		                $allInform[$key]['userEmail']= "";
		                $allInform[$key]['userMobile']= "";
		                $allInform[$key]['userCity']= "";
		                $allInform[$key]['userLatitude']= "";
		                $allInform[$key]['userLongitude']= "";
		                $allInform[$key]['item_total']= "";
			       
    			        // user details
    			        $where = array(
			               'userId'  => $user_id,
			               'userType'     =>3
						   );
			            $userDetail  = $this->my_model->select_data('*','users', $where);
			            if($userDetail){
			                 $allInform[$key]['userName']= $userDetail[0]['userName'];
			                 $allInform[$key]['userEmail']= $userDetail[0]['userEmail'];
			                 $allInform[$key]['userMobile']= $userDetail[0]['userMobile'];
			                 $allInform[$key]['userCity']= $userDetail[0]['address'];
			                 $allInform[$key]['userLatitude']= $userDetail[0]['latitude'];
			                 $allInform[$key]['userLongitude']= $userDetail[0]['longitude'];
			            }
    			        // item id check item name
    			        $where = array(
			               'salesInvoiceId'    => $sales_invoice_id
						   );
			            $itemDetail  = $this->my_model->select_data('*','wholesales_item', $where);
			            if($itemDetail){
			                $allInform[$key]['item_total']= count($itemDetail);
    			            foreach($itemDetail as $itemKey=>$itemValue){
    			                $itemId = $itemValue['itemId'];
    			                $where = array(
    			                    'subCatId'    => $itemId
    						    );
    			                $itemName  = $this->my_model->select_data('*','sub_categories', $where);
    			                if($itemName){
    			                    $itemDetail[$itemKey]['itemName']=$itemName[0]['subCatName'];
    			                    $itemDetail[$itemKey]['image']=$itemName[0]['image'];
    			                    $itemDetail[$itemKey]['qntUnit']=$itemName[0]['qntUnit'];
    			                    $itemDetail[$itemKey]['itemStockWeight']=$itemName[0]['itemStockWeight'];
    			                }
    			               
    			            }
    			            $allInform[$key]['item']=$itemDetail;
			            }else{
			                $allInform[$key]['item']="";
			            }
			            
			             
			          $i++;  
    			    }
    			    $dataArraylimit = array_slice($allInform,$start,$limit);
    				$resp = array('status' => 1 , 'ordersTotal' =>$tatalOders,'data'=>$dataArraylimit); 
    			}else{
    				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list'));
    			}  
    		 
    		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
    	}
    	
    	/**************************** Get oders ENDS **********************/
	
	
        /**************** admin login  **********************/	
		public function adminSignIn(){

			$email = trim($this->input->post('email'));
			$password  = md5(trim($this->input->post('password')));
		
			$where = array(
			               'userEmail'    => $email, 
						   'userPassword'  => $password,
						   'userType' => 1
						   );
			$result  = $this->my_model->select_data('*','users', $where);
			
			 if(isset($result) && !empty($result)){	
			        if($result[0]['status']==1){
					$resp   = array(
					          'status'   => '1', 
					          'msg' =>$this->ts_functions->getlanguage_msg('login_success'),
					          'data' =>$result[0]
					           );
			        }else{
			            $resp = array(
					       'status' => '0', 
					       'msg' =>$this->ts_functions->getlanguage_msg('account_disabled'));
					
			        }          
					
				}else{  
				    
					$resp = array(
					       'status' => '0', 
					       'msg' =>$this->ts_functions->getlanguage_msg('login_failure'));
					
				}   
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	    	die();
		}
	
	/**************** admin login end **********************/
	
  /**************** App suggetions  **********************/	
		public function app_suggetions(){

			$user_id = trim($this->input->post('user_id'));
			$aap_suggetions  = $this->input->post('aap_suggetions');
			                 
			if(!empty($user_id) && !empty($aap_suggetions)){
    			$SaleItem_data =array(
    	                            'suggetions' =>$aap_suggetions
    			                        );
    		
    			$where = array(
    			               'userId'    => $user_id
    						   );
    			$result  = $this->my_model->select_data('*','app_suggetions', $where);

    			 if(isset($result) && !empty($result)){	
    			        $sug_id = $result[0]['sugId'];
    			        
    			        
    	        	    $this->my_model->update_data('app_suggetions' ,$SaleItem_data , array('sug_id'=>$sug_id,'userId'=>$user_id));
    					$resp   = array(
    					          'status'   => '1', 
    					          'msg' =>$this->ts_functions->getlanguage_msg('update_success'),
    					          'sugId' =>$sug_id
    					           );
    					
    			}else{  
    				    $SaleItem_data['userId'] = $user_id;
    		    	    $sug_id = $this->my_model->insert_data('app_suggetions' , $SaleItem_data);
    					$resp = array(
    					       'status' => '1', 
    					       'msg' =>$this->ts_functions->getlanguage_msg('addButton'),
    					       'sugId'=>$sug_id);
    					
    			}  
			}else{
			   	$resp = array(
    					       'status' => '0', 
    					       'msg' =>$this->ts_functions->getlanguage_msg('userid_required'));
			}
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	    	die();
		}
	
	/**************** App suggetions end **********************/
	
	
	/**************************** Get oders STARTS **********************/
	public function ge_today_oders(){
	       $start     = trim($this->input->post('start'));
           $limit     = trim($this->input->post('limit'));
           $user_id     = trim($this->input->post('user_id'));
        	
           if($start==0){
                   $start = 0; 
            }else{
                    
                $limit = $limit - $start;
            }
            $from = date('Y-m-d');
    		$to = date('Y-m-d');
    	 
    		$condd ="STR_TO_DATE(`saleDate`, '%d/%m/%Y') >= '$from'  AND  STR_TO_DATE(`saleDate`, '%d/%m/%Y') <= '$to' AND status =1";
    		
            if($user_id){
                $where = array(
		               'userId'  => $user_id
					   );
		        $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('id','DESC'));
            }else{	 
		    	$allOders = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('id','DESC'));
            }
			if(!empty($allOders) && !empty($limit)){
			    $tatalOders = count($allOders);
			    $i =0;
			    $allInform = array();
			    foreach($allOders as $key=>$value){
			        $sales_invoice_id = $value['id'];
			        $user_id = $value['userId'];
			        $allInform[$key]['id'] = $sales_invoice_id;
			        $allInform[$key]['userId'] = $user_id;
			        $datef = str_replace('/', '-', $value['saleDate']);
                    $sale_date = date('d/m/Y', strtotime($datef));
			        $allInform[$key]['saleDate'] = $sale_date;
			        $allInform[$key]['partyName'] = $value['partyName'];
			        $allInform[$key]['totalAmount'] = $value['totalAmount'];
			        $allInform[$key]['createdAt'] = $value['createdAt'];
			        $allInform[$key]['updateAt'] = $value['updateAt'];
			       
			        // user details
			        $where = array(
		               'userId'  => $user_id,
		               'userType'     =>2
					   );
		            $userDetail  = $this->my_model->select_data('*','users', $where);
		            if($userDetail){
		                 $allInform[$key]['userName']= $userDetail[0]['userName'];
		                 $allInform[$key]['userEmail']= $userDetail[0]['userEmail'];
		                 $allInform[$key]['userMobile']= $userDetail[0]['userMobile'];
		                 $allInform[$key]['userCity']= $userDetail[0]['address'];
		                 $allInform[$key]['userLatitude']= $userDetail[0]['latitude'];
		                 $allInform[$key]['userLongitude']= $userDetail[0]['longitude'];
		            }else{
		                 $allInform[$key]['userName']= "";
		                 $allInform[$key]['userEmail']= "";
		                 $allInform[$key]['userMobile']= "";
		                 $allInform[$key]['userCity']= "";
		                 $allInform[$key]['userLatitude']= "";
		                 $allInform[$key]['userLongitude']= "";
		            }
			        // item id check item name
			        $where = array(
		               'salesInvoiceId'    => $sales_invoice_id
					   );
		            $itemDetail  = $this->my_model->select_data('*','wholesales_item', $where);
		            if($itemDetail){
			            foreach($itemDetail as $itemKey=>$itemValue){
			                $itemId = $itemValue['item_id'];
			                $where = array(
			                    'subCatId'    => $itemId
						    );
			                $itemName  = $this->my_model->select_data('*','sub_categories', $where);
			                if($itemName){
			                    $itemDetail[$itemKey]['itemName']=$itemName[0]['subCatName'];
			                }
			               
			            }
			            $allInform[$key]['item']=$itemDetail;
		            }else{
		                $allInform[$key]['item']="";
		            }
		            
		             
		          $i++;  
			    }
			 
			    $dataArraylimit = array_slice($allInform,$start,$limit);
			    if($dataArraylimit){
			    	$resp = array('status' => 1 , 'ordersTotal' =>$tatalOders,'data'=>$dataArraylimit);
			    }else{
   				    $resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list')); 
			    }
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list'));
			}  
		 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
    /**************************** Get oders ENDS **********************/
    
    /**************** forgote password STARTS **********************/
	function forgot_password(){
	    
		if(isset($_POST['u_mobile'])) {
			$res = $this->my_model->select_data('userId','users',array('userMobile'=>$_POST['u_mobile']),1); 
			
			if(!empty($res)) {
				$user_id = $res[0]['userId'];
				$randomstr	= substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 9);
				$fourdigitrandom = rand(1000,9999); 
                $fourdigitrandom;   
				$SaleItem_data = array(	'verifyCode'	=>$fourdigitrandom
								);
			    $message = $fourdigitrandom.' is the One Time Password (OTP) for verifying  your password change.';
			    $mobile_no = $_POST['u_mobile'];
				$this->ts_functions->send_msg($mobile_no,$message);
				$this->my_model->update_data('users' ,$SaleItem_data , array('userId'=>$user_id));
				$resp = array('status' => 1 , 'msg' =>$this->ts_functions->getlanguage_msg('forgote_password'));
			}else {
				$resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('mobileNotRegistered')); 
			}
		}
		else {
			$resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('register_mobilefiled'));
		}
		
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
		die();
	}
	
	/**************************** Forgot password ENDS **********************/
	
    /**************** order completed STARTS **********************/
	function order_completed(){
	    
			$order_id = trim($this->input->post('oder_id'));
			$delivery_status  = $this->input->post('delivery_status');
			


        if(!empty($order_id) && !empty($delivery_status))
		{  
			
    		    $where = array(
    			               'id'    => $order_id
    						   );
    		    $orderData = $this->my_model->select_data('*','wholesale_item_invoice', $where);
    		    
			if(!empty($orderData))
			{   
			    if($delivery_status==1){        
    			    // check stock items
    			    $where = array(
        			               'salesInvoiceId'    => $order_id
        						   );
        		    $orderitem = $this->my_model->select_data('*','wholesales_item', $where);
    			    if($orderitem){
    			        
    			        // update item stock
    			        foreach($orderitem as $item){
    			            $itemId =$item['itemId'];
    			            $itemQuantity =$item['quantity'];
    			            if($itemId){
    			                $where = array(
        			               'subCatId'    => $itemId
        						   );
        		                 $itemdetail = $this->my_model->select_data('*','sub_categories', $where);
        		                 if($itemdetail){
        		                     
        		                     $qunty =$itemdetail[0]['stockQnt'] - $itemQuantity;
        		                     if($qunty>=0){
        		                         $data=array('stockQnt'=>$qunty);
        		                         $this->my_model->update_data('sub_categories' ,$data, array('subCatId'=>$itemId));
        		                     }
        		                 }
    			            }
    			
    			        }
    			        
    			    }  
			    }
			    date_default_timezone_set("Asia/Calcutta");   //India time (GMT+5:30)
			    $today  = date('Y-m-d H:i:s');
			    $data = array(
			              'deliveryDate'=>$today,
			              'deliveryStatus'=>$delivery_status
			            );
			    $this->my_model->update_data('wholesale_item_invoice' ,$data, array('id'=>$order_id));
			    
			    $userId =$orderData[0]['userId'];
		        $where = array(
			               'userId'    => $userId,
			               'userType'=>2,
			               'status'=>1
						   );
		        $userData = $this->my_model->select_data('*','users', $where);
		        $vendor_id =$orderData[0]['vendorId'];
		        $where = array(
			               'userId'    => $vendor_id,
			               'userType'=>3,
			               'status'=>1
						   );
		        $vendorData = $this->my_model->select_data('*','users', $where);
		        
			    if($delivery_status==1){
			        $resp = array('status' => 1 , 'msg' =>$this->ts_functions->getlanguage_msg('order_delivered'));
			        
			        // send email
			        $user_name =$userData[0]['userName']; 
		            $to =$userData[0]['userEmail'];
			        $msg=str_replace("[order_number]",$order_id,str_replace("[username]",$user_name,str_replace("[break]","<br />",$this->ts_functions->getsettings('delivered','text'))));
            		$msg=str_replace("[order_date]",$today,$msg);
            		$this->ts_functions->email2('delivered',$to,$msg);
			    }else if($delivery_status==3){
			        
			        $resp = array('status' => 1 , 'msg' =>$this->ts_functions->getlanguage_msg('order_cancelled'));
			        if(!empty($vendorData)){
    		            $user_name =$vendorData[0]['userName'];
    		            $to =$vendorData[0]['userEmail'];
    			        $msg=str_replace("[order_number]",$order_id,str_replace("[username]",$user_name,str_replace("[break]","<br />",$this->ts_functions->getsettings('acanceled','text'))));
                		$msg=str_replace("[order_date]",$today,$msg);
                		$this->ts_functions->email2('acanceled',$to,$msg);
    		        }    
			    
			    }else{
			        $resp = array('status' => 1 , 'msg' =>$this->ts_functions->getlanguage_msg('order_cancelled'));
			        
			        // send email
			        if(!empty($userData)){
    		            $user_name =$userData[0]['userName'];
    		            $to =$userData[0]['userEmail'];
    			        $msg=str_replace("[order_number]",$order_id,str_replace("[username]",$user_name,str_replace("[break]","<br />",$this->ts_functions->getsettings('canceled','text'))));
                		$msg=str_replace("[order_date]",$today,$msg);
                		$this->ts_functions->email2('canceled',$to,$msg);
    		        }
			    }
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('update_failed'));
			}
		}else{
 			   	$resp = array(
     					       'status' => '0', 
     					       'msg' =>$this->ts_functions->getlanguage_msg('fieldRequired'));
			}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
		die();
	}
	
	// wholsaler item add and update
	
	public function create_item_vendors(){
		$userId          = trim($this->input->post('UserId'));
		$itemId          = trim($this->input->post('ItemId'));
		$itemName        = html_escape(trim($this->input->post('ItemName')));
		$itemCategoryId  = trim($this->input->post('ItemCategoryId'));
		$itemStock       = trim($this->input->post('ItemStock'));
		$itemStockUnit   = trim($this->input->post('ItemStockUnit'));
		$itemRate        = trim($this->input->post('ItemRate'));
		$ItemOfferPrice        = trim($this->input->post('itemMRP'));
		$ItemStockWeight       = trim($this->input->post('ItemStockWeight'));
		
		if(!empty($userId)){
		    
		    $SaleItem_data = array();
		    
		    if(!empty($userId)){
		        $SaleItem_data['partyId'] = $userId;
		    }
		    
		    if(!empty($itemName)){
		        $SaleItem_data['subCatName'] = $itemName;
		    }
		    
		    if($itemCategoryId !=" "){
		        $SaleItem_data['mainCatId'] = $itemCategoryId;
		    }
		    
		    if($itemStock !=" "){
		        $SaleItem_data['stockQnt'] = $itemStock;
		    }
		    
		    if($ItemStockWeight !=" "){
		        $SaleItem_data['itemStockWeight'] = $ItemStockWeight;
		    }
		    
		    if($itemStockUnit !=" "){
		        $SaleItem_data['qntUnit'] = $itemStockUnit;
		    }
		    
		    if($itemRate !=" "){
		        $SaleItem_data['rate'] = $itemRate;
		    }
		    
		    if($ItemOfferPrice !=" "){
		        $SaleItem_data['itemMrp'] = $ItemOfferPrice;
		    }
		    
		    
		    
		    if(isset($_FILES['ItemImage']['name']) && !empty($_FILES['ItemImage']['name'])){
				$ItemImage = $this->upload_image('/assets/uploads/' , 'ItemImage' );	
				$SaleItem_data['image'] = $ItemImage; 
			}
		    
		    if(!empty($itemId)){
		         $where = array(
    			               'partyId'     => $userId,
    			               'subCatId !='    => $itemId,
    			               'subCatName'  => $itemName
    						   );
		    	 $checkItem  = $this->my_model->select_data('*','sub_categories', $where);
		    	
		    	if(!empty($checkItem)){
		    	        
		    	    $resp = array(
    					       'status' => '0', 
    					       'msg' =>$this->ts_functions->getlanguage_msg('category_exists'));
		    	    
		    	}else{
		    	    
		    	    $this->my_model->update_data('sub_categories' ,$SaleItem_data , array('subCatId'=>$itemId));
		    	    $resp   = array(
    					          'status'   => '1', 
    					          'msg' =>$this->ts_functions->getlanguage_msg('item_update')
    					           );
		    	    
		    	}

		        
		    }else{
		        $where = array(
    			               'partyId'     => $userId,
    			               'subCatName'  => $itemName
    						   );
		    	 $checkItem  = $this->my_model->select_data('*','sub_categories', $where);
		        if(!empty($checkItem)){
		             $resp = array(
    					       'status' => '0', 
    					       'msg' =>$this->ts_functions->getlanguage_msg('category_exists'));
		        }else{
		            $this->my_model->insert_data('sub_categories' , $SaleItem_data);
		            $resp   = array(
    					          'status'   => '1', 
    					          'msg' =>$this->ts_functions->getlanguage_msg('add_item')
    					           );
		            
		        }
		        
		    }
		    
		}else{
			   	$resp = array(
    					       'status' => '0', 
    					       'msg' =>$this->ts_functions->getlanguage_msg('fieldRequired'));
			}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	
	// upload image folder
		
	
	function upload_image($upPath , $name , $postFix = NULL){
		$this->CI = get_instance();
		$basePath = explode('application',dirname(__FILE__))[0];
		$uploadPath = $basePath.$upPath; 
		$config['upload_path'] = $uploadPath;
		$config['allowed_types'] = '*';
		$this->CI->load->library('upload', $config);
		if ($this->CI->upload->do_upload($name)){
			$uploaddata = $this->CI->upload->data();
			$imgName = $uploaddata['raw_name'];
			$imgExt = $uploaddata['file_ext'];
			$randomstr = substr(md5(microtime()), 0, 10);
			$uploadedImage = $randomstr.$postFix.$imgExt;
			rename($uploadPath.$imgName.$imgExt, $uploadPath.$uploadedImage);
			return $uploadedImage;
		}else{ 
			return '';
		}
	}
	
		/**************************** Get vendor STARTS **********************/
	public function get_vendors(){
	        $start     = trim($this->input->post('start'));
            $limit     = trim($this->input->post('limit'));
            $vendorName = trim($this->input->post('vendorName'));
            
            if($start==0){
                   $start = 0; 
            }else{
                    
                $limit = $limit - $start;
            }
			
	    	if(!empty($vendorName)){
	    	    
        		$condd ="userType =3 AND address!='' AND status =1 AND userName LIKE '%$vendorName%'";
    	    	$wholesaler  = $this->my_model->select_data('*' , 'users',$condd,'',array('userName','ASC'));
	    	    
	    	}else{
	    	    
        		$condd ="userType =3 AND address !='' AND status =1 ";	
        		
    	    	$wholesaler  = $this->my_model->select_data('*' , 'users',$condd,'',array('userName','ASC'));
	    	}
	    	$dataArraylimit = array_slice($wholesaler,$start,$limit);
	    	
			if(!empty($wholesaler) && !empty($dataArraylimit)){			
				$resp = array('status' => 1 , 'userData' =>$dataArraylimit); 
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list'));
			}  
		 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	/**************************** Get vendor ENDS **********************/

	
		/**************************** Get vendor STARTS **********************/
	public function get_users(){
	        $start     = trim($this->input->post('start'));
            $limit     = trim($this->input->post('limit'));
            $userName = trim($this->input->post('userName'));
            
            if($start==0){
                   $start = 0; 
            }else{
                    
                $limit = $limit - $start;
            }
			
			if(!empty($userName)){
	    	    
        		$condd ="userType =2 AND status =1 AND address!=0 AND userName LIKE '%$userName%'";
    	    	$wholesaler  = $this->my_model->select_data('*' , 'users',$condd,'',array('userName','ASC'));
	    	    
	    	}else{
	    	   $condd ="userType =2 AND address!=0 AND status =1";				   
	    	   $wholesaler  = $this->my_model->select_data('*' , 'users',$condd,'',array('userName','ASC'));   
	    	}
			
	    	$dataArraylimit = array_slice($wholesaler,$start,$limit);
	    	
			if(!empty($wholesaler) && !empty($dataArraylimit)){			
				$resp = array('status' => 1 , 'userData' =>$dataArraylimit); 
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list'));
			}  
		 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	/**************************** Get vendor ENDS **********************/
	

	public function delivery_order(){
	      
           $vendor_id     = trim($this->input->post('vendor_id'));
           $delivery_status = trim($this->input->post('delivery_status'));
           $delivery_date   = trim($this->input->post('delivery_date'));
        	
           
            if($vendor_id){
                if($delivery_status==1){
                    $condd ="vendorId = $vendor_id AND deliveryStatus = 1";
                    $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('deliveryDate','DESC'));
                
                }else if($delivery_status==2){
                    $condd ="vendorId = $vendor_id AND deliveryStatus = 2";
                    $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('saleDate','DESC'));
                
                }else if($delivery_status==3){
                    $condd ="vendorId = $vendor_id AND deliveryStatus = 3";
                    $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('saleDate','DESC'));
                
                }else if($delivery_status==4){
                    $condd ="vendorId = $vendor_id AND deliveryStatus = 4";
                    $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('saleDate','DESC'));
                
                }else{
                    $condd ="vendorId = $vendor_id AND deliveryStatus = 0";
                    $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('saleDate','ASC'));
                
                }
                if($delivery_date){
                
                $date1 = str_replace('/', '-', $delivery_date);
                $date=date_create($date1);
                $newdate = date_format($date,"Y-m-d");
                
                $condd ="vendorId = $vendor_id AND deliveryStatus = 1 AND CAST(deliveryDate as Date) = '$newdate'";
                
                $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('deliveryDate','DESC'));
                
                }
    	    	
            }else{	 
		    	$allOders = "";
            }
			if(!empty($allOders)){
			    
			    $i =0;
			    $allInform = array();
			    foreach($allOders as $key=>$value){
			        $sales_invoice_id = $value['id'];
			        $user_id = $value['userId'];
			        $vendor_id = $value['vendorId'];
			        $allInform[$key]['id'] = $sales_invoice_id;
			        $allInform[$key]['vendorId'] = $vendor_id;
			        $allInform[$key]['userId'] = $user_id;
			        $datef = str_replace('/', '-', $value['saleDate']);
                    $sale_date = date('d/m/Y', strtotime($datef));
			        $allInform[$key]['saleDate'] = $sale_date;
			        $allInform[$key]['partyName'] = $value['partyName'];
			        $allInform[$key]['totalAmount'] = $value['totalAmount'];
			        $allInform[$key]['createdAt'] = $value['createdAt'];
			        $allInform[$key]['updateAt'] = $value['updateAt'];
			        $allInform[$key]['deliveryStatus'] = $value['deliveryStatus'];
			        $allInform[$key]['paymentType'] = $value['paymentType'];
			        $dbdate = $value['deliveryDate'];
			        $date=date_create($dbdate);
                    $d_date= date_format($date,"d/m/Y");
			        $allInform[$key]['deliveryDate'] = $d_date;
			        $allInform[$key]['status'] = $value['status'];
			        $allInform[$key]['userName']= "";
                    $allInform[$key]['userEmail']= "";
                    $allInform[$key]['userMobile']= "";
                    $allInform[$key]['userCity']= "";
                    $allInform[$key]['userLatitude']= "";
                    $allInform[$key]['userLongitude']= "";
                    $allInform[$key]['ordersTotal']= "";
			       
			        // user details
			        $where = array(
		               'userId'  => $user_id,
		               'userType'     =>2
					   );
		            $userDetail  = $this->my_model->select_data('*','users', $where);
		            if($userDetail){
		                 $allInform[$key]['userName']= $userDetail[0]['userName'];
		                 $allInform[$key]['userEmail']= $userDetail[0]['userEmail'];
		                 $allInform[$key]['userMobile']= $userDetail[0]['userMobile'];
		                 $allInform[$key]['userCity']= $userDetail[0]['address'];
		                 $allInform[$key]['userLatitude']= $userDetail[0]['latitude'];
		                 $allInform[$key]['userLongitude']= $userDetail[0]['longitude'];
		            }
			        // item id check item name
			        $where = array(
		               'salesInvoiceId'    => $sales_invoice_id
					   );
		            $itemDetail  = $this->my_model->select_data('*','wholesales_item', $where);
		            if($itemDetail){
		                $tatalOders = count($itemDetail);
		                $allInform[$key]['ordersTotal']= $tatalOders;
			            foreach($itemDetail as $itemKey=>$itemValue){
			                $itemId = $itemValue['itemId'];
			                $where = array(
			                    'subCatId'    => $itemId
						    );
			                $itemName  = $this->my_model->select_data('*','sub_categories', $where);
			                if($itemName){
			                    $itemDetail[$itemKey]['itemName']=$itemName[0]['subCatName'];
			                    $itemDetail[$itemKey]['image']=$itemName[0]['image'];
			                    $itemDetail[$itemKey]['stockQnt']=$itemName[0]['stockQnt'];
			                    $itemDetail[$itemKey]['itemStockWeight']=$itemName[0]['itemStockWeight'];
			                    $itemDetail[$itemKey]['qntUnit']=$itemName[0]['qntUnit'];
			                    $cat_id = $itemName[0]['mainCatId'];
			                    
			                    $where = array(
			                    'catId'    => $cat_id
    						    );
    			                $catName  = $this->my_model->select_data('*','categories', $where);
    			                if($catName){
    			                    $itemDetail[$itemKey]['catName']=$catName[0]['catName'];
    			                }else{
    			                    $itemDetail[$itemKey]['catName']='';
    			                }
			                }else{
			                    $itemDetail[$itemKey]['itemName']=0;
			                    $itemDetail[$itemKey]['image']=0;
			                }
			               
			            }
			            $allInform[$key]['item']=$itemDetail;
		            }else{
		                $allInform[$key]['item']="";
		            }
		            
		             
		          $i++;  
			    }
			
				$resp = array('status' => 1 , 'orderData'=>$allInform); 
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list'));
			}  
		 
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	/**************************** Search item and category name **********************/
    //get image logo and title
    public function get_logo_title(){

			$logo  = $this->my_model->select_data('*' , 'logo_settings','','');
			
			 if(isset($logo) && !empty($logo)){	
			        
			            $resp = array(
					       'status' => '1', 
					       'data' => $logo);
				
				}else{  
				    
					$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list'));
				}   
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	    	die();
		}
	
	//get image logo and title
    public function get_notice_orders(){
            $vendor_id     = trim($this->input->post('vendor_id'));
            $user_id       = trim($this->input->post('user_id'));
            date_default_timezone_set('Asia/Kolkata');
            $curentDate = date('Y-m-d H:i:s');
			
			if(!empty($vendor_id)){
			    $condd ="vendorId = $vendor_id AND vendorNoticeView=0";
                $allOdersup  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
                $user_notice=0;
                $vendor_notice=0;
                if(!empty($allOdersup)){
                    
                    foreach($allOdersup as $okey){
                         // count notice views 
                         $orderId = $okey['id'];
                         $SaleItem_data=array('updateAt'=>$curentDate,
                                               'vendorNoticeView'=>1
                                             );
                         $this->my_model->update_data('wholesale_item_invoice' ,$SaleItem_data , array('id'=>$orderId));
                    }
                }
               
                
			    
			    $condd ="vendorId = $vendor_id AND deliveryStatus = 0 ";

                $newOders  = count($this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC')));
                $condd ="vendorId = $vendor_id ";
                $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
			}
			
			if(!empty($user_id)){
			    
			        $condd ="userId = $user_id AND userNoticeView = 0 ";
                    $allOdersup  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
                    if(!empty($allOdersup)){
    			        foreach($allOdersup as $okey){
                             // count notice views 
                             $orderId = $okey['id'];
                             $SaleItem_data=array('updateAt'=>$curentDate,
                                                   'userNoticeView'=>1
                                                 );
                             $this->my_model->update_data('wholesale_item_invoice' ,$SaleItem_data , array('id'=>$orderId));
                        }
                    }
			    $condd ="userId = $user_id AND deliveryStatus = 0 ";

                $newOders  = count($this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC')));
                $condd ="userId = $user_id ";
                $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
			}
			
			if($allOders){	
			    
			    $msg='';
			    $dataOrder= array();
			    $i=0;
			    foreach($allOders as $key=>$okey){
			        
			        $deliveryStatus = $okey['deliveryStatus'];
			        $orderN =$okey['id'];
			        if(!empty($vendor_id)){
    			       if($deliveryStatus==3){
    			            $msg=$this->ts_functions->getlanguage_msg('notice_orderucancel');
    			            $dataOrder[]= array('id' =>$orderN,'msg'=> $msg ,'deliveryStatus'=>$deliveryStatus);
    			        }else if($deliveryStatus==0){
    			            $msg=$this->ts_functions->getlanguage_msg('notice_neworder');
    			            $dataOrder[]= array('id' =>$orderN,'msg'=> $msg ,'deliveryStatus'=>$deliveryStatus);
    			        }
			        }else{
			           if($deliveryStatus==2){
    			            $msg=$this->ts_functions->getlanguage_msg('notice_ordercancel');
    			            $dataOrder[]= array('id' =>$orderN,'msg'=> $msg ,'deliveryStatus'=>$deliveryStatus);
    			        }else {
    			            if($deliveryStatus==1){
    			            $msg=$this->ts_functions->getlanguage_msg('notice_orderdelivered');
    			            
    			            $dataOrder[]= array('id' =>$orderN,'msg'=> $msg ,'deliveryStatus'=>$deliveryStatus);
    			          }
    			        }
			        }
			        
			        
			        $i++;
			        
			    }
			   
			        
			    $resp = array('status' => 1 , 'totalNewOrder'=>$newOders,'orderData'=>$dataOrder); 
			}else{
				$resp = array('status' => 0 , 'error' =>$this->ts_functions->getlanguage_msg('order_list'));
			}  
			  
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	    	die();
		}
		
		public function count_notice_orders(){
            $vendor_id     = trim($this->input->post('vendor_id'));
            $user_id       = trim($this->input->post('user_id'));
			date_default_timezone_set('Asia/Kolkata');
            $curentDate = date('Y-m-d H:i:s');
                    
			if(!empty($vendor_id)){
			    $condd ="vendorId = $vendor_id AND vendorNoticeView=0";
                $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
                $user_notice=0;
                $vendor_notice=0;
                if(!empty($allOders)){
                    
                    foreach($allOders as $okey){
                        $delivery_status = $okey['deliveryStatus'];
                        $orderId = $okey['id'];
                        if($delivery_status==3){
                            $vendor_notice +=1;
                        }else if($delivery_status==0){
                            
                            $vendor_notice +=1;
                        }else{
                            $user_notice +=1;
                        }
                    }
                }
               
                
			}
			
			if(!empty($user_id)){
			    $condd ="userId = $user_id AND userNoticeView = 0 ";
                $allOders  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
                $user_notice=0;
                $vendor_notice=0;
                if(!empty($allOders)){
                    foreach($allOders as $okey){
                        $delivery_status = $okey['deliveryStatus'];
                        $orderId = $okey['id'];
                        if($delivery_status==2){
                            $user_notice +=1;
                        }else if($delivery_status==1){
                            $user_notice +=1;
                        }else{
                            $vendor_notice +=1;
                        }
                        
                    }
                }
			}
			
			if($allOders){	
			    $resp = array('status' => 1 , 'userNotice'=>$user_notice,'vendorNotice'=>$vendor_notice); 
			}else{
			    $resp = array('status' => 1 , 'userNotice'=>0,'vendorNotice'=>0);
			}  
			  
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	    	die();
		}

        public function payment_refund_notice(){
    
            $user_id           = trim($this->input->post('user_id'));
            $order_id          = trim($this->input->post('order_id'));
            $withdrawal_status = trim($this->input->post('withdrawal_status'));
            $account_number           = trim($this->input->post('account_number'));
            $ifsc_code   = trim($this->input->post('ifsc_code'));
            $holder_name = trim($this->input->post('holder_name'));
            $comments    = trim($this->input->post('comments'));
            $user_mobile = trim($this->input->post('user_mobile'));
            
            $SaleItem_data=array();
            
            if(!empty($user_id)){
                
                $SaleItem_data['userId']=$user_id;
            }
            
             if(!empty($order_id)){
                
                $SaleItem_data['orderId']=$order_id;
            }
             if(!empty($withdrawal_status)){
                
                $SaleItem_data['withdrawalStatus']= $withdrawal_status;
            }
             if(!empty($account_number)){
                
                $SaleItem_data['accountNumber']=$account_number;
            }
             if(!empty($ifsc_code)){
                
                $SaleItem_data['ifscCode']=$ifsc_code;
            }
             if(!empty($holder_name)){
                
                $SaleItem_data['holderName']=$holder_name;
            }
            if(!empty($comments)){
                
                $SaleItem_data['comments']=$comments;
            }
            if(!empty($user_mobile)){
                
                $SaleItem_data['userMobile']=$user_mobile;
            }
            if(!empty($order_id) && !empty($user_id)){
    			$condd ="userId = $user_id AND id = $order_id";
                $oderData  = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'');
                if(!empty($oderData)){
                    if($oderData[0]['deliveryStatus'] !=1){
                        $sale_date = $oderData[0]['saleDate'];
                        $date = strtotime($sale_date);
                        $date7 = strtotime("+7 day", $date);
                        
                        $cdate= date('Y-m-d');
                        $currentdate = strtotime($cdate);
                        if($date7 >= $currentdate){
                        
                           $condd ="userId = $user_id AND orderId = $order_id"; 
                           $refundData  = $this->my_model->select_data('*' , 'refund_notification',$condd,''); 
                           if(empty($refundData)){
                                 $SaleItem_data['vendorId']=$oderData[0]['vendorId'];
    							$refundId = $this->my_model->insert_data('refund_notification' , $SaleItem_data);
    							$resp = array('status' => 1 , 'refundId'=>$refundId,'msg'=>$this->ts_functions->getlanguage_msg('refund_success'));
    							
    							$vendor_id = $oderData[0]['vendorId'];
    							$condd ="userId = $vendor_id"; 
                                $venderData  = $this->my_model->select_data('*' , 'users',$condd,''); 
                                if(!empty($venderData)){
                                    $user_name=null;
                                    $invoice_date =date('Y-m-d');
                                    $to=$venderData[0]['userEmail'];
        							$msg=str_replace("[order_number]",$order_id,str_replace("[username]",$user_name,str_replace("[break]","<br />",$this->ts_functions->getsettings('crefundreq','text'))));
                            		$msg=str_replace("[order_date]",$invoice_date,$msg);
                            		$this->ts_functions->email2('crefundreq',$to,$msg);
                                }
                           }else{
                               $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('refund_amountall'));
                           }
                        }else{
                            $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('refund_dateexpired'));
                        }
                    }else{
                        $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('refund_delivered'));
                    }
                     
                }else{
                    
                     $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('refund_ordernumber'));
                }
            }else{
                $resp = array('status' => 0 , 'msg' =>$this->ts_functions->getlanguage_msg('fieldRequired'));
            }
			echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	    	die();
		}
}