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

class Directsales extends CI_Controller {
	function __Construct(){ 
		parent::__Construct();
		
		if(!isset($_SESSION['USERS_DATA'])){
			redirect(base_url("login"));
		}
		$this->load->library('ts_functions');
	}
	
	
	/* sales invoice page */
	public function orders_history($id=null){
		$from = date('Y-m-d');
		$to = date('Y-m-d');
		
        $data['from'] =date('d/m/Y');
        $data['to'] =date('d/m/Y');
	
	    if(!empty($id) && $_SESSION['USERS_DATA']['userType'] ==1){
	        $condd ="userId = '$id' AND status =1  AND totalAmount>0 AND saleDate BETWEEN  '$from' AND '$to'";
	        $where = array(
			               'userId'    => $id, 
						   'userType !=' => 1
						   );
		    $cuserData = $this->my_model->select_data('*','users', $where);
		    if($cuserData){
	            $data['customersName'] = $cuserData[0]['userName'];
	            $data['customersnumber'] = $cuserData[0]['userMobile'];
	            $data['customerId'] = $id;
		    }
	    }else if( !empty($_GET['from']) && !empty($_GET['to']) ){
	        
            $f1 = $_GET['from'];
	        $data['from'] =$f1;
            $datef = str_replace('/', '-', $f1);
            $form = date('Y-m-d', strtotime($datef));
            
            $to1 = $_GET['to'];
            $data['to'] =$to1;
            $dateto1 = str_replace('/', '-', $to1);
            $to =date('Y-m-d', strtotime($dateto1));
            
            
            if(!empty($_GET['id'])){
                $id = $_GET['id'];
                $condd ="userId = '$id' AND status =1 AND totalAmount>0 AND saleDate BETWEEN  '$form' AND '$to'";
                $where = array(
    			               'userId'    => $id, 
    						   'userType !=' => 1
    						   );
    		    $cuserData = $this->my_model->select_data('*','users', $where);
    		    if($cuserData){
    	            $data['customersName'] = $cuserData[0]['userName'];
    	            $data['customersNumber'] = $cuserData[0]['userMobile'];
    	            $data['customerId'] = $id;
    		    }
            }else{
                if($_SESSION['USERS_DATA']['userType']==1){
		         $condd ="status =1 AND deliveryStatus=0 AND totalAmount>0 AND saleDate BETWEEN  '$form' AND '$to'";
    		    }else{
    		        $userId = $_SESSION['USERS_DATA']['userId'];
    		        $condd ="status =1 AND deliveryStatus=0 AND totalAmount>0 AND vendorId= '$userId' AND saleDate BETWEEN  '$form' AND '$to'";
    		    }
            }
        }else{
		    if($_SESSION['USERS_DATA']['userType']==1){
		         $condd ="status =1 AND deliveryStatus=0 AND totalAmount>0 AND saleDate BETWEEN  '$from' AND '$to'";
		    }else{
		        $userId = $_SESSION['USERS_DATA']['userId'];
		        $condd ="status =1 AND deliveryStatus=0 AND totalAmount>0 AND vendorId= '$userId' AND saleDate BETWEEN  '$from' AND '$to'";
		    }
	    }   
		
		$allsales_invoice = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('createdAt','DESC'));
		foreach($allsales_invoice as $key =>$value){
		    $userId = $value['vendorId'];
		    $customersId = $value['userId'];
		    $whId = $value['id'];
		    $where = array(
			               'userId'    => $userId, 
						   'userType !=' => 1
						   );
		    $userData = $this->my_model->select_data('*','users', $where);
		    $where = array(
			               'userId'    => $customersId, 
						   'userType !=' => 1
						   );
		    $customersData = $this->my_model->select_data('*','users', $where);
		    if($customersData){
		      $allsales_invoice[$key]['customerName']= $customersData[0]['userName'];  
		    }else{
		      $allsales_invoice[$key]['customerName']=" ";  
		    }
		    if($userData){
		        $allsales_invoice[$key]['userName']= $userData[0]['userName'];
		        $allsales_invoice[$key]['userMobile']= $userData[0]['userMobile'];
		        $allsales_invoice[$key]['userCity']= $userData[0]['address'];
		    }else{
		        $allsales_invoice[$key]['userName']= " ";
		        $allsales_invoice[$key]['userMobile']= " ";
		        $allsales_invoice[$key]['userCity']= " ";
		    }
		    
		    // add total qty
		    $where = array(
			               'salesInvoiceId'    => $whId
						   );
		    $itemData = $this->my_model->select_data('*','wholesales_item', $where);
		    $qntyy =null;
		    if(!empty($itemData)){
		       
		       foreach($itemData as $tkey){
		           
		           $qntyy += $tkey['quantity'];
		       }
		       $allsales_invoice[$key]['totalQty']= $qntyy;
		    }
		    
		}
		
