<?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');
		
	}
	
	//Sales list page load
	public function index()
	{
		 
		$data['sales'] = $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();
        $this->load->view('sales',$data);
	}
	
	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($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);
		
		
		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['sale_id']=$sale_id;
        $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');

		$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'),
			);
			
               if ($this->Sales_Model->save_sale_payments($data,$sale_pymnt_id)) {
				   
				   //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
                    $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');
        $this->load->view('models/sales_payment',$data);	
	}
	
	//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');
		
		
		//start get next referance no
		$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
		$warehouse_code=$warehouse_dtls['code'];
		
		//lakmal - edit {
		$warehouse_last_id = $this->input->post('warehouse_last_id');
		if($warehouse_last_id == "")	
		$warehouse_last_id=(1+$this->Sales_Model->get_next_warehouse_ref_no($warehouse_id));
		
		
		$sale_reference_no = $this->input->post('sale_reference_no2');
		
		if($sale_reference_no == "")
		$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);
		
		// } end
		
		
		$sale_datetime_1=$this->input->post('sale_datetime');
		$sale_datetime=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');
		
		$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'),
			);
			$_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();
			for($i=1; $i<=$rowCount; $i++){
				//echo "/ $rowCount , Test:".$row[$i]['product_id'][0];
				if(isset($row[$i]['product_id'][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])
				);
				$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++){
						$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);
						
						
				//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);
				}
			}
		
		}else {
			
			$disMsg='Please select these before adding any product:'.$disMsg;
		}	
		
		$this->session->set_flashdata('message', 'Sale successfully added!');
		
		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));
	}

	//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';
		
		//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'] = $this->Customer_Model->get_all_customers();
		$data['status_list'] = $this->Common_Model->get_all_status();
		$data['rep_list'] = $this->User_Model->getSalesRep();
		
        $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');
		
//	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);
		
		$json = array();
		//echo "Count:".count($data['sales']);
		//print_r($data['sales']);
		//echo "<br/>:Test:";
		$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=$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.=", Selling 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'=> $price_tmp,
					'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"
                    );
					
					//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($srh_warehouse_id==2){
				$add_details=1;
			}
			if($quantity){
				$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);		
    }
	
	//Sale details page
	public function sale_details()
	{
		$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['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
        $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);
	}	
	
	
	
	//Sales list
	public function list_sales()
	{
	$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=$this->input->get('start');
	$length=$this->input->get('length');
	$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);
	$sales = $this->Sales_Model->get_all_sales($start,$length,$search_key_val,"","",$warehouse_id);
	
	$totalData = count($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);
		$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'];
		}
		$to_be_paid=$row['sale_total']-$return_tot_amt;
		$nestedData[] =display_date_time_format($row['sale_datetime']);
		$nestedData[] = $row['sale_reference_no'];
		$nestedData[] = $row['cus_name'];
		$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;
		
		$nestedData[] = $to_be_paid;
		$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 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>
								 <!--<li><a href="#" onClick ="delete_invoice('.$row['sale_id'].')"><i class="fa fa-trash-o"></i></i> Delete</a></li>-->
								</ul></div>';
		
		$data[] = $nestedData;
	}

	$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['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(5);
		$data['category_list'] 	= $this->category_models->getCategory();
		
		
        //if ($this->session->userdata('ss_group_id')==1 || )
            $this->load->view('sales_items', $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');
		$srh_sales_rep_id = $this->input->post('srh_sales_rep_id');
		$category = $this->input->post('category');
		
		//get all sales

        $data = array();
        $sales_tot = $this->Sales_Model->get_all_sales_count('','',$search_key_val,$srh_from_date,$srh_to_date,$srh_warehouse_id,$srh_sales_rep_id);
		$sales = $this->Sales_Model->get_all_sales($start,$length,$search_key_val,$srh_from_date,$srh_to_date,$srh_warehouse_id,$srh_sales_rep_id);
	
		$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'];
            $nestedData[] = $row['sale_total'];
			$nestedData[] = '';//"<left>" . $row['product_name'] . "</left>";
            $actionTxtDisble = '';
            $actionTxtEnable = '';
            $actionTxtUpdate = '';
            $actionTxtDelete = '';
            $nestedData[] = ''; 
			 $nestedData[] = ''; 
			 $nestedData[] ='';
			
            $data[] = $nestedData;
			
			
			//get sale items by sale id
			$sale_items = $this->Sales_Model->get_all_sale_items('', '', '',$sale_id,$category);
			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 , ";
				
				}
				}
				
				if($sale_sn_list) $sale_sn_list="<br/> Emei: ".$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']==3){
					$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;
				}
				
				if(!empty($qty)){
				$val_tmp=($sale_items_row['gross_total']/$qty_tmp)*$balance_qty;
				}
				$saleItemData[] =number_format($val_tmp, 2, '.', '');
				$saleItemData[] =$no_of_items;
				//	
				$data[] = $saleItemData;			
			}
			

			
			
        }

        $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);

		//print_r($sales_list);

		$status=0;

		if(empty($item_list)){

			$status=1;

		}

         $st = array('pis_cost_price'=>$pis_cost_price,'status' =>$status,'validation' =>'Error!');

         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);
    }
}
