<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Sales extends CI_Controller {

    var $main_menu_name = "sales";
	var $sub_menu_name = "sales";

	public function __construct()
	{
		parent::__construct();

		$this->load->model('Sales_Model');
		$this->load->model('Supplier_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Common_Model');
		$this->load->model('Tax_Rates_Model');
		$this->load->model('Customer_Model');
		$this->load->model('Sales_Return_Model');
		$this->load->model('Cus_Pricing_Model');
		$this->load->model('Country_Model');
		$this->load->model('Transfer_Model');
		$this->load->model('Purchases_Model');
		$this->load->model('User_Model');
		$this->load->model('Product_Damage_Model');//
		$this->load->model('Product_Models');//
		$this->load->model('category_models');
		$this->load->model('Department_Model');
		$this->load->model('Supplier_Multiple_Payment_Model');
		$this->load->model('sms_model');
		ini_set("memory_limit","400M");
		
	}
	
	function test_new_sms(){
	    ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
	    $msg="Dear test";
				 
		$this->Common_Model->send_sms_new($msg,'0716672244');
	}
	
	//Sales list page load
	public function index()
	{
		 
		$data['sales'] = array();//$this->Sales_Model->get_all_sales();
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
		
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['shift_list'] = $this->Common_Model->get_shif_list();
		
        $this->load->view('sales',$data);
	}

	    public function ebill($encoded_id = null)
    {
        // --- Decode the sale_id if passed ---
        $decode_sale_id = null;
        
        
    
        if (!empty($encoded_id)) {
            // Decode safely (Base64 example)
            $decode_sale_id = base64_decode(urldecode($encoded_id));
        }else{
            die();
        }

		
        
        
        $sale_id = $decode_sale_id;
         $data = [];
        
        $data['sale_details']= $this->Sales_Model->get_sale_info($sale_id);

		
		$this_invoice_date = $data['sale_details']['sale_datetime'];
		//echo $this_invoice_date;

		$saleDate = new DateTime($this_invoice_date);
		$today = new DateTime();

		$interval = $today->diff($saleDate);

		if ($saleDate < $today && $interval->days > 14) {
			echo '<div style="padding:15px; background-color:#f8d7da; color:#721c24; border:1px solid #f5c6cb; border-radius:5px; font-family:Arial;">
				⚠️ This eBill has expired. Please contact support for further assistance.
			</div>';
			exit;

		}
		


		//$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
    
        // Prepare data for view
       
        $data['sale_id'] = $decode_sale_id;

		$sl_rtn_id=$data['sale_details']['sl_rtn_id'];
		$data['sale_rtn_item_list']=array();
		$data['sale_rtn_details']=array();
		
		//echo "Test 2";
		
		if(isset($sl_rtn_id)){
			$data['sale_rtn_item_list']= $this->Sales_Return_Model->get_sale_return_item_list($sl_rtn_id);
			$data['sale_rtn_details']= $this->Sales_Return_Model->get_sale_return_info($sl_rtn_id);
		}
		
		$data['is_print'] = 0;
		
        
        //print_r($data);
    
        $this->load->view('models/view_sales', $data);
    }
    


	
	
	//send_sms
		public function test_sms()
	{
	    
	    echo "Test <br/>";
	    //$number1="717844988";

		//$formatted_number = "714617137";
		//$formatted_number = "0767453326"; // Nawanjana
		$formatted_number = "0760578535"; // smart phone
        $sale_datetime =  date('Y-m-d'); 
        $reference_no = 'ddddd';
        $sale_pymnt_amount = 20000;
        //$message = "Test";

		$sale_id = 188;
		$s_inv_no = 'SPA/S/0182';
		$encoded_id = urlencode(base64_encode($sale_id));
		$url = $_SERVER['HTTP_HOST'];

		$now_date_time = date("Y-m-d H:i:s");

		echo "<br/> $now_date_time <br/> ";

		$message = "Hi, ";
		$message .= "Thanks for your order!.\n";
		$message .= "View your bill here:\n";
		$message .= "https://$url/sales/ebill/$encoded_id\n\n";
		$message .= "This URL expires in 14 days.\n";
		//$message .= "Ref: $s_inv_no.";
		//$message .= "\n $now_date_time";

		$response = [];
        $response = $this->sms_model->send_sms($formatted_number, $message);
        print_r($response);

	//   // $number1="0714617137";
	//    // $msg="Dear Mr. Nishantha, \\nInvoice No : L/S/21024 12.51 ";
	    
	//    $msg="Dear Mr. Nishantha, \\nInvoice No : L/S/21024 \\nAmount Rs. 10,000.00 \\n \\nPlease visit our website for online order : http://www.lasermobile.lk \\nLike us & follow on facebook for special officers : http://www.facebook.com/LaserMobile \\nContact us for flash home deliveries on 0717844988 or 0777844988. \\n \\nThank You For Your Business. Please come Again. \\n \\nLaser Mobile Technology (Pvt) Ltd.  \\nAthurugiriya. \\nLiberty Plaza.";
	//     $this->Common_Model->send_sms($msg,$number1);
	}
	
	
		public function test_ser_sms()
	{
	    
	    echo "Test <br/>";
	  //  $number1="94717844988";
	   $number1="0714617137";
	   // $msg="Dear Mr. Nishantha, \\nInvoice No : L/S/21024 12.51 ";
	    
	   $msg="Dear Mr. Nishantha, \\n\\nRepair Job No : L/S/21024 \\nTechnician Name : Anura \\n\\nItem Name : Samsung , A30s , Fault Type : No Power , IMEI/Serial No : Not Found ,  Estimated Amount : Pending. \\n\\nJob Status Inquire Hotline : 0718230230. \\n\\nLaser Mobile Technology (Pvt) Ltd. \\nService - Repair Department, \\nAthurugiriya.";
	    $this->Common_Model->send_ser_sms($msg,$number1);
	    
	    echo "Msg:$msg";
	}
	
	
		public function get_list_sales_for_manual()
	{
	    $requestData=$this->input->get();
	
	$search_key=$this->input->get('search');
	$warehouse_id=$this->input->get('warehouse_id');
	//echo "warehouse_id:$warehouse_id";
	
	//print_r($search_key);
	//echo $search_key['value'];
	$search_key_val=$search_key['value'];
	$start=0;//$this->input->get('0');
	$length=500;//$this->input->get('10');
	$sale_id='';//3683;
	

	
	$data = array();

	$sales = $this->Sales_Model->get_all_sales_for_manual_qury($start,$length,$search_key_val,"","",$warehouse_id,"","",$sale_id);
	
	//$totalData = count($sales_tot);
	//$totalFiltered = $totalData;  
	
	foreach ($sales as $row){
	    
	    $sale_id=$row['sale_id'];
	    $sale_total=$row['sale_total'];
	    $sl_rtn_id=$row['sl_rtn_id'];
	    $sls_rtn_total_paid=0;
	    if($sl_rtn_id){
		$sale_rtn_details=$this->Sales_Return_Model->get_sale_return_info($sl_rtn_id);
		$sls_rtn_total_paid=$sale_rtn_details['sls_rtn_total_paid'];
		//$sl_rtn_reference_no=$sale_rtn_details['sl_rtn_reference_no'];
		}
		
			$total_paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($sale_id);
	    
	    
	    $balance=$sale_total-$sls_rtn_total_paid-$total_paid_amount;
	    
	    $updated_txt="";
	    if($balance==0){
	        //update status as paid
	        $data=array(
				'is_completed'=>1,	
			);
			if($sale_id){
			$this->Sales_Model->save_sales($data,$sale_id);
			$updated_txt="Updated";
			}
	    }
	    
	    echo "<br/> sale_id:".$sale_id ." / sale_total:$sale_total / Return : $sls_rtn_total_paid / Total paid: $total_paid_amount / Balance :  $balance / Updated txt: $updated_txt";
	    
	}
	    
	    
	}
	
	
	
		public function get_warranty_types(){
	
		$sn_data=array();
		//echo "sn:".$sn;
		
		//if($sn)
		{
		$w_data = $this->Sales_Model->get_warranty_types();
		}
		//print_r($sn_data);
		$status=0;
		//if(count($sn_data)) 
		$w_data=$w_data;
		$st = array('w_data' =>$w_data);
        echo json_encode($st);
		
	}
	
	public function interest_cal()
	{
		 $start='';
		 $length='';
		 $search_key_val='';
		 $warehouse_id=3;
		 $srh_from_date='2018-12-11';
		 $today_date='';
		 $today_date='2018-12-17 13:00:00';
		 if(!$today_date) $today_date=date("Y-m-d");
		 echo "<h1>Sale Interest</h1>";
		  echo "<p>Today Date: $today_date</p>";
		  echo "<p>From Date: $srh_from_date</p>";
		$sales = $this->Sales_Model->get_all_sales($start,$length,$search_key_val,$srh_from_date,"",$warehouse_id);
	
		foreach ($sales as $row){
			
			$sale_id=$row['sale_id'];
			$sale_reference_no=$row['sale_reference_no'];
			//get balance
			$total_paid_amount=0;
			$total_paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($sale_id);
			$return_tot_amt=0;
			$return_tot_amt=$this->Sales_Return_Model->get_total_return_by_sale_id($sale_id);
			$tot_si_amount=$this->Sales_Model->get_total_interest_by_sale_id($sale_id);
			$to_be_paid=$row['sale_total']-$return_tot_amt+$tot_si_amount-$total_paid_amount;
			$si_amount=0;
			
			$user_id=0;
			if(!empty($this->session->userdata('ss_user_id'))){
				$user_id=$this->session->userdata('ss_user_id');
			}
			
			$si_amount=10;
			$interest_val_0_5=0;
			$interest_val_5_10=0;
			$interest_val_15_more=0;
			//get settings table data by id
			$interest_val_0_5=$this->Common_Model->check_option_valable_by_setting_id(3);
			$interest_val_5_10=$this->Common_Model->check_option_valable_by_setting_id(4);
			$interest_val_10_15=$this->Common_Model->check_option_valable_by_setting_id(5);
			$interest_val_15_more=$this->Common_Model->check_option_valable_by_setting_id(7);
			
			//echo "<br/>interest_val_5_10:$interest_val_5_10 , interest_val_10_15:$interest_val_10_15";
			
			$date_diff=0;
			$date1=date_create($row['sale_datetime']);
			//$date2=date_create(date("Y-m-d H:i:s"));
			$date2=date_create($today_date);
			$diff=date_diff($date1,$date2);
			$date_diff=$diff->format("%R%a");
			$interest_val=0;
			$test='';
			if($date_diff<=5){
				$interest_val=$interest_val_0_5;
				//$test='1';
			}else if($date_diff>5 && $date_diff<=10){
				$interest_val=$interest_val_5_10;
				//$test='2';
			}
			else if($date_diff>10 && $date_diff<=15){
				$interest_val=$interest_val_10_15;
				//$test='3';
			}
			else if($date_diff>15){
				$interest_val=$interest_val_15_more;
				//$test='4';
			}
			
			//echo "<br/>Test: $test";
			
			$si_amount=($to_be_paid*$interest_val/100);
			echo "<br/>si_amount: $si_amount , to_be_paid:$to_be_paid";
			
			//get last add interest date age
			$last_int_des=$this->Sales_Model->get_last_interest_des($sale_id);
			$last_added_date='';
			//$last_int_des=$last_int_des[0];
			
			//print_r($last_int_des);
			//$last_added_date=$last_int_des['si_added'];
			
			//foreach ($last_int_des as $row_int){
			//echo "<br/>sale_id:$sale_id , si_added: ".$row_int->si_added;
			//$last_added_date=$row_int->si_added;
			//}
			if($row['current_interest']!=0.00){
				$last_added_date=$row['current_interest_date'];
				//echo "5555555555";
			}else{
				//echo "999999999";
			}
			
			//$last_added_date=$row['current_interest_date'];
			
			
			$last_added_date_def=0;
			$date1=date_create($last_added_date);
			//$date2=date_create(date("Y-m-d H:i:s"));
			$date2=date_create($today_date);
			$diff=date_diff($date1,$date2);
			$last_added_date_def_site=5;
			$last_added_date_def=$diff->format("%R%a");
			$added=0;
			
			$add_record=0;
			
			
			
			if($last_added_date_def==$last_added_date_def_site){
				
				if($si_amount){
					$add_record=1;
					//echo " , add_record:$add_record";
					$test=1;
				}
			}else if($last_added_date_def==0){
				//first time 
				$test=2;
				
				//interest 0
				if($row['current_interest']==0.00){
					$test=3;
					if($si_amount){
						$add_record=1;
					}
				}
			}
			
			//echo "<br/><br/> last_added_date:$last_added_date, last_added_date_def:$last_added_date_def, current_interest:$row[current_interest] test:$test ";
			
			
			
			//echo " , add_record111:$add_record";
			
			if($last_added_date==''){
				if($si_amount){
					$add_record=1;
				}
			}
			
			
			
			{
				
			$si_remark="Sale No:$sale_reference_no , Interest:$interest_val , Balance Amount: $to_be_paid";
			
			//$add_record=0; //test
			
			
				
			if($add_record==1){
			//add interest
			/*
			$data=array(
				'sale_id'=>$sale_id,	
				'si_amount'=>$si_amount,	
				'si_remark'=>$si_remark,	
				'si_added'=>date("Y-m-d H:i:s"),
				'user_id'=>$this->session->userdata('ss_user_id'),	
			);
			*/
			$data=array(
				'current_interest'=>$si_amount,	
				'current_interest_remark'=>$si_remark,	
				'current_interest_date'=>$today_date,
			);
				
               //if ($this->Sales_Model->save_sale_interest($data,'')) 
			   //save current interest
			   if($sale_id){
			   if ($this->Sales_Model->save_sales($data,$sale_id)) 
			   {
				  $added='Added'; 
			   }
			   }
			   
			   //echo "<br/>1111111111<br/> Sale No:$sale_reference_no,  To be paid:$to_be_paid ,  Interest: $si_amount , interest_val:$interest_val , date_diff:$date_diff , last_added_date:$last_added_date ,last_added_date_def:$last_added_date_def<br/><br/>";
			  // print_r($last_int_des[0]);
			   //send to acctivity list
			   $this->Common_Model->add_user_activitie("Added Sale Interest, (Sale No:$sale_reference_no , Interest: $si_remark) , Status: $added");
			   
			}
			}
			{
			echo "<br/><br/>Sale No:$sale_reference_no , Invoice Date:$row[sale_datetime] , Invoice Age :$date_diff , Last Interest Added Date:$last_added_date , Interest Val: $interest_val ,  To be paid:$to_be_paid  :: Interest Added Status : $added";
			}
		}
		
	}
	
	public function check_serial_no_valid($sn){
		$sn=$this->uri->segment(3);
		$product_id=$this->uri->segment(4);
		$sn_data=array();
		//echo "sn:".$sn;
		
		if($sn){
		$sn_data = $this->Sales_Model->check_serial_no_valid($sn,$product_id);
		}
		//print_r($sn_data);
		$status=0;
		if(count($sn_data)) $status=1; else $status=0;
		$st = array('status' =>$status);
        echo json_encode($st);
		
	}
	
	
	public function get_invoice_items()
	{
		$sale_id =  $this->input->get('sale_id');

		if ( $sale_id ) {
			$val = $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
			//print_r($val);
			if (!empty($val)) {
				echo '<select onChange="check_product_details()" name="product_id" id="product_id" class="form-control search-select">';
				echo "<option value=''></option>";
				foreach ($val as $row){
				echo "<option value='".$row['product_id']."'>".$row['product_name']."(".$row['product_code'].")"."</option>";
				}
				echo '</select>';
			}
			
		} else {
			echo NULL;
		}
		
	}	
	

	public function check_serial_no_details($product_sn=''){
		$sn=$this->input->get('sn');
		$service_type=$this->input->get('service_type');
		$sale_id=$this->input->get('sale_id');
		$product_id=$this->input->get('product_id');
		
		//print_r($this->input->get());
		$sn_data=array();
		//echo "sn:".$sn;
		if($service_type=='Serial'){
		$sn_data = $this->Sales_Model->get_serial_no_details($sn);
		}else if($service_type=='Invoice'){
			$sn_data = $this->Sales_Model->get_service_invocie_no_details($sale_id,$product_id);
		}
		//echo $this->db->last_query();
		//echo "tye:".$service_type;
		//print_r($sn_data);
		$status=0;
		$product_id='';
		$cus_id='';
		$supp_id='';
		$warranty_avalable=0;
		$warranty_exp_date='';
		$sale_reference_no='';
		$outstanding=0;
		$warranty_months=0;
		$sale_datetime='';
		$total_paid_amount=0;
		$supp_id='';
		$grn_id='';
		$grn_date='';
		
		
		if(count($sn_data)) {
			$sn_data=$sn_data[0];
			$product_id=$sn_data->product_id;
			$cus_id=$sn_data->customer_id;
			$supp_id=$sn_data->supp_id;
			$warranty_months=$sn_data->product_w;
			$sale_datetime=$sn_data->sale_datetime;
			$sale_reference_no=$sn_data->sale_reference_no;
			
			$date1 = $sale_datetime;
			$date2 = date("Y-m-d");
			
			$ts1 = strtotime($date1);
			$ts2 = strtotime($date2);
			
			$year1 = date('Y', $ts1);
			$year2 = date('Y', $ts2);

			$month1 = date('m', $ts1);
			$month2 = date('m', $ts2);
			
			$diff = (($year2 - $year1) * 12) + ($month2 - $month1);
			
			//echo "<br/>sale date:.$sale_datetime , Month:".$diff;
			
			if($diff<=$warranty_months) $warranty_avalable=1;
			//print_r($sn_data);
			
			$sale_id=$sn_data->sale_id;
			$total_paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($sale_id);
			$outstanding=$sn_data->sale_total-$total_paid_amount;
			if($outstanding>0) {
				$outstanding=$outstanding; 
				$outstanding=number_format($outstanding, 2, '.', ',');
			}else $outstanding=0;
			
			//get supplier id by serial key
			
			//echo 'service_type'.$service_type;
			if($service_type=='Serial'){
				
				$supp_des=$this->Purchases_Model->get_serial_no_supp_id($sn_data->sis_number);
				//print_r($supp_des);
				
				$supp_id=$supp_des[0]->supplier_id;
				$grn_id=$supp_des[0]->reference_no;
				$grn_date=$supp_des[0]->date;
			}
			
			//get serial number grn details
			
			
			//echo $supp_id;
			
			
		}
		
		//check varanti avalable
		
	
		$st = array('product_id'=>$product_id,'cus_id'=>$cus_id,'supp_id'=>$supp_id,'warranty_avalable'=>$warranty_avalable,'warranty_exp_date'=>$warranty_exp_date,'sale_reference_no'=>$sale_reference_no,'outstanding'=>$outstanding,'warranty_months'=>$warranty_months,'sale_datetime'=>$sale_datetime,'grn_id'=>$grn_id,'grn_date'=>$grn_date);
        echo json_encode($st);
		
	}
			public function purchase_check_serial_no_valid($sn){
		$sn=$this->uri->segment(3);
		$sn_data=array();
		//echo "sn:".$sn;
		if($sn){
		$sn_data = $this->Sales_Model->check_serial_no_valid($sn);
		}
		//print_r($sn_data);
		$status=0;
		if(count($sn_data)) $status=0; else $status=1;
		$st = array('status' =>$status);
        echo json_encode($st);
		
	}
	
	 public function add_serial_no()
    {
		
        $data['row'] = $this->uri->segment(3);
		 $data['qty'] = $this->uri->segment(4);
		  $product_id = $this->uri->segment(5);
		   $warehouse_id = $this->uri->segment(6);
		   $each_price=$this->uri->segment(7);
		    $page=$this->uri->segment(8);
		   $data['product_id']=$product_id;
		   $data['each_price']=floatval($each_price);
		    $data['page']=floatval($page);
		   $product_des=$this->Product_Models->get_product_by_id($product_id);
		   $data['product_dis_name']=$product_des->product_code." ".$product_des->product_name;
		   
		
		//echo "test:".$this->uri->segment(3);
		 $data['btnText'] = 'Submit';
		// $data['sn_list1'] = $this->Purchases_Model->get_serial_no_by_product_id($product_id,$warehouse_id);
		 
		 //get transfer reseved serial no
		// $data['sn_list_tra_res2'] = $this->Purchases_Model->get_transfer_reserved_serial_no_by_product_id($product_id,$warehouse_id);
		 
		// $data['sn_list']=array_merge($data['sn_list1'],$data['sn_list_tra_res2']);
		//echo "w: $warehouse_id";
		 $data['sn_list']=$this->Purchases_Model->get_serial_no_by_avalable_warehosue_id_old($product_id,$warehouse_id);
		 
		// print_r($data['sn_list_tra_res']);
		 
		// print_r($data['sn_list']);
        $this->load->view('models/serial_no_add_sales',$data);
    }
	
	 public function sales_rtn_add_serial_no()
    {
        $data['row'] = $this->uri->segment(3);
		 $data['qty'] = $this->uri->segment(4);
		  $product_id = $this->uri->segment(5);
		   $sl_rtn_id = $this->uri->segment(6);
		   $data['product_id']=$product_id;
		   $product_des=$this->Product_Models->get_product_by_id($product_id);
		   $data['product_dis_name']=$product_des->product_code." ".$product_des->product_name;
		   
		
		//echo "test:".$this->uri->segment(3);
		 $data['btnText'] = 'Submit';
		 $data['sn_list'] = $this->Purchases_Model->get_serial_no_by_product_id_sale_id($product_id,$sl_rtn_id);
		 //print_r($data['sn_list']);
        $this->load->view('models/serial_no_add_sales_rtn',$data);
    }

	 public function grn_rtn_add_serial_no()
    {
        $data['row'] = $this->uri->segment(3);
		 $data['qty'] = $this->uri->segment(4);
		  $product_id = $this->uri->segment(5);
		   $grn_id = $this->uri->segment(6);
		   $warehouse_id = $this->uri->segment(7);
		   $data['product_id']=$product_id;
		   $product_des=$this->Product_Models->get_product_by_id($product_id);
		   $data['product_dis_name']=$product_des->product_code." ".$product_des->product_name;
		   
		
		//echo "test:".$this->uri->segment(3);
		 $data['btnText'] = 'Submit';
		 $data['sn_list'] = $this->Purchases_Model->get_serial_no_by_product_id_grn_id($product_id,$grn_id,$warehouse_id);
		 //print_r($data['sn_list']);
        $this->load->view('models/serial_no_add_grn_rtn',$data);
    }
	
	 public function add_serial_no_view($product_id)
    {
        $data['row'] = $this->uri->segment(3);
		 $data['qty'] = $this->uri->segment(4);
		//echo "test:".$this->uri->segment(3);
		$data['sn_list'] = $this->Purchases_Model->get_serial_no_by_product_id($product_id);
		$data['btnText'] = 'Submit';
        $this->load->view('models/serial_no_view_sales',$data);
    }
		
	//Sales details view
	public function view()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		
		//get sale id
		$sale_id=$this->uri->segment('3');
		$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		$data['sale_details']= $this->Sales_Model->get_sale_info($sale_id);
		
		$data['total_paid_amount']=$this->Sales_Model->get_total_paid_by_sale_id($sale_id);
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);		
		$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
		$old_payment_tot=0;
		$retured_payment_tot=0;
		$retured_payment_msg_this='';
		$old_payments_dis_msg_this='';
		
		//check return payments
		$return_sales_details=$this->Sales_Return_Model->get_return_sale_info_sale_id($sale_id);
		$sl_rtn_id_2=0;
		$sl_rtn_reference_no='';
		
		
		foreach ($return_sales_details as $row)
		{
	 		//echo "sale id:$row->sale_id";
			//echo "sale_total:$row->sale_total";

				$this_balance_pament=0;
				$this_trn_amt=$row->sl_rtn_total;
				$sl_rtn_id_2=$row->sl_rtn_id;
				$url=base_url("sales/sales_return_details/")."/".$sl_rtn_id_2;
				$sl_rtn_reference_no="<a href='$url' target='_blank'>".$row->sl_rtn_reference_no."</a>";
				$retured_payment_tot=$retured_payment_tot+$this_trn_amt;

				$retured_payment_msg_this=$retured_payment_msg_this.' (-)'.$this_trn_amt.' ,';
			
			
 		}
		
		
		$old_payment_tot=$old_payment_tot-$retured_payment_tot;
		
		$data['old_payments']=$old_payment_tot;
		
		$data['old_payments_dis_msg']="Return Total Amount";// ($old_payments_dis_msg_this $retured_payment_msg_this)";
		
		$data['sale_id']=$sale_id;
		
		$sl_rtn_id=$data['sale_details']['sl_rtn_id'];
		$data['sale_rtn_item_list']=array();
		$data['sale_rtn_details']=array();
		
		if(isset($sl_rtn_id)){
			$data['sale_rtn_item_list']= $this->Sales_Return_Model->get_sale_return_item_list($sl_rtn_id);
			$data['sale_rtn_details']= $this->Sales_Return_Model->get_sale_return_info($sl_rtn_id);
		}
		
		$data['sl_rtn_id_2']=$sl_rtn_id_2;
		$data['sl_rtn_reference_no_2']=$sl_rtn_reference_no;
		
	//	echo "sl_rtn_reference_no:$sl_rtn_reference_no";
		
        $this->load->view('sales_view',$data);
	}

	//Sales add page
	public function add_sale_payments()
	{
		$sale_pymnt_amount=$this->input->post('sale_pymnt_amount');
		$sale_id=$this->input->post('sale_id');
		$sale_pymnt_ref_no=$this->input->post('sale_pymnt_ref_no');
		$sale_pymnt_paying_by=$this->input->post('sale_pymnt_paying_by');
		$sale_pymnt_date_time=$this->input->post('sale_pymnt_date_time');
		$sale_pymnt_date_time_send=date('Y-m-d H:i:s', strtotime($sale_pymnt_date_time));
		$sale_pymnt_cheque_no=$this->input->post('sale_pymnt_cheque_no');
		$sale_pymnt_crdt_card_no=$this->input->post('sale_pymnt_crdt_card_no');
		$sale_pymnt_crdt_card_holder_name=$this->input->post('sale_pymnt_crdt_card_holder_name');
		$sale_pymnt_crdt_card_month=$this->input->post('sale_pymnt_crdt_card_month');
		$sale_pymnt_crdt_card_year=$this->input->post('sale_pymnt_crdt_card_year');
		$sale_pymnt_crdt_card_type=$this->input->post('sale_pymnt_crdt_card_type');
		$sale_type = $this->input->post('sale_type');
		$acctrnss_id=$this->input->post('acctrnss_id');
		
		$b_id=$this->input->post('b_id');

		$sale_pymnt_note=$this->input->post('sale_pymnt_note');
		$user_id=$this->session->userdata('ss_user_id');
		$sale_pymnt_added_date_time=date("Y-m-d H:i:s");
		$sale_pymnt_id='';
		
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('sale_pymnt_amount', 'Amount', 'required');
		if($sale_pymnt_paying_by=='Credit Card'){
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_type', 'Card Type', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_no', 'Credit Card No', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_holder_name', 'Holder Name', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_month', 'Month', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_year', 'Year', 'required');
		}
		if($sale_pymnt_paying_by=='Cheque'){
			$this->form_validation->set_rules('sale_pymnt_cheque_no', 'Cheque No', 'required');
		}
		$this->form_validation->set_rules('sale_id', 'System Error', 'required');


        if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
			$data=array(
				'sale_pymnt_amount'=>$sale_pymnt_amount,	
				'sale_pymnt_ref_no'=>$sale_pymnt_ref_no,
				'sale_pymnt_paying_by'=>$sale_pymnt_paying_by,
				'sale_pymnt_date_time'=>$sale_pymnt_date_time_send,
				'sale_pymnt_note'=>$sale_pymnt_note,
				'user_id'=>$user_id,
				'sale_id'=>$sale_id,
				'sale_pymnt_added_date_time'=>$sale_pymnt_added_date_time,
				'sale_pymnt_cheque_no'=>$sale_pymnt_cheque_no,
				'sale_pymnt_crdt_card_no'=>$sale_pymnt_crdt_card_no,
				'sale_pymnt_crdt_card_holder_name'=>$sale_pymnt_crdt_card_holder_name,
				'sale_pymnt_crdt_card_type'=>$sale_pymnt_crdt_card_type,
				'sale_pymnt_crdt_card_month'=>$sale_pymnt_crdt_card_month,
				'sale_pymnt_crdt_card_year'=>$sale_pymnt_crdt_card_year,
				'sale_payment_type' => $sale_type,
				'extra_val_1' => $this->input->post('extra_val_1'),
				'service_charge_percentage' => $this->input->post('service_charge_percentage'),
				'acctrnss_id_p'=>$acctrnss_id,
				//'bank_id'=>$b_id
			);
			
               if ($this->Sales_Model->save_sale_payments($data,$sale_pymnt_id)) {
				   
			   if($sale_type == 'sale'){
				
				   //send message
				 $send_phone_first='0714617137';
				 $sale_pymnt_amount=number_format($sale_pymnt_amount, 2, '.', ',');
				 //get sale no
				 $sale_des=$this->Sales_Model->get_sale_info($sale_id);
				 $customer_details=$this->Customer_Model->get_customer_info($sale_des['customer_id']);
				 $cus_name=$customer_details['cus_name'];
				 $sale_reference_no=$sale_des['sale_reference_no'];
				 $send_phone_first=$customer_details['cus_phone'];
				$message="Thank you $cus_name payment of LKR $sale_pymnt_amount in respect of The SmartPhone Shop \nInv no : $sale_reference_no";
				//$message="SmartFixServiceCenter Sanath";
				//$myStr=123456789;
				$send_phone = substr($send_phone_first, 0, 10);	
				if($sale_type=='sale'){
					//$this->Common_Model->send_sms($message,$send_phone);	
				}
				
			   }
				//echo "message:$message";
				   //end send message
				   
				   //add interest added
				   $sale_details=$this->Sales_Model->get_sale_info($sale_id);


				//    if($sale_details['current_interest']!=0.00 && $sale_details['current_interest']){
				if (!empty($sale_details['current_interest']) && $sale_details['current_interest'] != 0.00) {
				   $data=array(
				'sale_id'=>$sale_id,	
				'si_amount'=>$sale_details['current_interest'],	
				'si_remark'=>$sale_details['current_interest_remark'],	
				'si_added'=>date("Y-m-d H:i:s"),
				'user_id'=>$this->session->userdata('ss_user_id'),	
				);
				if ($this->Sales_Model->save_sale_interest($data,'')){
					//delete currect interest des
					$data=array(
				'current_interest'=>0,	
				'current_interest_remark'=>'',	
				//'current_interest_date'=>date("Y-m-d H:i:s"),
				);
				 	if($sale_id){
			  			 if ($this->Sales_Model->save_sales($data,$sale_id)) 
			  		 {
				 		 $added='Added'; 
			  		 }
				}}
				
				   }
				   
                    $st = array('status' =>1,'validation' =>'Done!');
                    echo json_encode($st);
               } else {
                    $st = array('status' =>0,'validation' =>'error occurred please contact your system administrator');
                    echo json_encode($st);
               }
		}
	}	
	
	//Sales payment page 
	public function payments()
	{
        $data['sale_id'] = $this->input->get('id');
        $data['sale_type'] = $this->input->get('sale_type');
        
        
        //get sale warehouse id
        $sale_details=$this->Sales_Model->get_sale_info($data['sale_id']);
		$warehouse_id = isset($sale_details['warehouse_id']) 
		? $sale_details['warehouse_id'] 
		: $this->session->userdata('ss_warehouse_id');


        
        //echo "warehouse_id:$warehouse_id";
        $shift_date=date("Y-m-d");
        $active_shift_des=$this->Common_Model->get_active_shift_by_warehouse_id_date($warehouse_id,$shift_date);

        //print_r($active_shift_des); 
		//die();

        if(!count($active_shift_des)){
			redirect(base_url("sales/error"));
			die();
		}else{
			$acctrnss_id=$active_shift_des['acctrnss_id'];
		}
						
		$data['acctrnss_id'] = $acctrnss_id;
         //echo "acctrnss_id:$acctrnss_id";
         
        $data['bank_details'] = $this->Supplier_Multiple_Payment_Model->get_all_bank_accounts();
         
        $this->load->view('models/sales_payment',$data);	
	}
	
	
	public function payments_sub()
	{
	    $data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		$data['sale_id'] = $this->input->get('id');
		$data['sale_type'] = $this->input->get('sale_type');
		$warehouse_id = $this->session->userdata('ss_warehouse_id');

		//echo "warehouse_id:$warehouse_id";
		$shift_date = date("Y-m-d");
		$active_shift_des = $this->Common_Model->get_active_shift_by_warehouse_id_date($warehouse_id, $shift_date);
		$acctrnss_id = $active_shift_des['acctrnss_id'];
		$data['acctrnss_id'] = $acctrnss_id;
		$data['bank_details'] = $this->Supplier_Multiple_Payment_Model->get_all_bank_accounts();
		$this->load->view('models/sales_payment_sub', $data);
	}


	public function add_sale_payments_sub()
	{
		$sale_pymnt_amount = $this->input->post('sale_pymnt_amount');
		$sale_id = $this->input->post('sale_id');
		$sale_pymnt_ref_no = $this->input->post('sale_pymnt_ref_no');
		$sale_pymnt_paying_by = $this->input->post('sale_pymnt_paying_by');
		$sale_pymnt_date_time = $this->input->post('sale_pymnt_date_time');
		$sale_pymnt_date_time_send = date('Y-m-d H:i:s', strtotime($sale_pymnt_date_time));
		$sale_pymnt_cheque_no = $this->input->post('sale_pymnt_cheque_no');
		$sale_pymnt_crdt_card_no = $this->input->post('sale_pymnt_crdt_card_no');
		$sale_pymnt_crdt_card_holder_name = $this->input->post('sale_pymnt_crdt_card_holder_name');
		$sale_pymnt_crdt_card_month = $this->input->post('sale_pymnt_crdt_card_month');
		$sale_pymnt_crdt_card_year = $this->input->post('sale_pymnt_crdt_card_year');
		$sale_pymnt_crdt_card_type = $this->input->post('sale_pymnt_crdt_card_type');
		$sale_type = $this->input->post('sale_payment_type');
		$acctrnss_id = $this->input->post('acctrnss_id');
		

		$b_id = $this->input->post('b_id');

		$sale_pymnt_note = $this->input->post('sale_pymnt_note');
		$user_id = $this->session->userdata('ss_user_id');
		$sale_pymnt_added_date_time = date("Y-m-d H:i:s");
		$sale_pymnt_id = '';

		$this->load->library('form_validation'); //form validation lib
		$this->form_validation->set_rules('sale_pymnt_amount', 'Amount', 'required');
		$this->form_validation->set_rules('sale_pymnt_ref_no', 'Reference No', 'required');
		if ($sale_pymnt_paying_by == 'Credit Card') {
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_type', 'Card Type', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_no', 'Credit Card No', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_holder_name', 'Holder Name', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_month', 'Month', 'required');
			//$this->form_validation->set_rules('sale_pymnt_crdt_card_year', 'Year', 'required');
		}
		if ($sale_pymnt_paying_by == 'Cheque') {
			$this->form_validation->set_rules('sale_pymnt_cheque_no', 'Cheque No', 'required');
		}
		$this->form_validation->set_rules('sale_id', 'System Error', 'required');


		if ($this->form_validation->run() == FALSE) {
			$st = array('status' => 0, 'validation' => validation_errors());
			echo json_encode($st);
		} else {
			$data = array(
				'sale_pymnt_amount' => $sale_pymnt_amount,
				'sale_pymnt_ref_no' => $sale_pymnt_ref_no,
				'sale_pymnt_paying_by' => $sale_pymnt_paying_by,
				'sale_pymnt_date_time' => $sale_pymnt_date_time_send,
				'sale_pymnt_note' => $sale_pymnt_note,
				'user_id' => $user_id,
				'sale_id' => $sale_id,
				'sale_pymnt_added_date_time' => $sale_pymnt_added_date_time,
				'sale_pymnt_cheque_no' => $sale_pymnt_cheque_no,
				'sale_pymnt_crdt_card_no' => $sale_pymnt_crdt_card_no,
				'sale_pymnt_crdt_card_holder_name' => $sale_pymnt_crdt_card_holder_name,
				'sale_pymnt_crdt_card_type' => $sale_pymnt_crdt_card_type,
				'sale_pymnt_crdt_card_month' => $sale_pymnt_crdt_card_month,
				'sale_pymnt_crdt_card_year' => $sale_pymnt_crdt_card_year,
				'sale_payment_type' => $sale_type,
				'extra_val_1' => $this->input->post('extra_val_1'),
				'service_charge_percentage' => $this->input->post('service_charge_percentage'),
				'acctrnss_id_p' => $acctrnss_id,
				//'bank_id'=>$b_id
			);

			if ($this->Sales_Model->save_sale_payments($data, $sale_pymnt_id)) {
				$st = array('status' => 1, 'validation' => 'Done!');
				echo json_encode($st);
			} else {
				$st = array('status' => 0, 'validation' => 'error occurred please contact your system administrator');
				echo json_encode($st);
			}
		}
	}
	
	//Sales save 
	//Sales item save
	//Add sales items to 54 table
	public function save_sales()
	{
		//$sale_reference_no=$this->input->post('sale_reference_no');
		// $query   		= $this->Sales_Model->get_next_ref_no();
        //$result  		= $query->row();
		$warehouse_id=$this->input->post('warehouse_id');
		$customer_id=$this->input->post('customer_id');
		$rowCount=$this->input->post('rowCount');
		$sale_pymnt_given_amount_cash=$this->input->post('sale_pymnt_given_amount');
		//$is_approve_requerd = $this->input->post('is_approve_requerd');
	//	$sale_pymnt_given_amount=$this->input->post('sale_pymnt_given_amount');
		
		//start get next referance no
		$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
		$warehouse_code=$warehouse_dtls['code'];
		$warehouse_last_id=(1+$this->Sales_Model->get_next_warehouse_ref_no($warehouse_id));
		$sale_reference_no =$warehouse_code.'/S/'.sprintf("%04d",$warehouse_last_id);
		//end get next referance no
        //  $sale_reference_no		= sprintf("%05d", $result->sale_id+1);
		
		$sale_datetime_1=$this->input->post('sale_datetime');
		$sale_datetime=date('Y-m-d H:i:s');//date('Y-m-d H:i:s', strtotime($sale_datetime_1));
		$tax_rate_id=$this->input->post('tax_rate_id');
		$sale_inv_discount=$this->input->post('sale_inv_discount');
		$sale_status=$this->input->post('sale_status');
		$payment_status=$this->input->post('payment_status');
		$sale_shipping=$this->input->post('sale_shipping');
		$sale_payment_term=$this->input->post('sale_payment_term');
		$sale_total=$this->input->post('sale_total');
		$sale_paid=floatval($this->input->post('sale_paid'));
		$sale_balance=$this->input->post('sale_balance');
		$cost_total=$this->input->post('cost_total');
		$in_type=$this->input->post('in_type');
		$sale_inv_discount_amount=$this->input->post('sale_inv_discount_amount');
		$sale_datetime_created=date('Y-m-d H:i:s');
		$sale_inv_rc=$this->input->post('sale_inv_rc');
		$sl_rtn_id=$this->input->post('sl_rtn_id');
		$sale_pymnt_amount=$this->input->post('sale_pymnt_amount');
		$sale_pymnt_paying_by=$this->input->post('sale_pymnt_paying_by');
		
		$sale_pymnt_amount_2=$this->input->post('sale_pymnt_amount_2');
		$service_charge_percentage_2=$this->input->post('service_charge_percentage_2');

		$payment_document_number=$this->input->post('payment_document_number');

		//echo "sale_pymnt_amount_2:".$sale_pymnt_amount_2;
		$sale_pymnt_paying_by_2=$this->input->post('sale_pymnt_paying_by_2');
		$is_phone_bill=$this->input->post('is_phone_bill');
		
		$sale_pymnt_amount_3=$this->input->post('sale_pymnt_amount_3');
		$sale_pymnt_amount_4=$this->input->post('sale_pymnt_amount_4');
		$koko_payment=$this->input->post('koko_payment');
		$SnapPay=$this->input->post('SnapPay');
		
		$item_name	=$this->input->post('item_name');
		$imei_number=$this->input->post('imei_number');
		$remarks	=$this->input->post('remarks');
		$tech_id	=$this->input->post('tech_id');
			$acctrnss_id=$this->input->post('acctrnss_id');
			
			$total_paid=floatval($sale_pymnt_amount)+floatval($sale_pymnt_amount_2)+$sale_pymnt_amount_3+$sale_pymnt_amount_4;
			
			$is_completed=0;
		if($sale_total==$total_paid){
		    $is_completed=1;
		}

		$is_approve_requerd = 0;

		//New
		$sale_pymnt_amount_other=$this->input->post('sale_pymnt_amount_other');
		$sale_pymnt_amount_other_2=$this->input->post('sale_pymnt_amount_other_2');
		$payment_document_charge=$this->input->post('payment_document_charge');
		
	//	echo "is_phone_bill:$is_phone_bill";
		
		
		//echo "sale_pymnt_amount:".$sale_pymnt_amount;
		
		$error='';
		$disMsg='';
		$lastid='';
		$sale_id='';
		
		if(!$error){
			$data=array(
				'sale_reference_no'=>$sale_reference_no,
				'warehouse_id'=>$warehouse_id,
				'customer_id'=>$customer_id,
				'warehouse_id'=>$warehouse_id,
				'sale_datetime'=>$sale_datetime,
				'tax_rate_id'=>$tax_rate_id,
				'sale_inv_discount'=>$sale_inv_discount,
				'sale_status'=>$sale_status,
				'payment_status'=>$payment_status,
				'sale_shipping'=>$sale_shipping,
				'sale_payment_term'=>$sale_payment_term,
				'sale_total'=>$sale_total,
				'sale_paid'=>$sale_paid,
				'cost_total'=>$cost_total,
				'sale_balance'=>$sale_balance,
				'in_type'=>$in_type,
				'sale_datetime_created'=>$sale_datetime_created,
				'sale_inv_discount_amount'=>$sale_inv_discount_amount,
				'rep_id'=>intval($this->input->post('rep_id')),
				'sale_inv_rc'=>$sale_inv_rc,
				'customer_po_no'=>$this->input->post('customer_po_no'),
				'warehouse_last_id'=>$warehouse_last_id,
				'user'=>$this->session->userdata('ss_user_id'),
				'sl_rtn_id'=>$sl_rtn_id,
				'is_phone_bill'=>$is_phone_bill,
				'item_name' => $item_name,
				'imei_number' => $imei_number,
				'remarks'	=> $remarks,
				'tech_id'	=> $tech_id,
				'acctrnss_id'=>$acctrnss_id,
				'sale_pymnt_given_amount_cash'=>$sale_pymnt_given_amount_cash,
				'is_completed'=>$is_completed,
				'payment_document_number' => $payment_document_number,
				'payment_document_charge' => $payment_document_charge,
				//'is_approve_requerd' => $is_approve_requerd,
			);
			$_insert=$this->Sales_Model->save_sales($data,$sale_id);
			$lastid=$this->db->insert_id();
			$sale_id=$lastid;
			//insert user activity
			$this->Common_Model->add_user_activitie("Added Sale, (Invoice No:$sale_reference_no)");
			$disMsg='Sale successfully added';
			
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_item=array();
			
		//	$tot_paid=$sale_pymnt_amount+$sale_pymnt_paying_by_2+sale_pymnt_amount_3;
			
			
			
			//$sale_pymnt_amount+$sale_pymnt_paying_by_2+sale_pymnt_amount_3;
			
			
			for($i=1; $i<=$rowCount; $i++){
				//echo "/ $rowCount , Test:".$row[$i]['product_id'][0];
				if(isset($row[$i]['product_id'][0]))
				{	
					$item_sale_price = 0;	
					$item_cost_price = 0;	
					
					
					

					
				$data_item=array(
					'sale_id'=>$sale_id,
					'product_id'=>$row[$i]['product_id'][0],
					//'product_sn'=>$row[$i]['product_sn'][0],
					'quantity'=>$row[$i]['qty'][0],
					'discount'=>$row[$i]['discount'][0],
					'unit_price'=>$row[$i]['unit_price'][0],
					'item_cost'=>$row[$i]['item_cost'][0],
					'unit_price'=>$row[$i]['unit_price'][0]+$row[$i]['item_price_p'][0],
					'discount_val'=>$row[$i]['discount_val'][0], 
					'gross_total'=>$row[$i]['gross_total'][0],
					'product_w'=>floatval($row[$i]['product_w'][0]),
					'w_id'=>floatval($row[$i]['w_id'][0]),
					'cost_admin_verified_user'=>floatval($row[$i]['cost_admin_verified_user'][0]),
					'cost_admin_verified'=>floatval($row[$i]['cost_admin_verified'][0])
				);
				$this->Sales_Model->save_sales_item($data_item);
				$itemid=$this->db->insert_id();
				
				//check serial no exists
				if($row[$i]['product_sn'][0])
				{
				//add serial numbers
				//exploid serial numbers
					$pieces_sn = explode(",", $row[$i]['product_sn'][0]);

					
 					



					for($h=0; $h<count($pieces_sn); $h++){

						$current_item_is_approve_requerd = 0;
						$sn_data=array(
							'product_id'=>$row[$i]['product_id'][0],	
							'product_w'=>$row[$i]['product_w'][0],	
							'sale_id'=>$sale_id,
							'sale_item_id'=>$itemid,
							'sis_number'=>$pieces_sn[$h],
						);
				  		$this->Sales_Model->save_sale_serial_numbers($sn_data);

						//Check cost > salling price
						$sn_des=$this->Sales_Model->get_serial_no_details_serial_no($pieces_sn[$h]);
				
						$item_sale_price = $row[$i]['gross_total'][0]/$row[$i]['qty'][0];
						$item_cost_price = $sn_des[0]->pis_cost_price;

						// print_r($sn_des);

						// print_r($item_sale_price);
						// die();

						//Coment for disble under cost aprove status 
						// if($item_sale_price < $item_cost_price){
						// 	$current_item_is_approve_requerd = 1;
						// 	if($is_approve_requerd == 0){
						// 		$is_approve_requerd = 1;
						// 	}
						// }
						
						
				//update grn serial number sold status
				$pis_number=$pieces_sn[$h];
				$sn_data=array(	
					'sale_inv_id'=>$sale_id,
					'pis_sold'=>1,
					'pis_transferred'=>0,
					'trnsfr_id'=>0,
					'pis_sales_return'=>0,
					'product_avalable'=>0,
					'avalable_warehouse_id'=>0,
				);
				
				$this->Purchases_Model->update_grn_serial_numbers($sn_data,$pis_number);
				
						
					}
                    //end add serial numbers
				}
				
				
				
				
				//insert user activity
				$this->Common_Model->add_user_activitie("Added Sale Item, (Id:$itemid)");
				
				//add reford for f4 table
				$type='sale';
				$ref_id=$sale_id;
				$product=$row[$i]['product_id'][0];
				$quantity=$row[$i]['qty'][0];
				$unit_cost=$row[$i]['unit_price'][0];
				$this->Common_Model->add_fi_table($type,$ref_id,$product,$quantity,$unit_cost);
				}
				
				
				
				
				
			}


			//Update is approved requed
			$data_approve=array(
				'is_approve_requerd' => $is_approve_requerd,
			);
			$_insert=$this->Sales_Model->save_sales($data_approve,$sale_id);
			
			
			//save sale payment start
				$data=array(
				'sale_pymnt_amount'=>str_replace(',', '', $sale_pymnt_amount),	
			//	'sale_pymnt_ref_no'=>$sale_pymnt_ref_no,
				'sale_pymnt_paying_by'=>$sale_pymnt_paying_by,
				'sale_pymnt_date_time'=>$sale_datetime,
			//	'sale_pymnt_note'=>$sale_pymnt_note,
				'user_id'=>$this->session->userdata('ss_user_id'),
				'sale_id'=>$sale_id,
				'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
			//	'sale_pymnt_cheque_no'=>$sale_pymnt_cheque_no,
				//'sale_pymnt_crdt_card_no'=>$sale_pymnt_crdt_card_no,
			//	'sale_pymnt_crdt_card_holder_name'=>$sale_pymnt_crdt_card_holder_name,
			//	'sale_pymnt_crdt_card_type'=>$sale_pymnt_crdt_card_type,
				//'sale_pymnt_crdt_card_month'=>$sale_pymnt_crdt_card_month,
				//'sale_pymnt_crdt_card_year'=>$sale_pymnt_crdt_card_year,
				'sale_payment_type' => 'sale',
				'acctrnss_id_p'=>$acctrnss_id,
			//	'extra_val_1' => ',
			);

			if($sale_pymnt_amount){
               $this->Sales_Model->save_sale_payments($data,'');
			}


			
			//Other payment type
			if($sale_pymnt_amount_other){
                 	$data=array(
					'sale_pymnt_amount'=>str_replace(',', '', $sale_pymnt_amount_other),	
					'sale_pymnt_paying_by'=>$this->input->post('sale_pymnt_paying_by_other'),
					'sale_pymnt_date_time'=>$sale_datetime,
					'user_id'=>$this->session->userdata('ss_user_id'),
					'sale_id'=>$sale_id,
					'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
					'sale_payment_type' => 'sale',
					'acctrnss_id_p'=>$acctrnss_id,
					'service_charge_percentage'=>$this->input->post('service_charge_percentage_other'),
					'sale_pymnt_ref_no'=>$this->input->post('sale_pymnt_cheque_no_1'),
				);  
				if ($this->Sales_Model->save_sale_payments($data,'')) {}
			}

			if($sale_pymnt_amount_other_2){
                 	$data=array(
					'sale_pymnt_amount'=>str_replace(',', '', $sale_pymnt_amount_other_2),	
					'sale_pymnt_paying_by'=>$this->input->post('sale_pymnt_paying_by_other_2'),
					'sale_pymnt_date_time'=>$sale_datetime,
					'user_id'=>$this->session->userdata('ss_user_id'),
					'sale_id'=>$sale_id,
					'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
					'sale_payment_type' => 'sale',
					'acctrnss_id_p'=>$acctrnss_id,
					'service_charge_percentage'=>$this->input->post('service_charge_percentage_other_2'),
					'sale_pymnt_ref_no'=>$this->input->post('sale_pymnt_cheque_no_2'),
				);  
				if ($this->Sales_Model->save_sale_payments($data,'')) {}
			}

			
				
				/* start 2nd payment */
				

				$data=array(
				'sale_pymnt_amount'=>str_replace(',', '', $sale_pymnt_amount_2),	
				'service_charge_percentage'=>$service_charge_percentage_2,
				'sale_pymnt_paying_by'=>$sale_pymnt_paying_by_2,
				'sale_pymnt_date_time'=>$sale_datetime,
				'credit_card_last_digits'=>$this->input->post('credit_card_last_digits'),
				'user_id'=>$this->session->userdata('ss_user_id'),
				'sale_id'=>$sale_id,
				'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
				'sale_payment_type' => 'sale',
				'sale_pymnt_crdt_card_type'=>$this->input->post('sale_pymnt_crdt_card_type'),
				'acctrnss_id_p'=>$acctrnss_id,
			);
			
			
			//print_r($data);
			if($sale_pymnt_amount_2)
			{
               if ($this->Sales_Model->save_sale_payments($data,'')) { }
			}
				/* end 2nd payment */
				
				
				
				/* start 3nd payment */
				$sale_pymnt_amount_3=str_replace(',', '', $this->input->post('sale_pymnt_amount_3'));
				$bank_id=$this->input->post('bank_id');
				$sale_pymnt_paying_by_3=$this->input->post('sale_pymnt_paying_by_3');
				$rea_date=date('Y-m-d H:i:s', strtotime($this->input->post('rea_date')));
				$data=array(
				'sale_pymnt_amount'=>$sale_pymnt_amount_3,	
				'bank_id'=>$bank_id,
				'sale_pymnt_paying_by'=>$sale_pymnt_paying_by_3,
				'sale_pymnt_date_time'=>$rea_date,
				'sale_pymnt_cheque_no'=>$this->input->post('sale_pymnt_cheque_no'),
				'user_id'=>$this->session->userdata('ss_user_id'),
				'sale_id'=>$sale_id,
				'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
				'sale_payment_type' => 'sale',
				'sale_pymnt_crdt_card_type'=>$this->input->post('sale_pymnt_crdt_card_type'),
				'acctrnss_id_p'=>$acctrnss_id,
			);
			
			
			//print_r($data);
			if($sale_pymnt_amount_3)
			{
               if ($this->Sales_Model->save_sale_payments($data,'')) { }
			}
				/* end 3nd payment */
				
				
					/* start 4nd payment */
				$sale_pymnt_amount_4=str_replace(',', '', $this->input->post('sale_pymnt_amount_4'));
				$b_id=$this->input->post('b_id_4');
				$sale_pymnt_paying_by_4=$this->input->post('sale_pymnt_paying_by_4');
				$rea_date=date('Y-m-d H:i:s', strtotime($this->input->post('rea_date')));
				$data=array(
				'sale_pymnt_amount'=>$sale_pymnt_amount_4,	
				'b_id'=>$b_id,
				'sale_pymnt_paying_by'=>$sale_pymnt_paying_by_4,
				'sale_pymnt_date_time'=>$rea_date,
				'sale_pymnt_note'=>$this->input->post('sale_pymnt_cheque_no_4'),
				'user_id'=>$this->session->userdata('ss_user_id'),
				'sale_id'=>$sale_id,
				'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
				'sale_payment_type' => 'sale',
				'sale_pymnt_crdt_card_type'=>"",
				'acctrnss_id_p'=>$acctrnss_id,
				'responsible'=>$this->input->post('responsible'),
				'ref_no_type'=>$this->input->post('ref_no_type'),
			);
			
			
			//print_r($data);
			if($sale_pymnt_amount_4)
			{
               if ($this->Sales_Model->save_sale_payments($data,'')) { }
			}
				/* end 4nd payment */
				
				//Koko payment
				
			
			
			//print_r($data);
			if($koko_payment)
			{

			// print_r($this->input->post());
			    
				$sale_pymnt_amount_5=str_replace(',', '', $this->input->post('sale_pymnt_amount_5'));
				$b_id=$this->input->post('b_id_4');
				$sale_pymnt_paying_by_4=$this->input->post('sale_pymnt_paying_by_5');
				$service_charge_percentage_5=$this->input->post('service_charge_percentage_5');
				$rea_date=date('Y-m-d H:i:s', strtotime($this->input->post('rea_date')));
				$koko_data=array(
    				'sale_pymnt_amount'=>str_replace(',', '', $koko_payment),	
    				'b_id'=>0,
    				'sale_pymnt_paying_by'=>'KOKO Payment',
    				'sale_pymnt_date_time'=>$rea_date,
    				'sale_pymnt_note'=>$this->input->post('sale_pymnt_cheque_no_5'),
    				'user_id'=>$this->session->userdata('ss_user_id'),
    				'sale_id'=>$sale_id,
    				'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
    				'sale_payment_type' => 'sale',
    				'sale_pymnt_crdt_card_type'=>"",
    				'acctrnss_id_p'=>$acctrnss_id,
    				'responsible'=>0,
    				'ref_no_type'=>'',
					'service_charge_percentage'=>$service_charge_percentage_5,
    			);
               if ($this->Sales_Model->save_sale_payments($koko_data,'')) { }
			}
			
			if($SnapPay)
			{
			    
				$sale_pymnt_amount_6=str_replace(',', '', $this->input->post('sale_pymnt_amount_6'));
				$b_id=$this->input->post('b_id_4');
				$sale_pymnt_paying_by_4=$this->input->post('sale_pymnt_paying_by_4');
				$service_charge_percentage_6=$this->input->post('service_charge_percentage_6');
				$rea_date=date('Y-m-d H:i:s', strtotime($this->input->post('rea_date')));
				$koko_data=array(
    				'sale_pymnt_amount'=>$SnapPay,	
    				'b_id'=>0,
    				'sale_pymnt_paying_by'=>'SnapPay',
    				'sale_pymnt_date_time'=>$rea_date,
    				'sale_pymnt_note'=>$this->input->post('sale_pymnt_cheque_no_6'),
    				'user_id'=>$this->session->userdata('ss_user_id'),
    				'sale_id'=>$sale_id,
    				'sale_pymnt_added_date_time'=>date("Y-m-d H:i:s"),
    				'sale_payment_type' => 'sale',
    				'sale_pymnt_crdt_card_type'=>"",
    				'acctrnss_id_p'=>$acctrnss_id,
    				'responsible'=>0,
    				'ref_no_type'=>'',
					'service_charge_percentage'=>$service_charge_percentage_6,
    			);
               if ($this->Sales_Model->save_sale_payments($koko_data,'')) { }
			}
				
				
			//havlock city 
			
			if($this->session->userdata('ss_warehouse_id')==21){
			    
                $customer_phone =  $this->Customer_Model->get_customer_phone($customer_id);
                $cpone = '';
                if($customer_phone){
                    $cpone = $customer_phone;
                }
                
    
                $paidByCard = ($sale_pymnt_amount_2)?floatval($sale_pymnt_amount_2):0;
                $cardBank = ($this->input->post('bank_code'))?$this->input->post('bank_code'):"";
                $cardCategory = ($paidByCard > 0) ?"Debit":"";
                $sale_pymnt_crdt_card_type = $this->input->post('sale_pymnt_crdt_card_type');
                if($sale_pymnt_crdt_card_type=='Discover'){
                    $sale_pymnt_crdt_card_type = 'OTHER';
                }
                $cardType = ($paidByCard > 0) ?strtoupper($sale_pymnt_crdt_card_type):"";
                $api_data = array(
                    "customerMobileNo" => $cpone,
                    "invoiceType" => "Sale",
                    "invoiceNo" => $sale_reference_no,
                    "invoiceDate" => date('d/m/Y H:i:s'),
                    "invoiceDate2" => date('Y-m-d H:i:s'),
                    "totalInvoice" => floatval($sale_total),
                    //"totalTax" => 444.4400,
                    "totalDiscount" => ($sale_inv_discount_amount)?floatval($sale_inv_discount_amount):0,
                    /*
                    "totalGiftVoucherSale" => 5000.00,
                    "totalGiftVoucherTax" => 351.85,
                    "totalGiftVoucherDiscount" => 250.00,
                    */
                    "paidByCash" => ($sale_pymnt_amount && $sale_pymnt_paying_by=='Cash')?floatval($sale_pymnt_amount):0.00,
    
                    "paidByCard" => $paidByCard,
                    "cardBank" => $cardBank,
                    "cardCategory" => $cardCategory,
                    "cardType" => $cardType,
                    //"GiftVoucherBurn" => 1000.00,
                    //"hcmLoyalty" => 500.00,
                    //"tenantLoyalty" => 250.00,
                    "creditNotes" => 0.00,
                    "otherPayments" => 0.00
                );
                //echo '<pre>',print_r($api_data); die();
                //$return_code = $this->Sales_Model->send_api($api_data);
                //echo $return_code;
                //$sale_update = array('api_code' => $return_code);
                $this->Sales_Model->save_sales($sale_update, $lastid);
            
			}
				
				
				//end sale payment
		
		}else {
			
			$disMsg='Please select these before adding any product:'.$disMsg;
		}	
		
		$this->session->set_flashdata('message', 'Sale successfully added!');
		
		
		/* Start Send SMS  */
		
		$cus_name='';
		    $phonenumber='';
		    $msg='';
		if($customer_id!=1){
		    
		$customer_details=$this->Customer_Model->get_customer_info($customer_id);
				 $cus_name=$customer_details['cus_name'];
				 //$sale_reference_no=$sale_des['sale_reference_no'];
				 $phonenumber=$customer_details['cus_phone'];
				 $s_inv_no=$sale_reference_no;
				 
				 
				 $sale_total=number_format($sale_total, 2, '.', ',');
				 
				//  $msg="Dear $cus_name, \\nInvoice No : $s_inv_no \\nAmount Rs. $sale_total \\n \\nPlease visit our website for online orders : http://www.lasermobile.lk \\nLike us & follow on facebook for special offers : http://www.facebook.com/LaserMobile \\nContact us for flash home deliveries on 0717844988 or 0777844988. \\n \\nThank You For Your Business. Please Come Again. \\n \\nLaser Mobile Technology (Pvt) Ltd.  \\nAthurugiriya. \\nLiberty Plaza.";
				 
				//   $this->Common_Model->send_sms($msg,$phonenumber);

					$encoded_id = urlencode(base64_encode($sale_id));
					$url = $_SERVER['HTTP_HOST'];

					$msg="Hello, \\n
						Thank you for order with The SmartPhone Shop. \\n
						View your bill here: \\n
						https://$url/sales/ebill/$encoded_id \\n \\n
						This URL expires in 14 days.  \\n
						Ref: $s_inv_no.";

						//echo $msg; die();

					// Hello,
					// Thank you for shopping with Sriyani Dress Point.
					// View your bill here:
					// http://ebill.sriyanidresspoint.lk/?receiptno=6N3v81VCOAEI6wnPcOeeQ 

					// This URL expires in 14 days
				 
				//$this->Common_Model->send_sms($msg,$phonenumber);
				//$message="Thank you $cus_name payment of LKR $tot_paid in respect of The SmartPhone Shop \nInv no : $sale_reference_no";

				//Start Send SMS Start
				//$this->sms_model->send_sms($phonenumber, $msg);

				$formatted_number = $phonenumber; // smart phone
				$sale_datetime =  date('Y-m-d'); 
				$reference_no = '';
				$sale_pymnt_amount = '';
				//$message = "Test";

				$sale_id = $sale_id;
				$s_inv_no = '';
				$encoded_id = urlencode(base64_encode($sale_id));
				$url = $_SERVER['HTTP_HOST'];

				$now_date_time = date("Y-m-d H:i:s");

				//echo "<br/> $now_date_time <br/> ";

				$message = "Hi, ";
				$message .= "Thanks for your order!.\n";
				$message .= "View your bill here:\n";
				$message .= "https://$url/sales/ebill/$encoded_id\n\n";
				$message .= "This URL expires in 14 days.\n";
				//$message .= "Ref: $s_inv_no.";
				//$message .= "\n $now_date_time";

				$response = [];
				$response = $this->sms_model->send_sms($formatted_number, $message);

				//End Send SMS Start
				  
				//$this->Common_Model->send_sms($msg,'0714617137');
				 
		}else{
			//echo "w cus";
			//die();
		}
		
		
		/* End SMS Send */
		
		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg, 'is_approve_requerd'=> $is_approve_requerd));
	}
	
		public function error()
	{
	    $data['sales'] = array();
	    $this->load->view('error',$data);
	}
	

	//Sales reference no jenarate	
	public function get_next_ref_no(){
		$query=$this->Sales_Model->get_next_ref_no();
		$result = $query->row();
		//print_r($result);
		$sale_reference_no=sprintf("%05d", $result->sale_id+1);
		$sale_reference_no=$sale_reference_no;
		echo json_encode(array('sale_reference_no'=>$sale_reference_no));
	}


	public function get_cus_tot_credit($cus_id){
		//$query=$this->Sales_Model->get_next_ref_no();
		//$result = $query->row();
		//print_r($result);
		$totals_cus_credit=$this->Sales_Model->get_cus_tot_credit($cus_id);
		$totals_cus_paid_amount=$this->Sales_Model->get_cus_paid_amount($cus_id);
		$totals_cus_return_paid_amount=$this->Sales_Model->get_cus_return_amount($cus_id);
		$cus_balance=$totals_cus_credit-$totals_cus_paid_amount-$totals_cus_return_paid_amount;
		$cus_balance=$cus_balance;
		echo json_encode(array('totals_cus_credit'=>$cus_balance));
	}
	
		
	//Sales ger avalable product qty
	public function get_avalable_product_qty(){
		$product_id=$this->input->get('product_id');
		$warehouse_id=$this->input->get('warehouse_id');
		$new_qty_val=$this->input->get('new_qty_val');
		$data['total']=$this->get_avalable_product_qty_by_product_id_and_warehouse_id($product_id,$warehouse_id);
		//$data['total']=$this->Sales_Model->get_avalable_product_qty($product_id,$warehouse_id);
		echo json_encode(array('remmnaingQty'=>$data['total'],'new_qty_val'=>$new_qty_val));
	}
	
	public function get_avalable_product_qty_by_product_id_and_warehouse_id($product_id,$srh_warehouse_id){
		//quantity for label
				$quantity =0;
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$purchased_qty=0;
				$sales_return_qty=0;
				$product_damaged_qty=0;
				$sold_qty=0;	
				
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($srh_warehouse_id,$product_id);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($srh_warehouse_id,$product_id);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($srh_warehouse_id,$product_id);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($srh_warehouse_id,$product_id);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($srh_warehouse_id,$product_id);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($srh_warehouse_id,$product_id);
				$quantity = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 0, '.', '');
				//echo "$quantity";
			//end qty for label
		return $quantity;
	}

	//Sales add form
    public function add_sales()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'add_sales';
		
		//updat paid status
	//	$this->get_list_sales_for_manual();
		
		//get suppliers list
		$data['suppliers'] = $this->Supplier_Model->get_all_supplier();
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['tax_rates_list'] = $this->Tax_Rates_Model->get_all_tax_rates();
		$data['customer_list'] = array();//$this->Customer_Model->get_all_customers();
		$data['status_list'] = $this->Common_Model->get_all_status();
		$data['rep_list'] = $this->User_Model->getSalesRep();
		$data['bank_list'] = $this->Sales_Model->get_all_bank();
			$data['w_data'] = $this->Sales_Model->get_warranty_types();
			
			$data['bank_details'] = $this->Supplier_Multiple_Payment_Model->get_all_bank_accounts();
			
		$sl_rtn_id=$this->uri->segment('3');
		$data['sl_rtn_id'] = $sl_rtn_id;
		
		
		$data['sale_rtn_details']=array();
		
		if(isset($sl_rtn_id)){
			//$data['sale_rtn_item_list']= $this->Sales_Return_Model->get_sale_return_item_list($sl_rtn_id);
			$data['sale_rtn_details']= $this->Sales_Return_Model->get_sale_return_info($sl_rtn_id);
		}
		
		$data['category_list'] 	= $this->category_models->getCategory();
		
        $this->load->view('add_sales',$data);
    }
	
	//Sales product items get
	 public function suggestions($value='')
    {
		
		//print_r($_GET);
		$term=$this->input->get('term');
		$in_type=$this->input->get('t');
		$cus_type=$this->input->get('cus_type');
		$city_id=$this->input->get('city_id');
		$cat_id=$this->input->get('cat_id');
		$srh_warehouse_id=$this->input->get('srh_warehouse_id');
		$cat_id=$this->input->get('cat_id');
		$manual_search= '';//$this->input->get('manual_search');
		
//	echo $status;	
		//if()
		if($cus_type == 'Special' && $in_type=='Wholesale'){
//		if enabled
		
		$result = $this->Country_Model->get_area_info_by_id($city_id);
		$status = $result[0]['status'];

		if($status == 1){
		//$data['sales'] = $this->Cus_Pricing_Model->get_products_suggestions_sale($term,$city_id);
		//$data['sales'] = $this->Sales_Model->get_products_suggestions($term);
		}
		
		else {
		//$data['sales'] = $this->Sales_Model->get_products_suggestions($term);
		}//end if
		
		}
		else if($cus_type == 'Normal'){
		//$data['sales'] = $this->Sales_Model->get_products_suggestions($term);
 	}
	
	
	$data['sales'] = $this->Sales_Model->get_products_suggestions($term,$cat_id,$srh_warehouse_id);
		
	//print_r($data['sales']);
	$pis_cost_price = "";
		$json = array();
		$json_itm=array();
		foreach ($data['sales'] as $row)
		{
			//set price
			$price_tmp=0;
			if($in_type=='Wholesale'){
			$price_tmp=floatval($row['wholesale_price']);
			}else {
			$price_tmp=$row['product_price'];
			}

			$pis_cost_price = $row['pis_cost_price'];;
			
			
			$price_tmp_sn='';
			$price_tmp_sn=$row['pis_cash_price'];
			if($price_tmp_sn){
				$price_tmp=$price_tmp_sn;
				
			}else{
				$price_tmp=$price_tmp;
			}
			
		//	echo "price_tmp:".$price_tmp;
			
		//	$price_tmp=$row['product_price'];
			//quantity for label
				$quantity =0;
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$purchased_qty=0;
				$sales_return_qty=0;
				$product_damaged_qty=0;
				$sold_qty=0;
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$quantity = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 2, '.', ',');
			//end qty for label
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_sn=$row['pis_number'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_w=$row['product_w'];
			$product_sn_exissts=$row['product_sn_exissts'];
			$product_price=$price_tmp;
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			//$extraName.=", Serial No: $product_sn";

			$item_cost_display = '';
			if ($this->session->userdata('ss_group_id')== 1 || $this->session->userdata('ss_group_id')== 3){
				$item_cost_display = ", Cost: " .number_format($pis_cost_price, 2, '.', ',');
			}
			

			$extraName.= $item_cost_display . " Price: ".number_format($product_price, 2, '.', ',').", Qty. :".$quantity;			
			
			$is_search_by_sn=0;
			if($row['pis_number']==$term){
				$is_search_by_sn=1;
			}
			
			//product have serial no get grn item serial table cost, val empty set def val
			//if($product_sn_exissts){
				//get cost by sn
				//	get_serial_no_supp_id($sn='');
				
			//}
			
			$json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $product_price,
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'product_sn'=> $row['pis_number'],
					'pis_cost_price'=> $row['pis_cost_price'],
					'product_w'=> $product_w,
					'product_sn_exissts'=> $product_sn_exissts,
					'is_search_by_sn'=> $is_search_by_sn,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName | SN: $row[pis_number]"
                    );
					
					//echo "Test:";
					array_push($json,$json_itm);	
					
		}	
		
		
		
		
		$data['sales_non_seril'] = $this->Sales_Model->get_non_serial_products_suggestions($term,$cat_id);
		
		foreach ($data['sales_non_seril'] as $row)
		{
			//set price
		//	$price_tmp=0;
			
		//	$price_tmp=$row['product_price'];
		$price_tmp=0;
			if($in_type=='Wholesale'){
			$price_tmp=floatval($row['wholesale_price']);
			}else {
			$price_tmp=$row['product_price'];
			}
			//quantity for label
				$quantity =0;
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$purchased_qty=0;
				$sales_return_qty=0;
				$product_damaged_qty=0;
				$sold_qty=0;	
				
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$quantity = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 0, '.', ',');
			//end qty for label
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_sn='';
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_w='';//need check
			$product_price=$price_tmp;
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			if($product_sn){
				//$extraName.=", Serial No: $product_sn";
			}
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',')." ,Qty. :".$quantity;			
			
			//$json_itm=array();
			//if($srh_warehouse_id!=2){//not smart phone maharagama
			
			$add_details=0;
			
		//	if($quantity){
			///	$add_details=1;
		//	}
		
		
		if($quantity){
		        $add_details=1;
		    }

		if($srh_warehouse_id==9 || $srh_warehouse_id==10 || $srh_warehouse_id==11 || $srh_warehouse_id==13)
			{
		    if($quantity){
		        $add_details=1;
		    }
		    
		}else /*{
		    $add_details=1;
		}*/
		if($srh_warehouse_id == 15){
			if($term == "111111"){
				 $add_details=1;
			}else if($term == "222222"){
				$add_details=1;
			}
		}
		
			
			if($add_details)
			{
			$json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $price_tmp,
					'product_part_no'=> $row['product_part_no'],
					'pis_cost_price'=> $row['product_cost'],
					'product_sn'=> $product_sn,
					'product_w'=> $product_w,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"
                    );
					array_push($json,$json_itm);
			}
			//}
					
		}
		
		
		
		
		echo json_encode($json);		
    }
	
	//Sale details page
	public function sale_details()
	{
		//echo "Test";
		 error_reporting( E_ALL );
		$sale_type = 0;
		$sale_id=$this->input->get('sale_id');
		$sale_type = $this->input->get('type');
		//echo ",5";
		$data['sale_details']= $this->Sales_Model->get_sale_info($sale_id);
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		
	//	echo ",6";
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
		//get old payments amounts
		$cus_sales_details=array();
	//	$cus_sales_details=$this->Sales_Model->get_sale_info_by_customer_id($data['sale_details']['customer_id']);
		//print_r($cus_sales_details);
		$old_payment_tot=0;
		$retured_payment_tot=0;
		$retured_payment_msg_this='';
		$old_payments_dis_msg_this='';
		
	//	echo ",7";
		
		//check return payments
		$return_sales_details=array();//$this->Sales_Return_Model->get_return_sale_info_sale_id($sale_id);
		
		
		
		
		//$old_payment_tot=$old_payment_tot-$retured_payment_tot;
		
		$data['old_payments']=0;//$old_payment_tot;
		$data['old_payments_dis_msg']="";//"Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";
		
		
		$data['cr_limit_list'] = array();//$this->Common_Model->get_all_cr_limit();
		
		/* get return invocie details */
	//	echo "Test 1.1";
		$sl_rtn_id=$data['sale_details']['sl_rtn_id'];
		$data['sale_rtn_item_list']=array();
		$data['sale_rtn_details']=array();
		
		//echo "Test 2";
		
		if(isset($sl_rtn_id)){
			$data['sale_rtn_item_list']= $this->Sales_Return_Model->get_sale_return_item_list($sl_rtn_id);
			$data['sale_rtn_details']= $this->Sales_Return_Model->get_sale_return_info($sl_rtn_id);
		}

		$data['is_print'] = 1;
		
		/* get return invocie details  */ 
		
		//echo "Test 3";
		
        $this->load->view('models/view_sales',$data);
	}	
	
	
	
	
	//Sale details page
	public function sale_details_ser()
	{
		$sale_type = 0;
		$sale_id=$this->input->get('sale_id');
		$sale_type = $this->input->get('type');
		$data['sale_details']= $this->Sales_Model->get_sale_info($sale_id);
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
		//get old payments amounts
		$cus_sales_details=$this->Sales_Model->get_sale_info_by_customer_id($data['sale_details']['customer_id']);
		//print_r($cus_sales_details);
		$old_payment_tot=0;
		$retured_payment_tot=0;
		$retured_payment_msg_this='';
		$old_payments_dis_msg_this='';
		
		foreach ($cus_sales_details as $row)
		{
	 		//echo "sale id:$row->sale_id";
			//echo "sale_total:$row->sale_total";
			if($row->sale_id!=$sale_id){
			//get paid amount
			$paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($row->sale_id);
			if($row->sale_total!=$paid_amount){
				//$this_balance_pament=$row->sale_total-$paid_amount;
				//$old_payment_tot=$old_payment_tot+$this_balance_pament;
				//echo "sale_total:$row->sale_total , ";
				//$old_payments_dis_msg_this=$old_payments_dis_msg_this.''.$this_balance_pament.' ,';
			}
			}
 		}
		
		//check return payments
		$return_sales_details=$this->Sales_Return_Model->get_return_sale_info_sale_id($sale_id);
		
		
		foreach ($return_sales_details as $row)
		{
	 		//echo "sale id:$row->sale_id";
			//echo "sale_total:$row->sale_total";

				$this_balance_pament=0;
				$this_trn_amt=$row->sl_rtn_total;
				$retured_payment_tot=$retured_payment_tot+$this_trn_amt;

				$retured_payment_msg_this=$retured_payment_msg_this.' -'.$this_trn_amt.' ,';
			
			
 		}
		
		
		$old_payment_tot=$old_payment_tot-$retured_payment_tot;
		
		$data['old_payments']=$old_payment_tot;
		$data['old_payments_dis_msg']="Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";
		$data['total_sales']=array();
		$data['total_return']=array();
		$data['total_payments']=array();
		//BF calculation
		if ($data['sale_details']['customer_id'] != 1){
            $data['total_sales'] = $this->Sales_Model->get_all_sales_for_view($data['sale_details']['warehouse_id'], $data['sale_details']['customer_id']);
		
            $data['total_return'] = $this->Sales_Model->get_all_sales_return_for_view($data['sale_details']['warehouse_id'], '', '', $data['sale_details']['customer_id']);

        $data['total_payments'] = $this->Sales_Model->getPaymentsForView($data['sale_details']['warehouse_id'], '', '', 'sale', 'Return_Cash', '', $data['sale_details']['customer_id']);
		}
		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
        $this->load->view('models/view_sales_ser',$data);
	}	
	
	
	
		
	//Sale details page
	public function sale_details_ser_2()
	{
	    
	    
	    	    
	    	    
		$sale_type = 0;
		$sale_id=$this->input->get('sale_id');
		$sale_type = $this->input->get('type');
		$data['sale_details']= $this->Sales_Model->get_sale_info($sale_id);
		
		
			
			
			
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		
	
		$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
		//get old payments amounts
		$cus_sales_details=array();//$this->Sales_Model->get_sale_info_by_customer_id($data['sale_details']['customer_id']);
		//print_r($cus_sales_details);
		$old_payment_tot=0;
		$retured_payment_tot=0;
		$retured_payment_msg_this='';
		$old_payments_dis_msg_this='';
		
		
		/*
		foreach ($cus_sales_details as $row)
		{

			if($row->sale_id!=$sale_id){

			$paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($row->sale_id);
			if($row->sale_total!=$paid_amount){

			}
			}
 		}
 		*/
		
		//check return payments
		$return_sales_details=$this->Sales_Return_Model->get_return_sale_info_sale_id($sale_id);
		
		/*
		foreach ($return_sales_details as $row)
		{
	 	
				$this_balance_pament=0;
				$this_trn_amt=$row->sl_rtn_total;
				$retured_payment_tot=$retured_payment_tot+$this_trn_amt;

				$retured_payment_msg_this=$retured_payment_msg_this.' -'.$this_trn_amt.' ,';
			
			
 		}
		*/
		
		$old_payment_tot=$old_payment_tot-$retured_payment_tot;
		
		$data['old_payments']=$old_payment_tot;
		$data['old_payments_dis_msg']="Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";
		$data['total_sales']=array();
		$data['total_return']=array();
		$data['total_payments']=array();
		//BF calculation
		if ($data['sale_details']['customer_id'] != 1){
            $data['total_sales'] = $this->Sales_Model->get_all_sales_for_view($data['sale_details']['warehouse_id'], $data['sale_details']['customer_id']);
		
            $data['total_return'] = $this->Sales_Model->get_all_sales_return_for_view($data['sale_details']['warehouse_id'], '', '', $data['sale_details']['customer_id']);

        $data['total_payments'] = $this->Sales_Model->getPaymentsForView($data['sale_details']['warehouse_id'], '', '', 'sale', 'Return_Cash', '', $data['sale_details']['customer_id']);
		}
		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
		
		
		if ($data['sale_details']['customer_id'] != 1){
		     $this->load->view('models/view_sales_ser_2',$data);
		}else{
		    
		    $this->load->view('models/view_sales_ser_2',$data);
		}
       
	}	
	
	
		public function sale_details_ser_3()
	{
			$sale_type = 0;
		$sale_id=$this->input->get('sale_id');
		$sale_type = $this->input->get('type');
		$data['sale_details']= $this->Sales_Model->get_sale_info($sale_id);
		$data['sale_type'] = $sale_type;
		//get sale item list
		$data['sale_item_list']= $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['sale_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['sale_details']['warehouse_id']);
		$data['sale_payments_list']= $this->Sales_Model->get_sale_payments_by_sale_id($sale_id);
		
		//get old payments amounts
		$cus_sales_details=$this->Sales_Model->get_sale_info_by_customer_id($data['sale_details']['customer_id']);
		//print_r($cus_sales_details);
		$old_payment_tot=0;
		$retured_payment_tot=0;
		$retured_payment_msg_this='';
		$old_payments_dis_msg_this='';
		
		
		/*
		foreach ($cus_sales_details as $row)
		{

			if($row->sale_id!=$sale_id){

			$paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($row->sale_id);
			if($row->sale_total!=$paid_amount){

			}
			}
 		}
 		*/
		
		//check return payments
		$return_sales_details=$this->Sales_Return_Model->get_return_sale_info_sale_id($sale_id);
		
		/*
		foreach ($return_sales_details as $row)
		{
	 	
				$this_balance_pament=0;
				$this_trn_amt=$row->sl_rtn_total;
				$retured_payment_tot=$retured_payment_tot+$this_trn_amt;

				$retured_payment_msg_this=$retured_payment_msg_this.' -'.$this_trn_amt.' ,';
			
			
 		}
		*/
		
		$old_payment_tot=$old_payment_tot-$retured_payment_tot;
		
		$data['old_payments']=$old_payment_tot;
		$data['old_payments_dis_msg']="Return Total Amount ($old_payments_dis_msg_this $retured_payment_msg_this)";
		$data['total_sales']=array();
		$data['total_return']=array();
		$data['total_payments']=array();
		//BF calculation
		if ($data['sale_details']['customer_id'] != 1){
            $data['total_sales'] = $this->Sales_Model->get_all_sales_for_view($data['sale_details']['warehouse_id'], $data['sale_details']['customer_id']);
		
            $data['total_return'] = $this->Sales_Model->get_all_sales_return_for_view($data['sale_details']['warehouse_id'], '', '', $data['sale_details']['customer_id']);

        $data['total_payments'] = $this->Sales_Model->getPaymentsForView($data['sale_details']['warehouse_id'], '', '', 'sale', 'Return_Cash', '', $data['sale_details']['customer_id']);
		}
		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
        $this->load->view('models/view_sales_ser_3',$data);
	}	

	
  public function update_sale_status()
  {
    //print_r($this->input->post());
    $sale_id = $this->input->post('sale_id_s');

    //echo "sale_id:$sale_id";
    $type = 'sale'; //$this->input->get('type');

    $disMsg = '';
    $prepared_user = 0;
    $checked_user = 0;
    $approved_user = 0;
    $reserved_user = 0;
    $authorized_user = 0;


    $printed_date = '';
    $reviewed_status = 0;
    $reviewed_user = '';

    $approved_status = $this->input->post('approved_status');

    //if($this->input->post('reviewed_status')=='Reviewed')  
    $approved_user = $this->session->userdata('ss_user_id');


    //echo $prepared_user;
    $data_edit = array();
    if ($type == 'sale') {
      $data_edit = array(
        'approved_status' => $this->input->post('approved_status'),
        'approved_user' => $approved_user,
        'approved_date' => date("Y-m-d H:i:s"),
      );
    }


    $_insert = $this->Sales_Model->save_sales($data_edit, $sale_id);
	// echo $this->db->last_query();

    //echo "approved_status:$approved_status";

    //update serial no transer status
    if ($approved_status) {
      $sale_details = $this->Sales_Model->get_sale_info($sale_id);
      //echo "trnsfr_to_warehouse_id:".$trnsfr_details['trnsfr_to_warehouse_id'];
      //print_r($trnsfr_details);
      $sale_item_list = $data['sale_item_list'] = $this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
      if ($approved_status) {
        foreach ($sale_item_list as $row) {
          $sn_list = $this->Sales_Model->get_sales_serial_by_id($sale_id, $row['id']);
          if (!empty($sn_list)) {

            //print_r($sn_list);

            foreach ($sn_list as $sn) {
              //	echo "<br/> Serial No. ";
              //	echo "($sn->sis_number) , ";
              //update grn status
              //update grn serial number sold status
              $product_avalable = 1;
              //echo " <br/> reviewed_status:$reviewed_status";
              if ($approved_status == 'Approved') {
                //$avalable_warehouse_id=$trnsfr_details['trnsfr_to_warehouse_id'];
                $sn_data = array(
                  'product_avalable' => 0,
                  //'avalable_warehouse_id'=>$avalable_warehouse_id,
                );
              } else if ($approved_status == 'Rejected') {
                $sn_data = array(
                  'product_avalable' => 1,
                  'avalable_warehouse_id' => $sale_details['warehouse_id'],
                );
              }

              //print_r($sn_data);
              $pis_number = $sn->sis_number;
              $this->Purchases_Model->update_grn_serial_numbers($sn_data, $pis_number);
            }
          }
        }
      }
      //else if($reviewed_status=='Rejected'){

      //}
    }



    //end update serial no transer status

    //echo $this->db->last_query();

    echo json_encode(array('req_id' => $sale_id, 'error' => '', 'disMsg' => $disMsg,));
  }

	
	
	//Sales list
	public function list_sales()
	{
	$requestData=$this->input->get();
	
	$search_key=$this->input->get('search');
	$warehouse_id=$this->input->get('warehouse_id');
	$search_key1=$this->input->get('search_key1');
	$shift_id=$this->input->get('shift_id');
	$in_type = $this->input->get('in_type');
	//echo "warehouse_id:$warehouse_id";
	
	//print_r($search_key);
	//echo $search_key['value'];
	$search_key_val=$search_key['value'];
	$start=$this->input->get('start');
	$length=$this->input->get('length');

	if ($this->session->userdata('ss_group_id')==2){
		$length= 3; //Sales staff
	}
	$columns = array( 
		0 =>'sale_id', 
		1 => 'sale_reference_no',
		2=> 'sale_id',
		3 =>'sale_id', 
		4 => 'sale_id',
		5=> 'sale_id'
	);
	
	$data = array();
	$sales_tot =$this->Sales_Model->get_all_sales("","","","","",$warehouse_id,$search_key1,$shift_id, $in_type);
	///$sales_tot =5000;
	$sales = $this->Sales_Model->get_all_sales($start,$length,$search_key_val,"","",$warehouse_id,$search_key1,$shift_id, $in_type);
	
	$totalData = ($sales_tot);
	$totalFiltered = $totalData;  
	
	foreach ($sales as $row){
		$nestedData=array(); 
		$sale_id=$row['sale_id'];
		$total_paid_amount=0;
		$total_paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($sale_id);
		$return_tot_amt=0;
		$return_tot_amt=$this->Sales_Return_Model->get_total_return_by_sale_id($sale_id);
		$tot_si_amount=$this->Sales_Model->get_total_interest_by_sale_id($sale_id);
		$rep_name='';
		if(!empty($row['rep_id'])){
		$rep_info=$this->User_Model->get_user_info($row['rep_id']);
		//echo $this->db->last_query();
		//print_r($rep_info);
		$rep_name=$rep_info['user_first_name'];
		}
		
		//get return invocie paid amount
		$sls_rtn_total_paid=0;
		if($row['sl_rtn_id']){
		$sale_rtn_details=$this->Sales_Return_Model->get_sale_return_info($row['sl_rtn_id']);
		$sls_rtn_total_paid=$sale_rtn_details['sls_rtn_total_paid'];
		}
		
		$to_be_paid=$row['sale_total']-$return_tot_amt+$tot_si_amount;
		$nestedData[] =display_date_time_format($row['sale_datetime']);
		$nestedData[] = $row['sale_reference_no'];
		$nestedData[] = $row['cus_name'];
		$nestedData[] = $row['cus_phone'];
		$nestedData[] = $rep_name;
		/*
		$nestedData[] = number_format($row['sale_total'], 2, '.', ',');
		$nestedData[] = number_format($total_paid_amount, 2, '.', ',');
		$nestedData[] = number_format($row['sale_total']-$total_paid_amount, 2, '.', ',');
		*/
		$nestedData[] = $row['sale_total'];
		$nestedData[] = $return_tot_amt;
		$tot_si_amount_des='';
		
		$total_paid_amount=$total_paid_amount+$sls_rtn_total_paid;
		//if($row['current_interest']!=0.00) 
		//$tot_si_amount_des="$row[current_interest] + ";
		 
		$tot_si_amount_des=$row['current_interest']+$tot_si_amount;
		$nestedData[] =$tot_si_amount_des;
		$nestedData[] = number_format($to_be_paid, 2, '.', '');
		$nestedData[] = $total_paid_amount;
		
		$nestedData[] = $to_be_paid-$total_paid_amount;
		
		
		/*
		if($row['payment_status']=='Paid') {
			$nestedData[]='<span class="label label-sm label-success">'.$row['payment_status'].'</span>'; 
		}else {
			$nestedData[]=$row['payment_status'];
		}
		*/
		if (empty($total_paid_amount)) {
		  $pay_st = '<span class="label label-warning">Pending</span>';
		}else{
		  if ($total_paid_amount >= $to_be_paid) {
			$pay_st = '<span class="label label-success">Paid</span>';
		  }else{
			$pay_st = '<span class="label label-info">Partial</span>';
		  }
		}
		
		$nestedData[]=$pay_st;
		
		
		//$nestedData[] = $row['sale_id'];
		$actionTxtDisble='';
		$actionTxtEnable='';
		$actionTxtUpdate='';
		$actionTxtDelete='';
		
		$url=base_url("sales/sale_details?sale_id=$sale_id");
		$actionTxtUpdate='<a onClick="fbs_click('.$row['sale_id'].')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="clip-zoom-in-2"></i></a> &nbsp;';
		
		$actionTxtViewDetails='<a href="'.base_url().'sales/view/'.$sale_id.'" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-file-text-o"></i></a> &nbsp;';
		
		$nestedData[] = '<div class="btn-group text-left">
								<button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
								<ul role="menu" class="dropdown-menu pull-right">
								<li><a href="'.base_url().'sales/view/'.$sale_id.'"><i class="fa fa-file-text-o"></i> Sale Details</a></li>
							
								
								 <!--<li><a href="#" onClick ="delete_invoice('.$row['sale_id'].')"><i class="fa fa-trash-o"></i></i> Delete</a></li>-->
								</ul></div>';
		
		$data[] = $nestedData;
	}
	
	/*
		<li><a onClick="fbs_click('.$row['sale_id'].')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Sale</a></li>
		
		 <li><a href="'.base_url().'sales_return/sales_return_add/'.$sale_id.'"><i class="fa fa-angle-double-left"></i></i> Return Sale</a></li>
		*/

	$json_data = array(
			"draw"            => intval( '' ),  
			"recordsTotal"    => intval( $totalData ),  
			"recordsFiltered" => intval( $totalFiltered ),
			"data"            => $data 
			);

	echo json_encode($json_data); 
}


public function sales_delete(){
 	
$sale_id = $this->input->get('sale_id');
	
$result = $this->Sales_Model->delete_sales($sale_id);

return $result;
	}
	
	
	    public function sale_items() {
	        
	        $data['sub_category']   = $this->category_models->getSubCategory();

//        $data['sales'] = $this->Sales_Model->get_all_sales();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = 'sale_items';
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['rep_list'] = $this->User_Model->getUserstypeByID();
		$data['category_list'] 	= $this->category_models->getCategory();
		$data['department_list'] 	= $this->Department_Model->get_all_department_list();
			$data['type_list'] 	= $this->Department_Model->get_all_type_list();
		
        //if ($this->session->userdata('ss_group_id')==1 || )
            $this->load->view('sales_items', $data);
      //  else
          //  show_404();
    }
    
     public function day_sale_summary() {
	        
	        $data['sub_category']   = $this->category_models->getSubCategory();

//        $data['sales'] = $this->Sales_Model->get_all_sales();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name'] = 'day_sale_summary';
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['rep_list'] = $this->User_Model->getUserstypeByID();
		$data['category_list'] 	= $this->category_models->getCategory();
		$data['department_list'] 	= $this->Department_Model->get_all_department_list();
		
        //if ($this->session->userdata('ss_group_id')==1 || )
            $this->load->view('day_sale_summary', $data);
      //  else
          //  show_404();
    }
    
    public function list_sale_items()
	{
		$requestData = $this->input->post();
		$search_key = $this->input->post('search');
		$search_key_val = '';//$search_key['value'];
		$start = $this->input->post('start');
		$length = $this->input->post('length');
		$srh_from_date = $this->input->post('srh_from_date');
		$srh_to_date = $this->input->post('srh_to_date');
		$srh_warehouse_id = $this->input->post('srh_warehouse_id');
		$product_id = $this->input->post('product_id');
		$subcategory = $this->input->post('subcategory');
		//$srh_warehouse_id_send = explode(",",$this->input->post('srh_warehouse_id'));
		//print_r($srh_warehouse_id);
		$srh_sales_rep_id = $this->input->post('srh_sales_rep_id');
		$category = $this->input->post('category');
		$dep_id = $this->input->post('dep_id');
		$srh_sub_cat = $this->input->post('srh_sub_cat');
		//get all sales
		$data = array();
		//$sales_tot = $this->Sales_Model->get_all_sales_count_v1('', '', $search_key_val, $srh_from_date, $srh_to_date, $srh_warehouse_id, $srh_sales_rep_id, $dep_id, $category);
		$all_sn_list=$this->Sales_Model->get_sales_serial_by_id_new($srh_from_date,$srh_to_date);
		//echo '<pre>',print_r($all_sn_list),'</pre>'; die();
		$sales = $this->Sales_Model->get_all_sales_v2($start, $length, $search_key_val, $srh_from_date, $srh_to_date, $srh_warehouse_id, $srh_sales_rep_id, $dep_id, $category);
		//echo '<pre>',print_r($sales),'</pre>'; die();
		$sale_itemss = $this->Sales_Model->get_all_sale_items_v1($category, $dep_id, $srh_sub_cat, $product_id, $subcategory,$srh_from_date, $srh_to_date);
		// $returned_qty_dess = $this->Sales_Model->get_returned_qty_by_sale_id_and_product_id_v1($srh_from_date, $srh_to_date);
		
		//echo '<pre>',print_r($returned_qty_des),'</pre>'; die();	
		$totalData = count($sales);
		$totalFiltered = $totalData;
		//print_r($sales);
		$inv_number = 0;
		foreach ($sales as $row) {

			$returned_qty_dess = $this->Sales_Model->get_returned_qty_by_sale_id_and_product_id_v1($srh_from_date, $srh_to_date, $row['sale_id']);
			
			$inv_number ++;

			$nestedData = array();
			$sale_id = $row['sale_id'];
			$nestedData[] = display_date_time_format($row['sale_datetime']);
			$nestedData[] = "<center> ($inv_number)." . $row['sale_reference_no'] . "</center>";
			$nestedData[] = $row['cus_name'] . ' / ' . $row['cus_phone'];
			$nestedData[] = $row['sale_total'];
			$nestedData[] = " ( Sales Rep. -  ".$row['user_first_name'].")";//"<left>" . $row['product_name'] . "</left>"; //"<left>" . $row['product_name'] . "</left>";
			$actionTxtDisble = '';
			$actionTxtEnable = '';
			$actionTxtUpdate = '';
			$actionTxtDelete = '';
			$nestedData[] = '';
			$nestedData[] = '';
			$nestedData[] = '';
			$nestedData[] = '';
			$nestedData[] = '';
			$nestedData[] = '';
			$data[] = $nestedData;
			//get sale items by sale id
			//$sale_items = $this->Sales_Model->get_all_sale_items_v1($sale_id, $category, $dep_id, $srh_sub_cat, $product_id, $subcategory,$srh_from_date, $srh_to_date);
			$sale_items = (isset($sale_itemss[$sale_id]))?$sale_itemss[$sale_id]:array();
			//echo '<pre>',print_r($sale_items),'</pre>'; die();


			if($row['sale_id'] == 106)
			{
				//echo $row['sale_id'];
				//print_r($returned_qty_dess);
			}

			$last_item = end($sale_items);
			$total_profit = 0;
			foreach ($sale_items as $sale_items_row) {
				//print_r($sale_items_row);
				$no_of_items = 0;
				$sale_item_id = $sale_items_row['id'];
				$saleItemData = array();
				$saleItemData[] = '';
				$saleItemData[] = '';
				$saleItemData[] = '';
				$saleItemData[] = '';
				
				$qty = $sale_items_row['quantity'];
				//get returned qty by sale_id and product id
				$returned_qty_des = $this->Sales_Model->get_returned_qty_by_sale_id_and_product_id($sale_id, $sale_items_row['product_id']);

				//if($row['sale_id'] == 106)
				{

					//echo "product_id : ". $sale_items_row['product_id'];
					//echo "<pre>";
				  // print_r($returned_qty_des);
					//die();
				}
				
				//Comment 22/2/2026
				//$returned_qty_des = (isset($returned_qty_dess[$sale_id][$sale_items_row['product_id']]))?$returned_qty_dess[$sale_id][$sale_items_row['product_id']]:0;
				$returned_qty_des = $returned_qty_des->quantity;

				if($row['sale_id'] == 105){

					//echo "returned_qty_des : $returned_qty_des";
				  // print_r($returned_qty_des);
					//die();
				}

				
				$sale_sn_list = '';
				//$sale_sn_list="<br/> $sale_id , $sale_item_id";
				$sn_list = (isset($all_sn_list[$sale_id][$sale_item_id]))?$all_sn_list[$sale_id][$sale_item_id]:'';
				if(!empty($sn_list)){
				    if(is_array($sn_list)){
				        foreach ($sn_list as $sn) { 
            				$sale_sn_list.=" $sn->sis_number <br/> ";	
            			} 
				    }else{
				        $sale_sn_list.=$sn_list[0]->sis_number." <br/> ";
				    }
				}

				if ($sale_sn_list) $sale_sn_list = "<br/>  " . $sale_sn_list;
				//print_r($returned_qty_des);
				$returned_qty = 0;
				$returned_dis_text = '';
				$balance_qty = 0;
				//$returned_qty = intval($returned_qty_des->quantity);
				$returned_qty = intval($returned_qty_des);
				if ($returned_qty) {
					$returned_dis_text = "  <span class='label label-danger'>$returned_qty Item(s) Returned</span>";
				}
				$balance_qty = $sale_items_row['quantity'] - $returned_qty;
				$no_of_items = $no_of_items + $balance_qty;
				$cal_class_1 = '';
				$cal_class_2 = '';
				if ($sale_items_row['cat_id'] == 3 || $sale_items_row['cat_id'] == 2 || $sale_items_row['cat_id'] == 13) {
					$cal_class_1 = "<span class='label label-success'>";
					$cal_class_2 = "</span>";
				}
				$saleItemData[] = "<left>$cal_class_1" . $sale_items_row['product_name'] . ' (' . $sale_items_row['product_code'] . ") X ($qty) $cal_class_1 $returned_dis_text $sale_sn_list</left>";
				if ($this->session->userdata('ss_group_id') == 1) {
					$saleItemData[] = number_format($balance_qty * $sale_items_row['item_cost'], 2, '.', '');
				} else {
					// $saleItemData[] = '';
					$saleItemData[] = number_format($balance_qty * $sale_items_row['item_cost'], 2, '.', '');
				}
				$val_tmp = 1;
				$qty_tmp = $qty;
				if ($qty == 0.00) {

					$qty_tmp = 1;
				}
				$profit = 0;
				if (!empty($qty)) {
					$val_tmp = ($sale_items_row['gross_total'] / $qty_tmp) * $balance_qty;
					$profit = number_format($val_tmp - $balance_qty * $sale_items_row['item_cost'], 2, '.', '');
				}
				$saleItemData[] = number_format($val_tmp, 2, '.', '');
				$saleItemData[] = $no_of_items;
				$profit_hide = 0;


				//Get service charge
				$sale_payments_list = $this->Sales_Model->get_sale_payments_by_sale_id($row['sale_id']);
				$tot_advnc_paid = 0;
				$cr_interest_tot = 0;
				$v2_a_total = 0;
				$v3_net_interest_amount = 0;
				$v3_net_previous_amount = 0;
				foreach ($sale_payments_list as $row_p) {
				// print_r($row_p);
					$sale_pymnt_amount = 0;
					$cr_interest = 0;
					



					//Get selected invoice return, payment type amount
					$invoice_return_payment_type_amount = $this->Sales_Model->get_invoice_return_payment_type_amount($row['sale_id'],$row_p->sale_pymnt_paying_by);
					$invoice_balance_amount = $row_p->sale_pymnt_amount - $invoice_return_payment_type_amount;
					//if($row['sale_id'] == 176)
					{
						// echo "sale_pymnt_id:".":".$row_p->sale_pymnt_id;
						// echo "sale_pymnt_amount:".":".$row_p->sale_pymnt_amount;
						// echo "sale_pymnt_paying_by:".":".$row_p->sale_pymnt_paying_by;
						// echo "invoice_return_payment_type_amount:".":".$invoice_return_payment_type_amount;
						// echo "invoice_balance_amount:".":".$invoice_balance_amount;
					}

					$sale_pymnt_amount = $invoice_balance_amount;


					// if ($row_p->extra_val_1) {
					//     //$tot_advnc_paid+=$row_p->sale_pymnt_amount;
					//     $cr_interest = $sale_pymnt_amount * 0.03;
					// }

					if ($row_p->service_charge_percentage) {
						$cr_interest = ($sale_pymnt_amount / 100) * $row_p->service_charge_percentage;
					}

					//echo $row_p->service_charge_percentage;


					//$cr_interest = $sale_pymnt_amount * 0.03;
					$cr_interest_tot += $cr_interest;
					$tot_advnc_paid = $tot_advnc_paid + $sale_pymnt_amount; //-$cr_interest;


					// New calculation profit

					$total = $sale_pymnt_amount;//135000;
					$percentage = $row_p->service_charge_percentage;//12.5;

					$A = $total / (1 + $percentage / 100);

					$v2_a_total = $v2_a_total + $A;

					//echo $A; // 120000

					// End new calculation profit



					// $amount_with_interest = $row_p->sale_pymnt_amount;
					$amount_with_interest = $invoice_balance_amount;
					$interest = $row_p->service_charge_percentage;
					$return_data = calculateOriginalAmountFromServiceCharge($amount_with_interest, $interest);
					$previous_amount = $return_data['previous_amount'];
					$interest_amount = $return_data['interest_amount'];
					$v3_net_previous_amount = $v3_net_previous_amount + $previous_amount;
					$v3_net_interest_amount = $v3_net_interest_amount + $interest_amount;

				}

				//End get ss 
				


				


				if (!$profit_hide) {
					if($this->session->userdata('ss_group_id')==1){
						$saleItemData[] = $profit;
					}else{
						$saleItemData[] = '';
					}

				} else {
					$saleItemData[] = "";
				}


				

				$total_profit = $total_profit + $profit;

				if ($sale_items_row === $last_item) {
					$saleItemData[] = number_format($cr_interest_tot, 2, '.', ''). "<br/>($v3_net_interest_amount) ";;//number_format($cr_interest_tot, 2);
					if($this->session->userdata('ss_group_id')==1){
						
						$saleItemData[] = number_format(($total_profit - $v3_net_interest_amount), 2, '.', '');
						//$saleItemData[] = number_format($total_profit - $cr_interest_tot, 2, '.', ''). "<br/>(".($total_profit - $v3_net_interest_amount).") ";
					}else{
						$saleItemData[] = '';
					}
				}else{
					$saleItemData[] = '';
					$saleItemData[] = "";
				}


				

				
				// $saleItemData[] = '';
				// $saleItemData[] = '';
				//	
				$data[] = $saleItemData;
				if (!empty($sn_list)) {
					//echo "<br/> Serial No. ";
					foreach ($sn_list as $sn) {
						//	$sale_sn_list.=" $sn->sis_number <br/> ";
						/* add searial no row */

						// $saleItemDataSn = array();
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = '';
						// $saleItemDataSn[] = $sn->sis_number;
						// $saleItemDataSn[] = $sale_items_row['item_cost'];
						// $data[] = $saleItemDataSn;
					}
				}
				/* end add serial no row */
			}
		}
		$json_data = array(
			// "draw" => intval($requestData['draw']),
			"recordsTotal" => intval($totalData),
			"recordsFiltered" => intval($totalFiltered),
			"data" => $data
		);
		echo json_encode($json_data);
	}

    public function list_sale_items_old() {
        $requestData = $this->input->post();
        $search_key = $this->input->post('search');
        $search_key_val = $search_key['value'];
        $start = $this->input->post('start');
        $length = $this->input->post('length');
		$srh_from_date = $this->input->post('srh_from_date');
        $srh_to_date = $this->input->post('srh_to_date');
		$srh_warehouse_id = $this->input->post('srh_warehouse_id');
		$product_id=$this->input->post('product_id');
		$subcategory=$this->input->post('subcategory');
		//$srh_warehouse_id_send = explode(",",$this->input->post('srh_warehouse_id'));
		//print_r($srh_warehouse_id);
		$srh_sales_rep_id = $this->input->post('srh_sales_rep_id');
		$category = $this->input->post('category');
		$dep_id = $this->input->post('dep_id');
		$srh_sub_cat = $this->input->post('srh_sub_cat');
		
		//get all sales

        $data = array();
        $sales_tot = $this->Sales_Model->get_all_sales_count_v1('','',$search_key_val,$srh_from_date,$srh_to_date,$srh_warehouse_id,$srh_sales_rep_id,$dep_id,$category);
		$sales = $this->Sales_Model->get_all_sales_v1($start,$length,$search_key_val,$srh_from_date,$srh_to_date,$srh_warehouse_id,$srh_sales_rep_id,$dep_id,$category);
	
		$totalData = ($sales_tot);
		$totalFiltered = $totalData;  
		
        //print_r($sales);
        foreach ($sales as $row) {
			
            $nestedData = array();
            $sale_id=$row['sale_id'];
            $nestedData[] = display_date_time_format($row['sale_datetime']);
            $nestedData[] = "<center>" . $row['sale_reference_no'] . "</center>";
            $nestedData[] = $row['cus_name'] .' / '.$row['cus_phone'];
            $nestedData[] = $row['sale_total'];
			$nestedData[] = '';//"<left>" . $row['product_name'] . "</left>";
            $actionTxtDisble = '';
            $actionTxtEnable = '';
            $actionTxtUpdate = '';
            $actionTxtDelete = '';
            $nestedData[] = ''; 
			 $nestedData[] = ''; 
			 $nestedData[] ='';
			  $nestedData[] ='';
			  $nestedData[] ='';
			  $nestedData[] ='';
			
            $data[] = $nestedData;
			
			
			//get sale items by sale id
			$sale_items = $this->Sales_Model->get_all_sale_items('', '', '',$sale_id,$category,$dep_id,$srh_sub_cat,$product_id,$subcategory);
			foreach ($sale_items as $sale_items_row) {
				//print_r($sale_items_row);
				$no_of_items=0;
				$sale_item_id=$sale_items_row['id'];
				$saleItemData = array();
				$saleItemData[] ='';
				$saleItemData[] ='';
				$saleItemData[] ='';
				$saleItemData[] ='';
				$qty=$sale_items_row['quantity'];
				//get returned qty by sale_id and product id
				$returned_qty_des=$this->Sales_Model->get_returned_qty_by_sale_id_and_product_id($sale_id,$sale_items_row['product_id']);
				$sale_sn_list='';
				//$sale_sn_list="<br/> $sale_id , $sale_item_id";
				 $sn_list=$this->Sales_Model->get_sales_serial_by_id($sale_id,$sale_item_id);
				if(!empty($sn_list)){
				//echo "<br/> Serial No. ";
				foreach ($sn_list as $sn) { 
				$sale_sn_list.=" $sn->sis_number <br/> ";
				
				}
				}
				
				if($sale_sn_list) $sale_sn_list="<br/>  ".$sale_sn_list;
				
				
				//print_r($returned_qty_des);
				$returned_qty=0;
				$returned_dis_text='';
				$balance_qty=0;
				$returned_qty=intval($returned_qty_des->quantity);
				if($returned_qty){
					$returned_dis_text="  <span class='label label-danger'>$returned_qty Item(s) Returned</span>";
				}
				
				$balance_qty=$sale_items_row['quantity']-$returned_qty;
				
				$no_of_items=$no_of_items+$balance_qty;
				
				$cal_class_1='';
				$cal_class_2='';
				if($sale_items_row['cat_id']==1){
					$cal_class_1="<span class='label label-success'>";
					$cal_class_2="</span>";
				}
				$saleItemData[] ="<left>$cal_class_1".$sale_items_row['product_name'].' ('. $sale_items_row['product_code'].") X ($qty) $cal_class_1 $returned_dis_text $sale_sn_list</left>";
				if($this->session->userdata('ss_group_id')==1){
				$saleItemData[] =number_format($balance_qty*$sale_items_row['item_cost'], 2, '.', '');
				}else{
					$saleItemData[] ='';
				}
				$val_tmp=1;
				$qty_tmp=$qty;
				if($qty==0.00)
				{
				    
				    $qty_tmp=1;
				}
				
				$profit=0;
				if(!empty($qty)){
					$val_tmp=($sale_items_row['gross_total']/$qty_tmp)*$balance_qty;
					$profit=number_format($val_tmp-$balance_qty*$sale_items_row['item_cost'], 2, '.', '');
				}
				$saleItemData[] =number_format($val_tmp, 2, '.', '');
				$saleItemData[] =$no_of_items;
				$profit_hide=1;
				if(!$profit_hide) {
				$saleItemData[] =$profit;
				}else{
				    $saleItemData[] ="";
				}
				$saleItemData[] ='';
				$saleItemData[] ='';
				//	
				$data[] = $saleItemData;	
				
				
				
				if(!empty($sn_list)){
				//echo "<br/> Serial No. ";
				foreach ($sn_list as $sn) { 
			//	$sale_sn_list.=" $sn->sis_number <br/> ";
				
			
				/* add searial no row */
				$saleItemDataSn=array();
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] =$sn->sis_number;
					$saleItemDataSn[] =$sale_items_row['item_cost'];
				$data[] = $saleItemDataSn;
				}
				}
				
				
				
				/* end add serial no row */
			}
			
			
			

			
			
        }

        $json_data = array(
           // "draw" => intval($requestData['draw']),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        echo json_encode($json_data);
    }
    
    
     public function list_day_sale_summary() {
        $requestData = $this->input->post();
        $search_key = $this->input->post('search');
        $search_key_val = $search_key['value'];
        $start = $this->input->post('start');
        $length = $this->input->post('length');
		$srh_from_date = $this->input->post('srh_from_date');
        $srh_to_date = $this->input->post('srh_to_date');
		$srh_warehouse_id = $this->input->post('srh_warehouse_id');
		$product_id=$this->input->post('product_id');
		//$srh_warehouse_id_send = explode(",",$this->input->post('srh_warehouse_id'));
		//print_r($srh_warehouse_id);
		$srh_sales_rep_id = $this->input->post('srh_sales_rep_id');
		$category = $this->input->post('category');
		$dep_id = $this->input->post('dep_id');
		$srh_sub_cat = $this->input->post('srh_sub_cat');
		
		//get all sales

        $data = array();
        $sales_tot = $this->Sales_Model->get_all_sales_count_v1('','',$search_key_val,$srh_from_date,$srh_to_date,$srh_warehouse_id,$srh_sales_rep_id,$dep_id,$category);
		$sales = $this->Sales_Model->get_all_sales_v1($start,$length,$search_key_val,$srh_from_date,$srh_to_date,$srh_warehouse_id,$srh_sales_rep_id,$dep_id,$category);
	
		$totalData = ($sales_tot);
		$totalFiltered = $totalData;  
		
        //print_r($sales);
        foreach ($sales as $row) {
			
            $nestedData = array();
            $sale_id=$row['sale_id'];
            $nestedData[] = site_date($row['sale_datetime']);
            $nestedData[] = "<center>" . $row['sale_reference_no'] . "</center>";
            $nestedData[] = $row['cus_name'] .' / '.$row['cus_phone'];
            $nestedData[] = $row['sale_total'];
			$nestedData[] = '';//"<left>" . $row['product_name'] . "</left>";
            $actionTxtDisble = '';
            $actionTxtEnable = '';
            $actionTxtUpdate = '';
            $actionTxtDelete = '';
            $nestedData[] = ''; 
			 $nestedData[] = ''; 
			 $nestedData[] ='';
			  $nestedData[] ='';
			  $nestedData[] ='';
			  $nestedData[] ='';
			
           // $data[] = $nestedData;
			
			
			//get sale items by sale id
			$sale_items = $this->Sales_Model->get_all_sale_items('', '', '',$sale_id,$category,$dep_id,$srh_sub_cat,$product_id);
			foreach ($sale_items as $sale_items_row) {
				//print_r($sale_items_row);
				
				//get_sale_info($id)
				$sale_des=$this->Sales_Model->get_sale_info($sale_items_row['sale_id']);
				$no_of_items=0;
				$sale_item_id=$sale_items_row['id'];
				$saleItemData = array();
			//	$saleItemData[] ='';
			$saleItemData[] = site_date($row['sale_datetime']);
				$saleItemData[] ="<a target='_blank' href='sales/view/$sale_id'>".$sale_des['sale_reference_no']."</a>";
				//$saleItemData[] =$row['cus_phone'];
				///$saleItemData[] ='';
				$qty=$sale_items_row['quantity'];
				//get returned qty by sale_id and product id
				$returned_qty_des=$this->Sales_Model->get_returned_qty_by_sale_id_and_product_id($sale_id,$sale_items_row['product_id']);
				$sale_sn_list='';
				$sale_cost_list='';
				//$sale_sn_list="<br/> $sale_id , $sale_item_id";
				 $sn_list=$this->Sales_Model->get_sales_serial_by_id($sale_id,$sale_item_id);
				if(!empty($sn_list)){
				//echo "<br/> Serial No. ";
				foreach ($sn_list as $sn) {
				    
				    if($sale_sn_list) 
				    $sale_sn_list.="<br/>";
				    
				$sale_sn_list.=" $sn->sis_number ";
				
				}
				}
				
				if($sale_sn_list) $sale_sn_list="".$sale_sn_list;
				
				
				//print_r($returned_qty_des);
				$returned_qty=0;
				$returned_dis_text='';
				$balance_qty=0;
				$returned_qty=intval($returned_qty_des->quantity);
				if($returned_qty){
					$returned_dis_text="  <span class='label label-danger'>$returned_qty Item(s) Returned</span>";
				}
				
				$balance_qty=$sale_items_row['quantity']-$returned_qty;
				
				$no_of_items=$no_of_items+$balance_qty;
				
				$cal_class_1='';
				$cal_class_2='';
				if($sale_items_row['cat_id']==1){
				//	$cal_class_1="<span class='label label-success'>";
				//	$cal_class_2="</span>";
				}
				$saleItemData[] ="<left>$cal_class_1".$sale_items_row['product_name'].' ('. $sale_items_row['product_id'].")  $cal_class_1 $returned_dis_text </left>";
				if($this->session->userdata('ss_group_id')==1){
				//$saleItemData[] =number_format($balance_qty*$sale_items_row['item_cost'], 2, '.', '');
				}else{
				//	$saleItemData[] ='';
				}
				$val_tmp=1;
				$qty_tmp=$qty;
				if($qty==0.00)
				{
				    
				    $qty_tmp=1;
				}
				
				$profit=0;
				if(!empty($qty)){
					$val_tmp=($sale_items_row['gross_total']/$qty_tmp)*$balance_qty;
					$profit=number_format($val_tmp-$balance_qty*$sale_items_row['item_cost'], 2, '.', '');
				}
				//$saleItemData[] =number_format($val_tmp, 2, '.', '');
				$saleItemData[] =$no_of_items;
				$profit_hide=1;
				if(!$profit_hide) {
				//$saleItemData[] =$profit;
				}else{
				    //$saleItemData[] ="";
				}
				$saleItemData[] =$sale_sn_list;
				//$saleItemData[] ='';
				$saleItemData[] =number_format($val_tmp, 2, '.', '');
				//	
				$data[] = $saleItemData;	
				
				
				
				if(!empty($sn_list)){
				//echo "<br/> Serial No. ";
				foreach ($sn_list as $sn) { 
			//	$sale_sn_list.=" $sn->sis_number <br/> ";
				
			
				/* add searial no row */
				$saleItemDataSn=array();
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] ='';
					$saleItemDataSn[] =$sn->sis_number;
					$saleItemDataSn[] =$sale_items_row['item_cost'];
				//$data[] = $saleItemDataSn;
				}
				}
				
				
				
				/* end add serial no row */
			}
			
			
			

			
			
        }

        $json_data = array(
           // "draw" => intval($requestData['draw']),
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );

        echo json_encode($json_data);
    }
	
		public function cheque_return_by_sp_id(){
		$sp_id = $this->input->get('sp_id');
		$data=array(
				'sale_pymnt_cheque_rtn_status'=>1,
				'sale_pymnt_cheque_rtn_user'=>$this->session->userdata('ss_user_id'),
				'sale_pymnt_cheque_rtn_date_time'=>date("Y-m-d H:i:s"),
			);
		$result = $this->Sales_Model->cheque_return_by_sp_id($sp_id,$data);
		return $result;
	}
	
	

	
	public function sale_pymnts_delete_by_sp_id(){
 	
$sp_id = $this->input->get('sp_id');
	
$result = $this->Sales_Model->sale_pymnts_delete_by_sp_id($sp_id);

return $result;
	}
	
	
	public function get_product_cost_by_serial_no_id(){
		$pis_number = $this->input->post('pis_number');
		
		$item_list=$this->Sales_Model->get_product_cost_by_serial_no_id($pis_number);
		
		
		
		//print_r($item_list);
		
		$pis_cost_price=floatval($item_list[0]->pis_cost_price);
		$pis_cash_price=floatval($item_list[0]->pis_cash_price);
		//print_r($sales_list);

		$status=0;

		if(empty($item_list)){

			$status=1;

		}

         $st = array('pis_cost_price'=>$pis_cost_price,'status' =>$status,'validation' =>'Error!','pis_cash_price'=>$pis_cash_price);

         echo json_encode($st);
	}
	
	public function get_all_sum_sales_for_summery_report()
    {
        $srh_warehouse_id = $this->input->get('warehouse_id');
        $srh_to_date      = $this->input->get('srh_to_date');
        $srh_from_date    = $this->input->get('srh_from_date');
        $srh_customer_id  = $this->input->get('srh_customer_id');
        $total_sales      = $this->Sales_Model->get_all_sum_sales_for_summery_report($srh_warehouse_id, $srh_to_date, $srh_from_date, '', '', '', $srh_customer_id);
        echo json_encode($total_sales);
    }
    public function get_sum_sales_return()
    {
        $srh_warehouse_id = $this->input->get('warehouse_id');
        $srh_to_date      = $this->input->get('srh_to_date');
        $srh_from_date    = $this->input->get('srh_from_date');
        $srh_customer_id  = $this->input->get('srh_customer_id');
        $total_returns    = $this->Sales_Model->get_sum_sales_return($srh_warehouse_id, $srh_to_date, $srh_from_date, '', '', '', $srh_customer_id);
        //print_r($total_returns);
        echo json_encode($total_returns);
    }
	  public function getSumPaymentsForBalanceRep()
    {
        $srh_warehouse_id = $this->input->get('warehouse_id');
        $srh_to_date      = $this->input->get('srh_to_date');
        $srh_from_date    = $this->input->get('srh_from_date');
        $srh_customer_id  = $this->input->get('srh_customer_id');
        $srh_type         = $this->input->get('srh_type');
        $srh_payment_term = $this->input->get('srh_payment_term');
        $return_name      = $this->input->get('return_name');
        $result           = $this->Sales_Model->getSumPaymentsForBalanceRep($srh_warehouse_id, $srh_to_date, $srh_from_date, $srh_type, $srh_payment_term, '', $srh_customer_id, $return_name);
        //print_r($total_returns);
        echo json_encode($result);
    }
    function get_product_by_serial_no($value='')
    {
		
		//print_r($_GET);
		$term=$this->input->post('term');
		$in_type=$this->input->post('in_type');
		$cus_type=$this->input->post('cus_type');
		$city_id=$this->input->post('city_id');
		$cat_id=$this->input->post('cat_id');
		$srh_warehouse_id=$this->input->post('srh_warehouse_id');
		$manual_search= '';//$this->input->get('manual_search');
		
	
	$data['sales'] = $this->Sales_Model->get_product_by_serial_no($term,$cat_id,$srh_warehouse_id);
		
		$json = array();
		$json_itm=array();
		foreach ($data['sales'] as $row)
		{
			//set price
			$price_tmp=0;
			if($in_type=='Wholesale'){
			$price_tmp=floatval($row['wholesale_price']);
			}else {
			$price_tmp=$row['product_price'];
			}
			
			
			$price_tmp_sn='';
			$price_tmp_sn=$row['pis_cash_price'];
			if($price_tmp_sn){
				$price_tmp=$price_tmp_sn;
				
			}else{
				$price_tmp=$price_tmp;
			}
			
		//	echo "price_tmp:".$price_tmp;
			
		//	$price_tmp=$row['product_price'];
			//quantity for label
				$quantity =0;
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$purchased_qty=0;
				$sales_return_qty=0;
				$product_damaged_qty=0;
				$sold_qty=0;
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$quantity = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 2, '.', ',');
			//end qty for label
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_sn=$row['pis_number'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_w=$row['product_w'];
			$product_sn_exissts=$row['product_sn_exissts'];
			$product_price=$price_tmp;
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			//$extraName.=", Serial No: $product_sn";
			$extraName.=",  Price:.. ".number_format($product_price, 2, '.', ',').", Qty. :".$quantity;			
			
			$is_search_by_sn=0;
			if($row['pis_number']==$term){
				$is_search_by_sn=1;
			}
			
			//product have serial no get grn item serial table cost, val empty set def val
			//if($product_sn_exissts){
				//get cost by sn
				//	get_serial_no_supp_id($sn='');
				
			//}
			
			$json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $product_price,
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'product_sn'=> $row['pis_number'],
					'pis_cost_price'=> $row['pis_cost_price'],
					'supp_id'=> $row['supp_id'],
					'supp_company_name'=> $row['supp_company_name'],
					'product_w'=> $product_w,
					'product_sn_exissts'=> $product_sn_exissts,
					'is_search_by_sn'=> $is_search_by_sn,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName | SN: $row[pis_number]"
                    );
					
					//echo "Test:";
					array_push($json,$json_itm);	
					
		}	
		
		
		
		
		$data['sales_non_seril'] = $this->Sales_Model->get_non_serial_products_suggestions($term,$cat_id);
		foreach ($data['sales_non_seril'] as $row)
		{
			//set price
		//	$price_tmp=0;
			
		//	$price_tmp=$row['product_price'];
		$price_tmp=0;
			if($in_type=='Wholesale'){
			$price_tmp=floatval($row['wholesale_price']);
			}else {
			$price_tmp=$row['product_price'];
			}
			//quantity for label
				$quantity =0;
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$purchased_qty=0;
				$sales_return_qty=0;
				$product_damaged_qty=0;
				$sold_qty=0;	
				
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$quantity = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 0, '.', ',');
			//end qty for label
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_sn='';
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_w='';//need check
			$product_price=$price_tmp;
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			if($product_sn){
				//$extraName.=", Serial No: $product_sn";
			}
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',')." ,Qty. :".$quantity;			
			
			//$json_itm=array();
			//if($srh_warehouse_id!=2){//not smart phone maharagama
			
			$add_details=0;
			
		//	if($quantity){
			///	$add_details=1;
		//	}
		
		
		if($srh_warehouse_id==9 || $srh_warehouse_id==10 || $srh_warehouse_id==11 || $srh_warehouse_id==13){
		    if($quantity){
		        $add_details=1;
		    }
		    
		}else{
		    $add_details=1;
		}
		
			
			if($add_details)
			{
			$json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $price_tmp,
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'product_sn'=> $product_sn,
					'product_w'=> $product_w,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"
                    );
				//	array_push($json,$json_itm);
			}
			//}
					
		}
		
		
		
		
		echo json_encode($json);		
    }
    
    
    public function sales_add_veryfy_item_cost()
    {
       // $data['row'] = $this->uri->segment(3);
	//	 $data['qty'] = $this->uri->segment(4);
	//	  $product_id = $this->uri->segment(5);
		//   $grn_id = $this->uri->segment(6);
		   
		   $cost_admin_verified_c=$this->uri->segment(3);
		    $data['cost_admin_verified_c'] = $cost_admin_verified_c;
		   
		  // echo "cost_admin_verified_c".$cost_admin_verified_c;
		 //  $warehouse_id = $this->uri->segment(7);
		   //$data['product_id']=$product_id;
		 //  $product_des=$this->Product_Models->get_product_by_id($product_id);
		  // $data['product_dis_name']=$product_des->product_code." ".$product_des->product_name;
		   
		
		//echo "test:".$this->uri->segment(3);
		 $data['btnText'] = 'Submit';
		// $data['sn_list'] = $this->Purchases_Model->get_serial_no_by_product_id_grn_id($product_id,$grn_id,$warehouse_id);
		 //print_r($data['sn_list']);
        $this->load->view('models/sales_add_veryfy_item_cost',$data);
    }
}