		$data['itemList'] = $this->my_model->select_data('*' , 'sub_categories','','',array('subCatId','DESC'));
		
		$data['allsales_invoice'] =$allsales_invoice;
		$data['title'] ="Orders History";
		$data['active'] ="orders_history";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('sales/orders',$data); 
		$this->load->view('footer');
	} 
	
	
	/* sales invoice page */
	public function delivered_orders(){
		$from = date('Y-m-d');
		$to = date('Y-m-d');
		
        $data['from'] =date('d/m/Y');
        $data['to'] =date('d/m/Y');
	    
	    if( !empty($_GET['from']) && !empty($_GET['to'])){
	        $f1 = $_GET['from'];
	        $data['from'] =$f1;
            $datef = str_replace('/', '-', $f1);
            $form = date('Y-m-d', strtotime($datef));
            
            $to1 = $_GET['to'];
            $data['to'] =$to1;
            $dateto1 = str_replace('/', '-', $to1);
            $to =date('Y-m-d', strtotime($dateto1));
            
            if($_SESSION['USERS_DATA']['userType'] ==1){
	    	   $condd ="status =1 AND totalAmount>0 AND deliveryStatus=1 AND deliveryDate BETWEEN  '$form' AND '$to'";
	        }else{
	            $userId = $_SESSION['USERS_DATA']['userId'];
		        $data['userId'] =$userId;
		        $condd ="status =1 AND totalAmount>0 AND deliveryStatus=1 AND vendorId ='$userId' AND deliveryDate BETWEEN  '$form' AND '$to'";
	        } 
           
	    }else{
	        if($_SESSION['USERS_DATA']['userType'] ==1){
	    	    $condd ="status =1 AND totalAmount>0 AND deliveryStatus=1 AND deliveryDate BETWEEN  '$from' AND '$to'";
	        }else{
	            $userId = $_SESSION['USERS_DATA']['userId'];
		        $data['userId'] =$userId;
	            $condd ="status =1 AND totalAmount>0 AND deliveryStatus=1 AND vendorId ='$userId' AND deliveryDate BETWEEN  '$from' AND '$to'";
	        }    
	    }
		
		$allsales_invoice = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('deliveryDate','DESC'));
		foreach($allsales_invoice as $key =>$value){
		    
		    $whId = $value['id'];
		    $userId = $value['userId'];
		    $vendor_id = $value['vendorId'];
		    $where = array(
			               'userId'    => $userId, 
						   'userType !=' => 1
						   );
		    $userData = $this->my_model->select_data('*','users', $where);
		    //wholesale name add
		    $where = array(
			               'userId'    => $vendor_id, 
						   'userType !=' => 1
						   );
		    $whoData = $this->my_model->select_data('*','users', $where);
		    if($whoData){
		        $allsales_invoice[$key]['wholName']= $whoData[0]['userName'];
		    }else{
		        $allsales_invoice[$key]['wholName']="";
		    }
		    if($userData){
		        $allsales_invoice[$key]['userName']= $userData[0]['userName'];
		        $allsales_invoice[$key]['userMobile']= $userData[0]['userMobile'];
		        $allsales_invoice[$key]['userCity']= $userData[0]['address'];
		    }else{
		        $allsales_invoice[$key]['userName']= " ";
		        $allsales_invoice[$key]['userMobile']= " ";
		        $allsales_invoice[$key]['userCity']= " ";
		    }
		    
		    // total qty
		    $where = array(
			               'salesInvoiceId'    => $whId
						   );
		    $itemData = $this->my_model->select_data('*','wholesales_item', $where);
		    $qntyy =null;
		    if(!empty($itemData)){
		       
		       foreach($itemData as $tkey){
		           
		           $qntyy += $tkey['quantity'];
		       }
		       $allsales_invoice[$key]['totalQty']= $qntyy;
		    }
		    
		    
		}
		
		$data['allsales_invoice'] =$allsales_invoice;
		$data['title'] ="Delivered Orders";
		$data['active'] ="delivered_orders";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('sales/delivery_orders',$data); 
		$this->load->view('footer');
	} 
	public function cancelled_orders($customer=null){
		$from = date('Y-m-d');
		$to = date('Y-m-d');
		
        $data['from'] =date('d/m/Y');
        $data['to'] =date('d/m/Y');
	    
	    if(empty($customer)){
    	    if( !empty($_GET['from']) && !empty($_GET['to'])){
    	        $f1 = $_GET['from'];
    	        $data['from'] =$f1;
                $datef = str_replace('/', '-', $f1);
                $form = date('Y-m-d', strtotime($datef));
                
                $to1 = $_GET['to'];
                $data['to'] =$to1;
                $dateto1 = str_replace('/', '-', $to1);
                $to =date('Y-m-d', strtotime($dateto1));
                
                if($_SESSION['USERS_DATA']['userType'] ==1){
    	    	    $condd ="status =1 AND totalAmount>0 AND deliveryStatus=2 AND deliveryDate BETWEEN  '$form' AND '$to'";
    	        }else{
    	            $userId = $_SESSION['USERS_DATA']['userId'];
    		        $data['userId'] =$userId;
    		        $condd ="status =1 AND totalAmount>0 AND deliveryStatus=2 AND vendorId ='$userId' AND deliveryDate BETWEEN  '$form' AND '$to'";
    	            
    	        }  
               
    	    }else{
    		    
    		    if($_SESSION['USERS_DATA']['userType'] ==1){
    	    	    $condd ="status =1 AND totalAmount>0 AND deliveryStatus=2 AND deliveryDate BETWEEN  '$from' AND '$to'";
    	        }else{
    	            $userId = $_SESSION['USERS_DATA']['userId'];
    		        $data['userId'] =$userId;
    		        $condd ="status =1 AND totalAmount>0 AND deliveryStatus=2 AND vendorId ='$userId' AND deliveryDate BETWEEN  '$from' AND '$to'";
    	            
    	        }    
    	    }
	    }else{
	        
	        $data['cancelCustomer'] ="Customers";
	        if( !empty($_GET['from']) && !empty($_GET['to'])){
    	        $f1 = $_GET['from'];
    	        $data['from'] =$f1;
                $datef = str_replace('/', '-', $f1);
                $form = date('Y-m-d', strtotime($datef));
                
                $to1 = $_GET['to'];
                $data['to'] =$to1;
                $dateto1 = str_replace('/', '-', $to1);
                $to =date('Y-m-d', strtotime($dateto1));
                
                if($_SESSION['USERS_DATA']['userType'] ==1){
    	    	    $condd ="status =1 AND totalAmount>0 AND deliveryStatus=3 AND deliveryDate BETWEEN  '$form' AND '$to'";
    	        }else{
    	            $userId = $_SESSION['USERS_DATA']['userId'];
    		        $data['userId'] =$userId;
    		        $condd ="status =1 AND totalAmount>0 AND deliveryStatus=3 AND vendorId ='$userId' AND deliveryDate BETWEEN  '$form' AND '$to'";
    	            
    	        }  
               
    	    }else{
    	        if($_SESSION['USERS_DATA']['userType'] ==1){
        	    	    $condd ="status =1 AND totalAmount>0 AND deliveryStatus=3 AND deliveryDate BETWEEN  '$from' AND '$to'";
    	        }else{
    	            $userId = $_SESSION['USERS_DATA']['userId'];
    		        $data['userId'] =$userId;
    		        $condd ="status =1 AND totalAmount>0 AND deliveryStatus=3 AND vendorId ='$userId' AND deliveryDate BETWEEN  '$from' AND '$to'";
    	            
    	        }
    	    }
	    }
		
		$allsales_invoice = $this->my_model->select_data('*' , 'wholesale_item_invoice',$condd,'',array('deliveryDate','DESC'));
		foreach($allsales_invoice as $key =>$value){
		    $userId = $value['userId'];
		     $vendor_id = $value['vendorId'];
		    $whId = $value['id'];
		    $where = array(
			               'userId'    => $userId, 
						   'userType !=' => 1
						   );
		    $userData = $this->my_model->select_data('*','users', $where);
		    
		    //wholesale name add
		    $where = array(
			               'userId'    => $vendor_id, 
						   'userType !=' => 1
						   );
		    $whoData = $this->my_model->select_data('*','users', $where);
		    if($whoData){
		        $allsales_invoice[$key]['wholName']= $whoData[0]['userName'];
		    }else{
		        $allsales_invoice[$key]['wholName']="";
		    }
		    if($userData){
		        $allsales_invoice[$key]['userName']= $userData[0]['userName'];
		        $allsales_invoice[$key]['userMobile']= $userData[0]['userMobile'];
		        $allsales_invoice[$key]['userCity']= $userData[0]['address'];
		    }else{
		        $allsales_invoice[$key]['userName']= " ";
		        $allsales_invoice[$key]['userMobile']= " ";
		        $allsales_invoice[$key]['userCity']= " ";
		    }
		    
		     // add total qty
		    $where = array(
			               'salesInvoiceId'    => $whId
						   );
		    $itemData = $this->my_model->select_data('*','wholesales_item', $where);
		    $qntyy =null;
		    if(!empty($itemData)){
		       
		       foreach($itemData as $tkey){
		           
		           $qntyy += $tkey['quantity'];
		       }
		       $allsales_invoice[$key]['totalQty']= $qntyy;
		    }
		    
		    
		}
		
		$data['allsales_invoice'] =$allsales_invoice;
		$data['title'] ="Cancelled Orders";
		$data['active'] ="cancelled_orders";
		$this->load->view('header',$data);
		$this->load->view('sidebar',$data);
		$this->load->view('sales/cancelled_orders',$data); 
		$this->load->view('footer');
	} 


	/* generate sales invoice */
	public function Create_wholesales_item(){
		

				$party_name = $_POST['mfwWholeSalePartyName'];
				$user_id = $_POST['mfwWholeSalePartyId'];
				$_POST['mfwSaleItemId'] = explode("@$#",$_POST['mfwDWSaleOldqty_item_id']);
				$_POST['mfwSaleItem_qty'] = explode("@$#",$_POST['mfwDWSaleItemqty_Shop']);
				$_POST['mfwSaleItemRate'] = explode("@$#",$_POST['mfwDWSaleItemRate']);
				$_POST['mfwSaleItemAmount'] = explode("@$#",$_POST['mfwDWSaleItemAmount']);	
				$invoice_total=$_POST['mfwDWInvoiceTotal'];
			    $invoice_date = date('Y-m-d');
				$OLD_INVOICE_ID = $_POST['mfwSaleBillNo'];
				//$user_id =(trim($Item_Arr['userId']) !='') ? trim($Item_Arr['userId']) : '0';
			
				$Invoice_data = array( 
						 'saleDate'=>$invoice_date,
						 //'partyName'=>$party_name,
						 'totalAmount'=>$invoice_total
						 );
				 
				 
				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));
					
					// user name update 
					if(!empty($user_id) && !empty($party_name)){
					$Invoice_data = array( 
						 'userName'=>$party_name
						 );
						 
					$this->my_model->update_data('users' ,$Invoice_data , array('userId'=>$user_id));
					}
					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))
							{
							    //wholesales_item id
							    $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));	
								
							}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 ,'redirect' => $_POST['mfwSaleItemId'],'msg'=>'Successfully updated');
						
					}
		
            	echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	

	/* Edit wholesales invoice */
	public function edit_wholesales(){
		
		if(isset($_POST['salesId']) && !empty($_POST['salesId']))
		{  $SalesData='';
	        $sales_id = $_POST['salesId'];
			$SalesData = $this->my_model->select_data('*' , 'wholesale_item_invoice' , array('id' => $sales_id),'1');
			foreach($SalesData as $key =>$value){
    		    $userId = $value['userId'];
    		    $where = array(
    			               'userId'    => $userId, 
    						   'userType !=' => 1
    						   );
    		    $userData = $this->my_model->select_data('*','users', $where);
    		    if($userData){
    		        $SalesData[$key]['userName']= $userData[0]['userName'];
    		    }else{
    		        $SalesData[$key]['userName']= " ";
    		    }
    		    $date = $value['saleDate'];
                $rdate = str_replace("/","-",$date);
                $datem =date_create($rdate);
                $SalesData[$key]['saleDate'] = date_format($datem,"d-M-Y");
    		    
		    
	    	}
			
			if(!empty($SalesData))
			{
				$sale_invoice_id = $SalesData[0]['id'];
				$party_id = $SalesData[0]['userName'];
				$field_list ='';
				 
				$Sales_itemData = $this->my_model->select_data('*' , 'wholesales_item' , array('salesInvoiceId' => $sale_invoice_id));
				
				$SaleitemList ='';
					
				if(!empty($Sales_itemData))
				{
					$i = 1;
					foreach($Sales_itemData as $saleitem) 
					{		
						$item_details = $this->my_model->select_data('*' , 'sub_categories' , array('subCatId' => $saleitem['itemId']),'1');
					
						$item_name = $item_details[0]['subCatName'];	
						$SaleitemList .="<tr class='item-row' id='addrow_$i'>"; 
						
						$SaleitemList .="<td>$i</td>";
						$SaleitemList .="<td><input type='text' readonly class='form-control mfw_DWSaleItemName' name='mfwDWSaleItemName[]' value='".$item_name."' autocomplete='off' placeholder='Item Name' required readonly tabindex='-1'> <div class='mfw_TransferGTSItemLiveSearchName'><ul class='mfw_TransferGTSItemLiveSearchNameList'></ul></div></td>";
						$SaleitemList .="<td class='for_shop_wholesale'><input type='hidden'  name='mfwDWSaleOldqty_itemId[]' class='mfw_DWSaleOldqty_itemId' value='".$saleitem['itemId']."'><input type='hidden' name='mfwDWSaleOldqty_Shop[]' class='mfw_DWSaleOldqty_Shop' value='".$saleitem['quantity']."'  autocomplete='off'/><input type='text' readonly name='mfwDWSaleItemqty_Shop[]' value='".$saleitem['quantity']."' placeholder='Quantity' class='form-control mfw_DWSaleItemqty_Shop' autocomplete='off'  /><label class='shopqty_error'></label></td> ";
				
						$SaleitemList .="<td><input type='text' readonly name='mfwDWSaleItemRate[]' value='".$saleitem['rate']."'  placeholder='Rate' class='form-control mfw_DWSaleItemRate' tabindex='-1' /><input type='hidden' name='mfwDWSaleItemRate_Hide[]' value='".$saleitem['rate']."' class='form-control mfw_DWSaleItemRate_Hide' readonly/></td>"; 
						
						$SaleitemList .="<td><input type='text' readonly name='mfwDWSaleItemAmount[]' value='".$saleitem['amount']."'  placeholder='Rate' class='form-control mfw_DWSaleItemAmount' readonly tabindex='-1'/></td>";
						
						$SaleitemList .="<td><span class='btn-danger stock_delete_row wholesales_item_delete'  id='".$saleitem['id']."' data-itemAmount='".$saleitem['amount']."'><i class='fa fa-trash-o'></i></span></td></tr>";
						
						$i++;
					}
					
					$resp = array('status' => 1 , 'salesdata' => $SalesData[0],'saleitemList'=>$SaleitemList,'company_list'=>$field_list);
				}else{
					$resp = array('status' => 1 ,'salesdata' => $SalesData[0],'saleitemList'=>$SaleitemList, 'error' => '12Something went wrong, please try.');
				}
			}else{
				$resp = array('status' => 0 , 'error' => '1Something went wrong, please try.');
			}
		}else{
			$resp = array('status' => 0 , 'error' => 'fgfSomething went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	
	
	
	
	/* generate sales invoice  view popup */
	public function generate_wholesales_invoice(){

		 if(isset($_POST['invoiceId']) && !empty($_POST['invoiceId']))
		 {
			$invoiceId = $_POST['invoiceId'];

			$salesData = $this->my_model->select_data('*' ,'wholesale_item_invoice' ,array('id' => $invoiceId));
			foreach($salesData as $key =>$value){
    		    $userId = $value['userId'];
    		    $where = array(
    			               'userId'    => $userId, 
    						   'userType !=' => 1
    						   );
    		    $userData = $this->my_model->select_data('*','users', $where);
    		    if($userData){
    		        $salesData[$key]['userName']= $userData[0]['userName'];
    		    }else{
    		        $salesData[$key]['userName']= " ";
    		    }
    		   
    		    $vendor_id = $value['vendorId'];;
				$where = array(
    			               'userId'    => $vendor_id, 
    						   'userType !=' => 1
    						   );
    		    $vendorData = $this->my_model->select_data('*','users', $where);
    		    if($vendorData){
    		        $salesData[$key]['vendorName']= $vendorData[0]['userName'];
    		        $salesData[$key]['vendorMobile']= $vendorData[0]['userMobile'];
    		        $test_str = $vendorData[0]['address'];; 
                    $words = explode('|', $test_str);
                    if($words[0]){
                       $salesData[$key]['vendor_address']=  $words[1]."/".$words[3]." ".$words[2]." ".$words[0];
                    }
    		        
    		    }else{
    		        $salesData[$key]['vendorName'] ="";
    		        $salesData[$key]['vendorMobile'] ="";
    		        $salesData[$key]['vendor_address'] ="";
    		    }
                    $date = $value['saleDate'];
                    $rdate = str_replace("/","-",$date);
                    $datem =date_create($rdate);
                    $salesData[$key]['saleDate'] = date_format($datem,"d-M-Y");	
                    
                    $date = $value['deliveryDate'];
                    $rdate = str_replace("/","-",$date);
                    $datem =date_create($rdate);
                    $salesData[$key]['deliveryDate'] = date_format($datem,"d-M-Y");	
		    
	    	}
			
		 }		

		if(!empty($salesData))
		{ 		$itemList ='';
				$invoiceId = $salesData[0]['id'];
				$party_id = $salesData[0]['userName'];

				$SubTotal = $salesData[0]['totalAmount'];
				
				
				if($salesData[0]['deliveryStatus']==1){
				    $delivryd ='<td  class="padderLF_20"><p class="print_td_p text-right"><strong>Delivery Date</strong>:  <b>'.$salesData[0]['deliveryDate'].'</b></p>
										</td>';
				}else if($salesData[0]['deliveryStatus']==2){
				    $delivryd ='<td  class="padderLF_20"><p class="print_td_p text-right"><strong>Cancelled Date</strong>:  <b>'.$salesData[0]['deliveryDate'].'</b></p>
										</td>';
				}else{
				    $delivryd ='<td></td>';
				}
				
				$itemList .='<html>
				        <head>
				         <style>
        						@media print {
        						  
        								body {margin-top:0mm;margin-left:0mm;margin-right:0mm;margin-bottom:0mm}
        							 
        								tr.vendorListHeading {
        									background-color: #000000 !important;
        									 
        								}
        								
        								th {
        									 color: #ffffff !important; 
        								}
        								
        								body {
        								  transform: scale(.75);
        								  transform-origin: 0 0;
        								}
        
        								@page {
        								   size: 80mm 297mm;
        								}
        						}
						</style>
						</head>
						<body>
						<table class="width_full">
								<thead>
    								<tr>
    								    <th colspan="2" class="table_head_padder">
        								    <h4 class="print_th_h">'.$salesData[0]['vendorName'].'</h4>
            								<p class="table_head_p">'.$salesData[0]['vendor_address'].'</p>
            								<p class="table_head_p"><strong>Phone</strong> :'.$salesData[0]['vendorMobile'].'</p>
        								</th>
        								<th class="table_head_padder">
        								    <h2 class="print_th_h2">INVOICE</h2>
        								</th>
    								</tr>
								</thead>
								<tbody>
									<tr>
										<td colspan="2" class="padderLF_20"><p class="print_td_p"><strong>Invoice</strong>: <b class="td_b">'.$salesData[0]['id'].'</b></p></td>
										<td class="padderLF_20"><p class="print_td_p text-right"><strong>Date</strong>: <b>'.$salesData[0]['saleDate'].'</b></p>
										</td>
									</tr>
									<tr>
										<td colspan="2" class="padderLF_20"><p class="print_td_p"><strong>Name</strong>:  <b>'.$salesData[0]['userName'].'</b></p></td>
										'.$delivryd.'
									</tr>';
									
									
				$itemList.='<tr>
							<td colspan="3" class="padderLF_20">
								<table class="printgodown123 mt_30 width_full">
									<thead>
										<tr class="vendorListHeading"><th class="print_th">S.NO</th>
                                           	<th class="vendorListcol print_th min_width_200">Item Name</th>	
											<th class="print_th">Qty</th>	
											<th class="print_th">Weight</th>	
											<th class="print_th">Rate</th>	
											<th class="print_th">Amount</th>	
										</tr>
									</thead>
									<tbody>';					
									
									
									
				$SaleItems = $this->my_model->select_data('*' ,'wholesales_item' , array('salesInvoiceId' => $invoiceId ));
				 
				if(!empty($SaleItems))
				{	
						$i = 1;
						$rate=0;
						$amount=0;
						$Invoice_amount=0;
						$Invoice_amount =$salesData[0]['totalAmount'];
						$total_quantity=0;
						foreach($SaleItems as $item)
						{
							$SaleItemsName = $this->my_model->select_data('*' ,'sub_categories' , array('subCatId' => $item['itemId'] ),1);
							$item_name= $SaleItemsName[0]['subCatName'];
							$Weight= $SaleItemsName[0]['itemStockWeight'];
						
							$rate=$item['rate'];
							$amount=$item['amount'];
							$total_quantity=$item['quantity'];
				
						
							if(($i%2) == 0)
							{
								$color_code ='#f9f9f9';

							}else{
								
								$color_code ='#ffffff';
							}
						
							
							$itemList.='<tr>
									<td class="print_td">'.$i.'</td> 
									<td class="print_td">'.$item_name.'</td>
									<td class="print_td">'.$total_quantity.'</td>
									<td class="print_td">'.$Weight.'</td>
									<td class="print_td">'.$rate.'</td>
									<td class="print_td">'.$amount.'</td></tr>';
							$i++;
						}

							$itemList.='<tr><td colspan="6" class="invoce_total"><strong>Invoice Total: '.number_format($SubTotal,2, '.', '').'</strong></td>
									</tr>
								</tbody>
								</table>
								</td>
							</tr>
						</tbody>
						</table>
						</body>
						</html>';
						
						$resp = array('status' => 1 ,'itemList'=>$itemList);
						
						
					}else{
					    	$resp = array('status' => 0 , 'error' => '1Something went wrong, please try.');

					}
			}	
				
		
		echo json_encode($resp , JSON_UNESCAPED_SLASHES); 
	}
	
	
	
	/* Edit order delivery complited  */
	public function deliveryStatus(){
		
		if(isset($_POST['salesId']) && !empty($_POST['salesId']))
		{  
	        $order_id = $_POST['salesId'];
			
    		    $where = array(
    			               'id'    => $order_id
    						   );
    		    $orderData = $this->my_model->select_data('*','wholesale_item_invoice', $where);
    		    
			if(!empty($orderData))
			{   
			    if($_POST['deliveryValue']==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]['stock_qnt'] - $itemQuantity;
        		                     if($qunty>=0){
        		                         $data=array('stock_qnt'=>$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'=>$_POST['deliveryValue']
			            );
			    $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);
			    if($_POST['deliveryValue']==1){
			        $resp = array('status' => 1 , 'msg' => 'Your order delivered complete.');
			        // 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('delivered','text'))));
                		$msg=str_replace("[order_date]",$today,$msg);
                		$this->ts_functions->email2('delivered',$to,$msg);
    		        }
			    }else{
			        $resp = array('status' => 1 , 'msg' => 'Your order delivery cancel.');
			        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' => 'Something went wrong, please try.');
			}
		}else{
			$resp = array('status' => 0 , 'error' => 'Something went wrong, please try.');
		}
		echo json_encode($resp , JSON_UNESCAPED_SLASHES);
	}
	
	
	
	
	
	
	
	
}