<?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();
		date_default_timezone_set("Asia/Colombo");
		$this->load->model('Route_Model');
		$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('User_Model');
		$this->load->model('Transfer_Model');
		$this->load->model('Purchases_Model');
		$this->load->model('Product_Damage_Model');
		$this->load->model('In_Type_Model');
		$this->load->model('Product_Discount_Model');
		$this->load->model('Pos_Model');
		$this->load->model('Bulk_Break_Model');
		 
		
	}
	
	//Sales list page load
	public function index()
	{	
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = $this->sub_menu_name;
        $this->load->view('invoice/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);		
		$cus_sales_details=$this->Sales_Model->get_sale_info_by_customer_id($data['sale_details']['customer_id']);
		$delivery_details	=	$this->Sales_Model->get_lorry_details_by_delivery_id($data['sale_details']['delivery_id']);
		$data['vehicle_name']	= '';
		if(isset($delivery_details[0]))
		$data['vehicle_name']	=	$delivery_details[0]['vehicle_name'];
		$sales_rep_details	=	$this->Sales_Model->get_rep_name_by_rep_id($data['sale_details']['sales_rep_id']);
	//	$data['fname'] = $sales_rep_details['user_first_name'];
	//	$data['lname'] = $sales_rep_details['user_last_name'];
		$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)
		{
			$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('invoice/distribution_invoice_details',$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');
		$bank_id=$this->input->post('bank_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('bank_id', 'Bank', '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,
				'bank_id'=>$bank_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
			);
			
               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 payment page 
	public function payments()
	{
		$this->load->model('Bank_Model');
        $data['sale_id'] = $this->input->get('id');
        $data['sale_type'] = $this->input->get('sale_type');
		$data['bank_list'] = $this->Bank_Model->get_all_bank();
        $this->load->view('models/sales_payment',$data);	
	}
	public function get_old_credit_amount()
	{
		$cus_id=$this->input->get('cus_id');
		$invocie_data=$this->Sales_Model->get_all_sales_bu_cus_id($cus_id);
		$balance_sub_tot_each=0;
		if(count($invocie_data)){ 
		$balance_sub_tot=0;	 	
		foreach ($invocie_data as $inv)
 		{ 
			$total_paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($inv->sale_id);
			$balance_h=0;
	 		$balance_h=$inv->sale_total-$total_paid_amount;
			if($balance_h){
				$balance_sub_tot_each+=$balance_h;			
				//reduse this sale return amount
				$sale_pymnt_ruturn_amount=0;
				$sale_pymnt_ruturn_amount=$this->Sales_Return_Model->get_total_return_by_sale_id($inv->sale_id);
				$balance_sub_tot_each-=$sale_pymnt_ruturn_amount;
			}
	 		//end check date range
		}
	}
		echo json_encode(array('old_credit_amount'=>$balance_sub_tot_each));
	}
	
	
	public function check_recod()
	{
		$CRN = $this->input->get('CRN');
		$query = $this->Sales_Model->get_count($CRN);
      	$resulttemp  		= $query->row();
		$result=$resulttemp->counts;		
		echo json_encode($result);		
	}	
	
	//Sales save 
	//Sales item save
	//Add sales items to 54 table
	public function save_sales()
	{
		//$sale_reference_no=$this->input->post('sale_reference_no');
		$card_ref_number=$this->input->post('card_ref_number');
		$warehouse_id=$this->input->post('warehouse_id');
		$customer_id=$this->input->post('customer_id');
		$rowCount=$this->input->post('rowCount');
		$sales_rep_id=$this->input->post('sales_rep_id');
		$cr_interest=$this->input->post('cr_interest');
		$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');
		$delivery_id=$this->input->post('delivery_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=$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');
		$invoice_type	=$this->input->post('invoice_type');
		$driver_id	=	$this->input->post('driver_id');
//		echo $in_type;
		$sale_inv_discount_amount=$this->input->post('sale_inv_discount_amount');
		$cr_interest_amt=$this->input->post('cr_interest_amt');
		$sale_datetime_created=date('Y-m-d H:i:s');
		$direct_sale			  = $this->input->post('direct_sale');
		$error='';
		$disMsg='';
		$lastid='';
		$sale_id='';
		$delivery=	'';
		$area_id=	'';
		$this->load->model('Marketing_Delivery_Model');	
		if($direct_sale != 1){
			$delivery=$this->Marketing_Delivery_Model->get_delivary_details($delivery_id);		
			$area_id=$delivery['area_id'];
		}
		$query   		= $this->Sales_Model->get_next_ref_no();
        $result  		= $query->row();
        $sale_reference_no		= sprintf("%05d", $result->sale_id+1);
		
		if(!$error){
			$data=array(
				'card_ref_number'=>$card_ref_number,
				'cr_interest'=>$cr_interest,
				'sale_reference_no'=>$sale_reference_no,
				'sales_rep_id'=>$sales_rep_id,
				'customer_id'=>$customer_id,
				'warehouse_id'=>$warehouse_id,
				'sale_datetime'=>$sale_datetime,
				'area_id'=>$area_id,
				'sale_inv_discount'=>$sale_inv_discount,
				'sale_status'=>$sale_status,
				'payment_status'=>$payment_status,
				'sale_payment_term'=>$sale_payment_term,
				'sale_total'=>$sale_total,
				'sale_paid'=>0,
				'cost_total'=>$cost_total,
				'in_type'=>$in_type,
				'invoice_type'	=>	$invoice_type,
				'user'=>$this->session->userdata('ss_user_id'),
				'cr_interest_amt'=>$cr_interest_amt,
				'sale_datetime_created'=>$sale_datetime_created,
				'sale_inv_discount_amount'=>$sale_inv_discount_amount,
				'delivery_id'	=>$delivery_id,
				'direct_sale'	=>$direct_sale,
				'due_date'		=>date('Y-m-d', strtotime("+3 months", strtotime($sale_datetime)))
			);
			$_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++){
				if(isset($row[$i]['product_id'][0]))
				{					
				$data_item=array(
					'sale_id'=>$sale_id,
					'delivery_id'=>$delivery_id,
					'product_id'=>$row[$i]['product_id'][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]
				);
				$this->Sales_Model->save_sales_item($data_item);
				$itemid=$this->db->insert_id();
				//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,));
	}
	function save_order(){
		$this->load->model('lot_process_model');
		//$sale_reference_no=$this->input->post('sale_reference_no');
		$card_ref_number=$this->input->post('card_ref_number');
		$warehouse_id=$this->input->post('warehouse_id');
		$customer_id=$this->input->post('customer_id');
		$rowCount=$this->input->post('rowCount');
		$sales_rep_id=$this->input->post('sales_rep_id');
		$cr_interest=$this->input->post('cr_interest');
		$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');
		$delivery_id=$this->input->post('delivery_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=$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');
		$invoice_type	=$this->input->post('invoice_type');
		$driver_id	=	$this->input->post('driver_id');
		$lot_master_id	= $this->input->post('lot_master_id');
//		echo $in_type;
		$sale_inv_discount_amount=$this->input->post('sale_inv_discount_amount');
		$cr_interest_amt=$this->input->post('cr_interest_amt');
		$sale_datetime_created=date('Y-m-d H:i:s');
		$direct_sale			  = $this->input->post('direct_sale');
		$error='';
		$disMsg='';
		$lastid='';
		$sale_id='';
		$delivery=	'';
		$area_id=	'';
		$this->load->model('Marketing_Delivery_Model');	
		$delivery=$this->Marketing_Delivery_Model->get_delivary_details($delivery_id);		
		$area_id=$delivery['area_id'];
		$query   		= $this->Sales_Model->get_next_ref_no();
        $result  		= $query->row();
        $sale_reference_no		= sprintf("%05d", $result->sale_id+1);
		
		if(!$error){
			$data=array(
				'card_ref_number'=>$card_ref_number,
				'cr_interest'=>$cr_interest,
				'sale_reference_no'=>$sale_reference_no,
				'sales_rep_id'=>$sales_rep_id,
				'customer_id'=>$customer_id,
				'warehouse_id'=>$warehouse_id,
				'sale_datetime'=>$sale_datetime,
				'area_id'=>$area_id,
				'sale_inv_discount'=>$sale_inv_discount,
				'sale_status'=>$sale_status,
				'payment_status'=>$payment_status,
				'sale_payment_term'=>$sale_payment_term,
				'sale_total'=>$sale_total,
				'sale_paid'=>0,
				'cost_total'=>$cost_total,
				'in_type'=>$in_type,
				'invoice_type'	=>	$invoice_type,
				'user'=>$this->session->userdata('ss_user_id'),
				'cr_interest_amt'=>$cr_interest_amt,
				'sale_datetime_created'=>$sale_datetime_created,
				'sale_inv_discount_amount'=>$sale_inv_discount_amount,
				'delivery_id'	=>$delivery_id,
				'direct_sale'	=>$direct_sale,
				'due_date'		=>date('Y-m-d', strtotime("+3 months", strtotime($sale_datetime))),
				'lot_master_id'	=>$lot_master_id
			);
			$_insert=$this->Sales_Model->save_sales($data,$sale_id);
			$lastid=$this->db->insert_id();			
			//$update=$this->Sales_Model->save_sales($data2,$lot_master_id);		
			$data2=array(
				'invoiced_status'=>'1');
			$this->lot_process_model->insert_update_master_table($data2,$lot_master_id,'lot_master_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++){
				if(isset($row[$i]['product_id'][0]))
				{					
				$data_item=array(
					'sale_id'=>$sale_id,
					'delivery_id'=>$delivery_id,
					'product_id'=>$row[$i]['product_id'][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]
				);
				$this->Sales_Model->save_sales_item($data_item);
				$itemid=$this->db->insert_id();
				//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));
	}
	
	//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');
		
		$data['total']=$this->Sales_Model->get_avalable_product_qty($product_id,$warehouse_id);
		echo json_encode(array('remmnaingQty'=>$data['total']));
	}

	//Sales add form
    public function add_sales()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'sales_add';		
		$data['sales_rep_list']=$this->User_Model->get_all_sales_user_reps();
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$this->load->model('Marketing_Delivery_Model');
		$data['delivary_list'] = $this->Marketing_Delivery_Model->get_delivary_approved_for_manual_sales();		
		$data['routes_list']=$this->Route_Model->get_all_routes();
        $this->load->view('invoice/add_sales',$data);
    }
	function direct()
    {   
		$this->load->model('Marketing_Delivery_Model');
		$this->load->model('Drivers_Model');
		$data['main_menu_name'] ='direct';		
		$data['sub_menu_name'] = 'add_direct';		
		$data['customer_list']  = $this->Customer_Model->get_all_customers();
		$data['in_type_list']=$this->In_Type_Model->get_active_in_types();
		$data['sales_rep_list']=$this->User_Model->get_all_sales_user_reps();
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['vehicle_list']=$this->Marketing_Delivery_Model->get_all_vehicle();
		$data['drivers_list']=$this->Drivers_Model->get_all_drivers_for_invoice();
		//print_r($data['drivers_list']);
		$this->load->model('Marketing_Delivery_Model');
		//$data['delivary_list'] = $this->Marketing_Delivery_Model->get_delivary_approved_for_manual_sales();		
		$data['routes_list']=$this->Route_Model->get_all_routes();
        $this->load->view('invoice/add_direct_sales',$data);
    }
	function listdirect()
    {
		$data['main_menu_name'] ='direct';		
		$data['sub_menu_name'] = 'list_direct';
        $this->load->view('invoice/list_direct_sales',$data);
    }
	
	function return_suggestion ()
	{
		$page='';
		$page=$this->input->get('page');
		$sale_id=$this->input->get('sale_id');
		$term=$this->input->get('term');
		$in_type=$this->input->get('t');
		$data['sales'] = $this->Sales_Model->get_products_suggestions_get_by_sales_id_for_return($term,$sale_id);
		
		$json = array();
		foreach ($data['sales'] as $row)
		{			
			//set price
			$price_tmp=0;
			$product_id=$row['product_id'];
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_price=$row['unit_price'];
			$product_cost =$row['item_cost'];
			$quantity=$row['quantity'];
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',');
			if($product_part_no) $extraName.=", Part No: $product_part_no";
			if($product_oem_part_number) $extraName.=", OEM Part No: $product_oem_part_number";			
			$return_qty_temp=$this->Sales_Model->get_sum_of_return_received_item_qty($product_id,$sale_id);		
			$return_qty = $return_qty_temp['quantity'];
			$qty_in_stock=$quantity-$return_qty;
			$extraName.=", Qty in stock: ".$qty_in_stock;
			if($qty_in_stock>0)
			{
			 $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'=> $product_cost,
					'qty_in_stock'=> $qty_in_stock,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"
                    );
					if($page=='sales_return_add'){
						if($quantity){
							array_push($json,$json_itm);
						}
					}else {
					array_push($json,$json_itm);
					}					
			}
		}		
		echo json_encode($json);		
	}
	function return_suggestion_hw()
	{
		$page='';
		$page=$this->input->get('page');
		$sale_id=$this->input->get('sale_id');
		$term=$this->input->get('term');
		$in_type=$this->input->get('t');
		$data['sales'] = $this->Sales_Model->get_products_suggestions_get_by_sales_id_for_return_hw($term,$sale_id);
		
		$json = array();
		foreach ($data['sales'] as $row)
		{			
			//set price
			$price_tmp=0;
			$product_id=$row['product_id'];
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_price=$row['gross_total']/$row['quantity'];
			$product_cost =$row['item_cost'];
			$quantity=$row['quantity'];
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',');
			if($product_part_no) $extraName.=", Part No: $product_part_no";
			if($product_oem_part_number) $extraName.=", OEM Part No: $product_oem_part_number";			
			$return_qty_temp=$this->Sales_Model->get_sum_of_return_received_item_qty($product_id,$sale_id);		
			$return_qty = $return_qty_temp['quantity'];
			$qty_in_stock=$quantity-$return_qty;
			$extraName.=", Qty in stock: ".$qty_in_stock;
			if($qty_in_stock>0)
			{
			 $json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'batch_id'=> $row['batch_id'],
					'product_price'=> $product_price,
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $product_cost,
					'qty_in_stock'=> $qty_in_stock,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"
                    );
					if($page=='sales_return_add'){
						if($quantity){
							array_push($json,$json_itm);
						}
					}else {
					array_push($json,$json_itm);
					}					
			}
		}		
		echo json_encode($json);		
	}
	
	//Sales product items get
	 public function suggestionsold($value='')
    {
		
		$page='';
		$page=$this->input->get('page');
		$sale_id=$this->input->get('sale_id');
		$term=$this->input->get('term');
		$in_type=$this->input->get('t');
		$Sales_rep_id= '';//$this->input->get('SR');
		$werehouse_id=$this->input->get('WH');		
		$data['sales'] = $this->Sales_Model->get_products_suggestions_get_by_sales_rep_id($term,$Sales_rep_id,$werehouse_id);
		$json = array();
		foreach ($data['sales'] as $row)
		{
			$saleqty=0;
			if($page=='sales_return_add')
			{
			//check invoice have this item
			$saleqty=$this->Sales_Return_Model->get_avalable_product_qty_for_return($row['product_id'],$this->session->userdata('ss_warehouse_id'),$sale_id); 	
			}			
			//set price
			$price_tmp=0;
			if($in_type=='Cash'){
				$price_tmp=$row['product_price'];
			}
			if($in_type=='Credit'){
				$price_tmp=$row['wholesale_price'];
			}
			if($in_type=='Wholesale'){
				$price_tmp=$row['wholesale_price'];
			}
			$product_id=$row['product_id'];
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_price=$price_tmp;
			$down_payment=$row['down_payment'];
			$per_day_rental=$row['per_day_rental'];
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',');
			if($product_part_no) $extraName.=", Part No: $product_part_no";
			if($product_oem_part_number) $extraName.=", OEM Part No: $product_oem_part_number";
			$qty_in_stock=0;			
			$received_qty_temp=$this->Sales_Model->get_sum_of_received_item_qty($product_id,$Sales_rep_id,$werehouse_id);
			$invoiced_qty_temp=$this->Sales_Model->get_sum_of_invoiced_item_qty($product_id,$Sales_rep_id,$werehouse_id);			
			if(isset($received_qty_temp[0]['salse_rep_issue_qty']))
			{
				$received_qty=($received_qty_temp[0]['salse_rep_issue_qty']);
			}
			else
			{
			$received_qty=0;
			}			
			if(isset($invoiced_qty_temp[0]['quantity']))
			{
				$invoiced_qty=($invoiced_qty_temp[0]['quantity']);
			}
			else
			{
			$invoiced_qty=0;
			}		
			$qty=$received_qty-$invoiced_qty;
			$extraName.=", Qty in stock: ".$qty;
			if($qty>0)
			{			
			 $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,
					'down_payment'=> $row['down_payment'],
					'per_day_rental'=> $row['per_day_rental'],
					'rep_commision'=> $row['rep_commision'],
					'daily_rental_days'=> $row['daily_rental_days'],
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'qtyforcheck'=> $qty,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"
                    );
					if($page=='sales_return_add'){
						if($saleqty){
							array_push($json,$json_itm);
						}
					}else {
					array_push($json,$json_itm);
					}			
			}
		}		
		echo json_encode($json);	
    }
	
	
	
	 public function suggestions($value='')
    {
		$this->load->model('Marketing_Delivery_Model');
		$page='';
		$page=$this->input->get('page');
		$sale_id=$this->input->get('sale_id');
		$term=$this->input->get('term');
		$in_type=$this->input->get('t');
		$werehouse_id=$this->input->get('WH');
		$delivery_id=$this->input->get('DL');		
		$data['sales'] = $this->Sales_Model->get_products_suggestions_get_by_delivery_id($term,$delivery_id,$werehouse_id);
		$json = array();
		
		foreach ($data['sales'] as $row)
		{
			$saleqty=0;		
			//set price
			$price_tmp=0;
			if($in_type=='Cash'){
				$price_tmp=$row['product_price'];
			}
			if($in_type=='Credit'){
				$price_tmp=$row['credit_salling_price'];
			}
			if($in_type=='Wholesale'){
				$price_tmp=$row['wholesale_price'];
			}
			$product_id=$row['product_id'];
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_price=$price_tmp;
			$down_payment=$row['down_payment'];
			$per_day_rental=$row['per_day_rental'];
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',');
			if($product_part_no) $extraName.=", Part No: $product_part_no";
			if($product_oem_part_number) $extraName.=", OEM Part No: $product_oem_part_number";
			$qty_in_stock=0;			
			
			$issue_qty=$this->Marketing_Delivery_Model->get_delivery_product_item($delivery_id,$row['product_id']);
			$invoice_qty=$this->Marketing_Delivery_Model->get_invoice_product_item($delivery_id,$row['product_id']);
			$return_qty=$this->Marketing_Delivery_Model->get_return_product_item($delivery_id,$row['product_id']);
			
			$qty=$issue_qty-$invoice_qty-$return_qty;		
			$extraName.=", Qty in stock: ".$qty;			

			if($qty>0)
			{			
			 $json_itm=array(
			 		'id'=> $row['product_id'],
					'sales_rep_issue_id'=> $delivery_id,
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $price_tmp,
					'down_payment'=> $row['down_payment'],
					'per_day_rental'=> $row['per_day_rental'],
					'rep_commision'=> $row['rep_commision'],
					'daily_rental_days'=> $row['daily_rental_days'],
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'qtyforcheck'=> $qty,					
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName"
                    );
					if($page=='sales_return_add'){
						if($saleqty){
							array_push($json,$json_itm);
						}
					}else {
					array_push($json,$json_itm);
					}					
			}
		}		
		echo json_encode($json);		
    }	
	
	function product_suggestions($value=''){
        $page          = '';
        $page          = $this->input->get('page');
        $sale_id       = $this->input->get('sale_id');
        $term          = $this->input->get('term');
        $in_type       = $this->input->get('t');
        $data['sales'] = $this->Sales_Model->get_products_suggestions($term);
        $json          = array();
        foreach ($data['sales'] as $row) {
            $saleqty = 0;
            if ($page == 'sales_return_add') {
                $saleqty = $this->Sales_Return_Model->get_avalable_product_qty_for_return($row['product_id'], $this->session->userdata('ss_warehouse_id'), $sale_id);
            }
            $price_tmp = 0;
            if ($in_type == 'Cash') {
                $price_tmp = $row['product_price'];
            }
            if ($in_type == 'Credit') {
                $price_tmp = $row['wholesale_price'];
            }
            if ($in_type == 'Wholesale') {
                $price_tmp = $row['wholesale_price'];
            }
			if ($in_type == 'special_price') {
                $price_tmp = $row['credit_salling_price'];
            }
            $product_name            = $row['product_name'];
            $product_code            = $row['product_code'];
            $product_part_no         = $row['product_part_no'];
            $product_oem_part_number = $row['product_oem_part_number'];
            $product_id              = $row['product_id'];
            $product_price           = $price_tmp;
            $sendParameters          = "'$product_id','$product_name','$product_code','$product_price'";
            $sendParameters          = "$product_id,$product_name,$product_code,$product_price";
            $extraName               = '';
            $extraName .= ", Selling Price: " . number_format($product_price, 2, '.', ',');
            if ($product_part_no)
                $extraName .= ", Part No: $product_part_no";
            if ($product_oem_part_number)
                $extraName .= ", OEM Part No: $product_oem_part_number";
            $qty_in_stock        = 0;
            $srh_warehouse_id    = $this->session->userdata('ss_warehouse_id');
            $transferd_qty       = 0;
            $transfer_reseve_qty = 0;
            $sold_qty            = $this->Sales_Model->getSoldQtyByWarehouseId($srh_warehouse_id, $product_id);
            $purchased_qty       = $this->Purchases_Model->getPurchasedQtyByWarehouseId($srh_warehouse_id, $product_id);
            $p_returned_qty      = 0;//$this->Purchases_Model->getReturnQtyByWarehouseId($srh_warehouse_id, $product_id);
            $sales_return_qty    = $this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($srh_warehouse_id, $product_id);
            $qty_in_stock        = $purchased_qty + $sales_return_qty - $sold_qty - $p_returned_qty;
            $extraName .= ", Qty in stock: $qty_in_stock";
            $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_oem_part_number' => $row['product_oem_part_number'],
                'value' => $row['product_name'] . " (" . $row['product_code'] . ")",
                'label' => $row['product_name'] . " (" . $row['product_code'] . ")$extraName"
            );
            if ($page == 'sales_return_add') {
                if ($saleqty) {
                    array_push($json, $json_itm);
                }
            } else {
                array_push($json, $json_itm);
            }
        }
        echo json_encode($json);
    }
	
	
	
	
	//Sale details page
	public function sale_details()
	{
		$sale_id=$this->input->get('sale_id');
		$data['sale_details']= $this->Sales_Model->get_sale_info($sale_id);
		$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);		
	
		if ($data['sale_details']['direct_sale'] == 0){				
			$this->load->view('invoice/distribution_invoice_print', $data);				
			}
			
		if ($data['sale_details']['direct_sale'] == 1){	
			$data['add_sale_details']= $this->Sales_Model->get_add_sale_info($sale_id);
			$this->load->view('invoice/direct_invoice_print', $data);					
			}
	}	
	
	
	
	//Sales list
	public function list_sales()
	{		
	$requestData= $_REQUEST;	
	$start=$this->input->get('start');
	$length=$this->input->get('length');
	$search=$this->input->get('search');	
	$direct_sale=$this->input->get('direct_sale');	
	$data = array();	
	$count = $this->Sales_Model->get_all_sales("","",$search,$direct_sale);
	$totalData =$count ;
	$sales = $this->Sales_Model->get_all_sales($start,$length,$search,$direct_sale);
	$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=$this->Sales_Return_Model->get_relevant_return_by_sale_id($sale_id);		
		if(isset($return_tot['sl_rtn_total']))
		{
		$return_tot_amt=$return_tot['sl_rtn_total'];
		}
		else
		{
			$return_tot_amt=0;
		}		
		if(isset($return_tot['sls_rtn_total_paid']))
		{
		$return_tot_paid=$return_tot['sls_rtn_total_paid'];
		}
		else
		{
			$return_tot_paid=0;
		}		
		$to_be_paid=$row['sale_total']-$return_tot_amt;
		$nestedData[] =display_date_time_format($row['sale_datetime']);
		$nestedData[] = $row['sale_reference_no']." / ".$row['card_ref_number'];
		$nestedData[] = $row['cus_name'];
		$nestedData[] = $row['sale_total'];
		$nestedData[] = $return_tot_amt;		
		$nestedData[] = $to_be_paid;
		$nestedData[] = $total_paid_amount;	
		$nestedData[] = $to_be_paid-$total_paid_amount;	
		$invoice_balance=$total_paid_amount-$return_tot_paid;
		//$nestedData[] = $to_be_paid-$invoice_balance;	
		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>';
		  }
		}		
		 if ($return_tot_amt>0) 
		 {
			$pay_st = '<span class="label label-danger">Returned</span>';
		 }		
		$nestedData[]=$pay_st;		
		$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;';
		
		$convert_enable='';
		if($row['invoice_type']==2)
		{
		  $convert_enable='<li><a onClick="turn_invoice_type_as_cash('.$sale_id.')"><i class="fa fa-gears"></i> Convert as Cash Invoice</a></li>';							
		}
		
		
		
		if ($return_tot_amt>0) 
		 {
			$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>
							 '.$convert_enable.'						
							</ul></div>'; 
		 }
	 else
		 {
		     if($this->session->userdata('ss_group_id')==1||$this->session->userdata('ss_group_id')==2||$this->session->userdata('ss_group_id')==3){
		         $sale_action=' <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>'; 
		     }else{
		         $sale_action='';
		     }
		    
			$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>
                            '.$sale_action.$convert_enable.'
							</ul></div>'; 
		 }	
		$data[] = $nestedData;
	}

	$json_data = array(
			//"draw"            => intval( $requestData['draw'] ),  
			"recordsTotal"    => intval( $totalData ),  
			"recordsFiltered" => intval( $totalFiltered ),
			"data"            => $data 
			);

	echo json_encode($json_data); 
	}
	
	
	//new update 2019-11-28 by sachith
	
	public function get_list_customer_delivery_id()
	{
		$delivary_id=$this->input->get('ld_id');
		$this->load->model('Customer_Model');
		$this->load->model('Route_Assign_Model');	
		$this->load->model('Marketing_Delivery_Model');		
		$delivery=$this->Marketing_Delivery_Model->get_delivary_details($delivary_id);		
		$area_id=$delivery['area_id'];
		$route_array=$this->Route_Assign_Model->get_relevent_route_ids($area_id);				
		$customer_list=$this->Customer_Model->get_all_customers_by_routes_jason($route_array);
		echo json_encode($customer_list);		
	}
	
	function get_list_customer_by_area_id()
	{
		$area_id=$this->input->get('area_id');
		$this->load->model('Customer_Model');
		$this->load->model('Route_Assign_Model');	
		$this->load->model('Marketing_Delivery_Model');		
		//$delivery=$this->Marketing_Delivery_Model->get_delivary_details($delivary_id);		
		//$area_id=$delivery['area_id'];
		$route_array=$this->Route_Assign_Model->get_relevent_route_ids($area_id);				
		$customer_list=$this->Customer_Model->get_all_customers_by_routes_jason($route_array);
		echo json_encode($customer_list);		
	}
	
	function writefile(){
	
		$this->load->helper('file');
		
		$file = "https://publib.boulder.ibm.com/bpcsamp/v6r1/monitoring/clipsAndTacks/download/ClipsAndTacksF1.zip";
//$file = 'C:\wamp\www\reelstubs\app\webroot\img\movies\0bf522bb76777ba43393b9be5552b263.jpg';
		$file_name = basename($file); 
// Open the file to get existing content
		$file_data = file_get_contents($file);
		
		//$data2 = 'Some file data';
		if ( ! write_file($file_name, $file_data))
		{
				echo 'Unable to write the file';
		}
		else
		{
				echo 'File written!';
		}
					
	}	
	function order_invoice()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'sales_add';
		
		$this->load->model('Customer_Order_Process_Model');
		$this->load->model('Marketing_Delivery_Model');
		$delivary_id =$this->uri->segment('3');
		
		//$data['customer_list']		=	$this->lot_process_model->get_delivary_customers($delivary_id);
		$data['in_type_list']=$this->In_Type_Model->get_active_in_types();
		$data['cus_order_details']	=	$this->Customer_Order_Process_Model->get_cus_order_master_details($delivary_id);
		$data['customer_details']	=	$this->Customer_Order_Process_Model->get_customer_details_by_cus_id($data['cus_order_details']['customer_id']);
		$data['products']			=	$this->Customer_Order_Process_Model->get_cus_order_item_details($data['cus_order_details']['cus_order_master_id']);
		
		//echo "<pre>";print_r($data['lot_order_details']);echo "</pre>";
		//echo "<pre>";print_r($data['customer_details']);echo "</pre>";
		//echo "<pre>";print_r($data['products']);echo "</pre>";
		
		$data['sales_rep_list']=$this->User_Model->get_all_sales_user_reps();
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$this->load->model('Marketing_Delivery_Model');
		$data['delivary_list'] = $this->Marketing_Delivery_Model->get_delivary_approved_for_manual_sales();		
		$data['routes_list']=$this->Route_Model->get_all_routes();
        $this->load->view('invoice/add_order_invoice',$data);
    }
	
	function save_cus_order(){
		$this->load->model('Customer_Order_Process_Model');
		$this->load->library('form_validation'); //form validation lib
		$this->form_validation->set_rules('invoice_type', 'Invoice Type', 'required|trim|xss_clean');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|trim|xss_clean');
		$this->form_validation->set_rules('sales_rep_id', 'Salse Rep', 'required|trim|xss_clean');		
		$this->form_validation->set_rules('delivery_id', 'Delivery', 'required|trim|xss_clean');
		$this->form_validation->set_rules('sale_datetime', 'Date','required|trim|xss_clean');
		$this->form_validation->set_rules('sale_inv_discount','Discunt','trim|xss_clean');
		$this->form_validation->set_rules('customer_id','Customer','required|trim|xss_clean');
		$this->form_validation->set_rules('cus_order_master_id','Order','required|trim|xss_clean');
        if ($this->form_validation->run() == FALSE)
        {
           echo json_encode(array('sale_id'=>0,'error'=>1,'disMsg'=>validation_errors()));
        }
        else
        {	
		//validattion start		
		$card_ref_number=$this->input->post('card_ref_number');
		$warehouse_id=$this->input->post('warehouse_id');
		$customer_id=$this->input->post('customer_id');
		$rowCount=$this->input->post('rowCount');
		$sales_rep_id=$this->input->post('sales_rep_id');
		$cr_interest=$this->input->post('cr_interest');
		$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');
		$delivery_id=$this->input->post('delivery_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=$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');
		$invoice_type	=$this->input->post('invoice_type');
		$driver_id	=	$this->input->post('driver_id');
		$cus_order_master_id	= $this->input->post('cus_order_master_id');
//		echo $in_type;
		$sale_inv_discount_amount=$this->input->post('sale_inv_discount_amount');
		$order_discount=$this->input->post('sale_inv_discount');
		$cr_interest_amt=$this->input->post('cr_interest_amt');
		$sale_datetime_created=date('Y-m-d H:i:s');
		$direct_sale			  = $this->input->post('direct_sale');
		$error='';
		$disMsg='';
		$lastid='';
		$sale_id='';
		$delivery=	'';
		$area_id=	'';
		$this->load->model('Marketing_Delivery_Model');	
		$delivery=$this->Marketing_Delivery_Model->get_delivary_details($delivery_id);		
		$area_id=$delivery['area_id'];
        $sale_reference_no	= $this->Common_Model->gen_ref_number('sale_id','sales','INV'); 
        
        //---------------------------------------------------	
		$order_discount_type=0;//value - 0 , precentage 1
		$order_discount_availble=0;
		$order_dis_val=0;			
		$needle   = "%";
			if( strpos( $order_discount, $needle ) !== false) {
				$order_discount_in=0;
				$order_dis_val=preg_replace('/[^0-9.]/', '', $order_discount);
				if(is_numeric($order_dis_val)){$order_discount_type=1;$order_discount_availble=1;}else{$order_dis_val=0;}
			}
			else
			{
				if(is_numeric($order_discount)){$order_discount_type=0;$order_discount_availble=1;$order_dis_val=$order_discount;}else{$order_dis_val=0;}
			}		
		//-----------------------------------------------	
			if($invoice_type!=2||$invoice_type!=1){
			$due_date=date('Y-m-d', strtotime("+1 days", strtotime($sale_datetime)));	
			}
			
			if($invoice_type==1){
			$due_date=date('Y-m-d', strtotime("+10 days", strtotime($sale_datetime)));	
			}
			if($invoice_type==2){
			$due_date=date('Y-m-d', strtotime("+30 days", strtotime($sale_datetime)));	
			}
		//----------------------------------------------------------
		
		if(!$error){
			$data=array(
				'card_ref_number'=>$card_ref_number,
				'cr_interest'=>$cr_interest,
				'sale_reference_no'=>$sale_reference_no,
				'sales_rep_id'=>$sales_rep_id,
				'customer_id'=>$customer_id,
				'warehouse_id'=>$warehouse_id,
				'sale_datetime'=>$sale_datetime,
				'area_id'=>$area_id,
				'sale_inv_discount'=>$sale_inv_discount,
				'sale_status'=>1,
				'payment_status'=>0,
				'sale_payment_term'=>0,
				'sale_total'=>$sale_total,
				'sale_paid'=>0,
				'cost_total'=>$cost_total,
				'invoice_type'	=>	$invoice_type,
				'user'=>$this->session->userdata('ss_user_id'),
				'cr_interest_amt'=>$cr_interest_amt,
				'sale_datetime_created'=>$sale_datetime_created,
				'sale_inv_discount_amount'=>$sale_inv_discount_amount,
				'delivery_id'	=>$delivery_id,
				'direct_sale'	=>$direct_sale,
				'due_date'		=>$due_date,
				'lot_master_id'	=>$cus_order_master_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';
			$total_added_discount_value=0;
			$total_default_discount_value=0;
			$total_invoice_value=0;
			$total_value=0;
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_item=array();
			for($i=1; $i<=$rowCount; $i++){
				if(isset($row[$i]['product_id'][0]))
				{	
	//-------------------------------------------------------------------------------------------------	
				$product_id=$row[$i]['product_id'][0];
				$product_qty=$row[$i]['qty'][0];
				$product_price=$row[$i]['unit_price'][0];
				$product_cost=$row[$i]['item_cost'][0];
				$product_added_price=$row[$i]['item_price_p'][0];
				$product_discount=$row[$i]['discount'][0];
				$product_discount_val=$row[$i]['discount_val'][0];					
					
				$new_product_price=$product_price+$product_added_price;
				$gross_total=$new_product_price*$product_qty;
					
				$default_discount_val=0;
				$net_product_price=0;	
				$one_item_added_discount=0;
				$one_item_default_discount=0;
				$one_item_added_discount=$product_discount_val/$product_qty;
				$default_discount_field="";
				$product_dis_id="";
				$o_i_discount=0;
				//get relevent discount item	
				$default_discount=$this->Product_Discount_Model->get_relevent_discount($product_id,$invoice_type,$product_qty,$warehouse_id);
							
					if(!$default_discount){						
					$net_product_price=($new_product_price*$product_qty)-$product_discount_val;										
					}
					else{						
						$default_discount_val=$default_discount['discount_value'];
						$default_discount_type=$default_discount['is_precentage'];						
						$product_dis_id=$default_discount['pd_discount_id'];
						if($default_discount_type==0){
						//if not presentage
						$one_item_default_discount=$default_discount_val;
						$net_product_price=	($new_product_price*$product_qty)-($one_item_default_discount*$product_qty)-($one_item_added_discount*$product_qty);		
						$default_discount_field=$default_discount_val;
						$total_default_discount_value+=$one_item_default_discount*$product_qty;
						$o_i_discount=$one_item_default_discount;
						}else{
						//if precentage
						$net_product_price=	($new_product_price*$product_qty)-((($new_product_price/100)*$one_item_default_discount)*$product_qty)-($one_item_added_discount*$product_qty);
						$default_discount_field=$default_discount_val."%";
						$total_default_discount_value+=((($new_product_price/100)*$one_item_default_discount)*$product_qty);
						$o_i_discount=(($new_product_price/100)*$one_item_default_discount);
						}						
					}	
					
					$total_invoice_value+=$net_product_price;
					$total_value+=$gross_total;
					$total_added_discount_value+=$one_item_added_discount*$product_qty;
	//--------------------------------------------------------------------------------------------------	
				$data_item=array(
					'sale_id'=>$sale_id,
					'delivery_id'=>$delivery_id,
					'product_id'=>$product_id,
					'quantity'=>$product_qty,
					'discount'=>$product_discount,
					'discount_val'=>$product_discount_val+($o_i_discount*$product_qty),
					'unit_price'=>$new_product_price,
					'item_cost'=>$product_cost,					 
					'gross_total'=>$gross_total,
					'net_total'=>$net_product_price,
					'added_discount_val'=>$one_item_added_discount,
					'default_discount'=>$default_discount_field,
					'default_discount_val'=>$o_i_discount,
					'discount_id'=>$product_dis_id					
				);
				$this->Sales_Model->save_sales_item($data_item);
				$itemid=$this->db->insert_id();
				//insert user activity
				
				}
			}
		}else {
			$disMsg='Please select these before adding any product:'.$disMsg;
		}
		
		//---------------------------------------
		$gross_amount=$total_invoice_value;
		if($order_discount_availble){
			if($order_discount_type==1){
				$order_dis_val=($total_invoice_value/100)*$order_dis_val;
				$total_invoice_value=$total_invoice_value-$order_dis_val;				
			}
			if($order_discount_type==0){
				$total_invoice_value=$total_invoice_value-$order_dis_val;				
			}			
		}
		//--------------------------------------			
		$secondary_data=array(
			'sale_total'=>$total_invoice_value,
			'sale_inv_total'=>$total_value,
			'sale_status'=>1,
			'total_added_discount_value'=>$total_added_discount_value,
			'total_default_discount_value'=>$total_default_discount_value,
			'sale_inv_gross_total'=>$total_value-$total_added_discount_value
		);
			
		$_insert=$this->Sales_Model->save_sales($secondary_data,$sale_id);
		$data2=array(
				'invoiced_status'=>'1');
		$this->Customer_Order_Process_Model->insert_update_master_table($data2,$cus_order_master_id);

		$this->session->set_flashdata('message', 'Sale successfully added!');
		
		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));
		}//validation end 
		
	}
	function get_cus_tot_credit($cus_id){
		
		$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=number_format($totals_cus_credit-$totals_cus_paid_amount-$totals_cus_return_paid_amount, 2, '.', ',');
		$cus_des=$this->Customer_Model->get_customer_info($cus_id);
		$cus_name=$cus_des['cus_name'];
		$cus_phone=$cus_des['cus_phone'];
		$cus_card='';
		echo json_encode(array('previus_total_sale'=>$cus_balance,'cus_name'=>$cus_name,'cus_phone'=>$cus_phone,'cus_card'=>$cus_card,'cus_id'=>$cus_id));
	}
	
	//----------------------------------------------------------------------------------------impliment new suggession metord for new sale type 2020-02-13
	function sale_product_suggestions($value=''){	
		$this->load->model('Customer_Order_Process_Model');		
		$term=$this->input->get('term');
		$product=$this->Customer_Order_Process_Model->get_product_suggestion($term);
		$in_type=$this->input->get('t');		
		$json=array();
		foreach ($product as $row)
		{
		$warehouse_id = "";//$this->session->userdata('ss_warehouse_id');
		//stock check 	
		$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($warehouse_id,$row['product_id']);
		$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($warehouse_id,$row['product_id']);
		$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($warehouse_id,$row['product_id']);
		$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($warehouse_id,$row['product_id']);				
		$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($warehouse_id,$row['product_id']);					
		$issue_qty=$this->Customer_Order_Process_Model->get_all_cus_isued_item($warehouse_id,$row['product_id']);	
		$return_qty=$this->Customer_Order_Process_Model->get_all_cus_return_item($warehouse_id,$row['product_id']);	
		$direct_sale_qty     = $this->Sales_Model->get_direct_sale_qty($warehouse_id,$row['product_id']);
		
		$hw_sale_qty    = $this->Pos_Model->get_hw_sale_qty($warehouse_id,$row['product_id'],"","");
        $mp       = $this->Bulk_Break_Model->getMpBreakQty($warehouse_id, $row['product_id']);
		$sp		  = $this->Bulk_Break_Model->getSpBreakQty($warehouse_id, $row['product_id']);
		
		
		$qty =	$purchased_qty-$issue_qty+$return_qty-$product_damaged_qty+$transfer_reseve_qty-$transferd_qty-$direct_sale_qty - $hw_sale_qty- $mp + $sp;
			
		 $product_id=$row['product_id'];
		 $product_code =$row['product_code'];
		 $product_name=$row['product_name'];
		 $product_oem_part_number=$row['product_oem_part_number'];
		 $product_part_no=$row['product_part_no'];
		 $product_cost=$row['product_cost']; 
		 $cash_price=$row['product_price'];
		 $wholesale_price=$row['wholesale_price']; 
		 $credit_salling_price=$row['credit_salling_price'];
			
		 if($in_type==1){
			$product_price=$cash_price; 
		 }			
		if($in_type==2){
			$product_price=$credit_salling_price; 
		 }
		if($in_type==3){
			$product_price=$wholesale_price; 
		 }			
		 $sendParameters="$product_id,$product_name,$product_code,$product_price";
		 $selling_R_price=" Selling Price: ".number_format($product_price, 2, '.', ',').' Cost Price:'.number_format($product_cost, 2, '.', ',');//RETAIL PRICE
		 $selling_W_price=" Selling Price(Wholesale): ".number_format($wholesale_price, 2, '.', ',');//WHOLESALE PRICE
		 $selling_C_price=" Selling Price(Credit): ".number_format($credit_salling_price, 2, '.', ',');//CREDIT PRICE
		 if($product_part_no) $selling_R_price.=", Part No: $product_part_no";
		 if($product_oem_part_number) $selling_R_price.=", OEM Part No: $product_oem_part_number";		
		 $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_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].") / $selling_R_price"." / IN SROCK : ".$qty ." / ".$row['batch_ref_number'],
					'qty'=> $qty,
                    );		
		array_push($json,$json_itm);						
		}		
		echo json_encode($json);	
	}
	//----------------------------------------------------------------------------------------impliment new direct sale save metord for diewct invoices distributor
	function save_direct_sale(){
		$this->load->model('Customer_Order_Process_Model');
		$this->load->library('form_validation'); //form validation lib
		$this->form_validation->set_rules('invoice_type', 'Invoice Type', 'required|trim|xss_clean');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required|trim|xss_clean');
		$this->form_validation->set_rules('sales_rep_id', 'Salse Rep', 'required|trim|xss_clean');		
		$this->form_validation->set_rules('route_id','Area', 'required|trim|xss_clean');
		$this->form_validation->set_rules('sale_datetime', 'Date','required|trim|xss_clean');
		$this->form_validation->set_rules('sale_inv_discount','Discunt','trim|xss_clean');
		$this->form_validation->set_rules('customer_id','Customer','required|trim|xss_clean');
		$this->form_validation->set_rules('vehicle_no','Vehicle','trim|xss_clean');
		$this->form_validation->set_rules('driver','Driver','trim|xss_clean');
        if ($this->form_validation->run() == FALSE)
        {
           echo json_encode(array('sale_id'=>0,'error'=>1,'disMsg'=>validation_errors()));
        }
        else
        {	
		//validattion start		
		$card_ref_number=$this->input->post('card_ref_number');
		$warehouse_id=$this->input->post('warehouse_id');
		$customer_id=$this->input->post('customer_id');
		$rowCount=$this->input->post('rowCount');
		$sales_rep_id=$this->input->post('sales_rep_id');
		$cr_interest=$this->input->post('cr_interest');
		$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');
		$area_id=$this->input->post('route_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=$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');
		$invoice_type	=$this->input->post('invoice_type');
		$driver_id	=	$this->input->post('driver');	
		$vehicle_no	=	$this->input->post('vehicle_no');
		$sale_inv_discount_amount=$this->input->post('sale_inv_discount_amount');
		$order_discount=$this->input->post('sale_inv_discount');
		$cr_interest_amt=$this->input->post('cr_interest_amt');
		$sale_datetime_created=date('Y-m-d H:i:s');
		$direct_sale			  = $this->input->post('direct_sale');
		$error='';
		$disMsg='';
		$lastid='';
		$sale_id='';
		$delivery=	'';
		//$area_id=	'';
		$sale_reference_no=$this->Common_Model->gen_ref_number('sale_id','sales','INVD');        
        //---------------------------------------------------	
		$order_discount_type=0;//value - 0 , precentage 1
		$order_discount_availble=0;
		$order_dis_val=0;			
		$needle   = "%";
			if( strpos( $order_discount, $needle ) !== false) {
				$order_discount_in=0;
				$order_dis_val=preg_replace('/[^0-9.]/', '', $order_discount);
				if(is_numeric($order_dis_val)){$order_discount_type=1;$order_discount_availble=1;}else{$order_dis_val=0;}
			}
			else
			{
				if(is_numeric($order_discount)){$order_discount_type=0;$order_discount_availble=1;$order_dis_val=$order_discount;}else{$order_dis_val=0;}
			}		
		//-----------------------------------------------	
		
			if($invoice_type!=2||$invoice_type!=1){
			$due_date=date('Y-m-d', strtotime("+1 days", strtotime($sale_datetime)));	
			}
			
			if($invoice_type==1){
			$due_date=date('Y-m-d', strtotime("+10 days", strtotime($sale_datetime)));	
			}
			if($invoice_type==2){
			$due_date=date('Y-m-d', strtotime("+30 days", strtotime($sale_datetime)));	
			}
		//----------------------------------------------------------
			
		if(!$error){
			$data=array(
				'card_ref_number'=>$card_ref_number,
				'cr_interest'=>$cr_interest,
				'sale_reference_no'=>$sale_reference_no,
				'sales_rep_id'=>$sales_rep_id,
				'customer_id'=>$customer_id,
				'warehouse_id'=>$warehouse_id,
				'sale_datetime'=>$sale_datetime,
				'area_id'=>$area_id,
				'sale_inv_discount'=>$sale_inv_discount,
				'sale_status'=>1,
				'payment_status'=>0,
				'sale_payment_term'=>0,
				'sale_total'=>$sale_total,
				'sale_paid'=>0,
				'cost_total'=>$cost_total,
				'invoice_type'	=>	$invoice_type,
				'user'=>$this->session->userdata('ss_user_id'),
				'cr_interest_amt'=>$cr_interest_amt,
				'sale_datetime_created'=>$sale_datetime_created,
				'sale_inv_discount_amount'=>$sale_inv_discount_amount,
				'direct_sale'	=>1,
				'due_date'		=>$due_date,
			);
			$_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';
			$total_added_discount_value=0;
			$total_default_discount_value=0;
			$total_invoice_value=0;
			$total_value=0;
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_item=array();
			for($i=1; $i<=$rowCount; $i++){
				if(isset($row[$i]['product_id'][0]))
				{	
	//-------------------------------------------------------------------------------------------------	
				$product_id=$row[$i]['product_id'][0];
				$product_qty=$row[$i]['qty'][0];
				$product_price=$row[$i]['unit_price'][0];
				$product_cost=$row[$i]['item_cost'][0];
				$product_added_price=$row[$i]['item_price_p'][0];
				$product_discount=$row[$i]['discount'][0];
				$product_discount_val=$row[$i]['discount_val'][0];					
					
				$new_product_price=$product_price+$product_added_price;
				$gross_total=$new_product_price*$product_qty;
					
				$default_discount_val=0;
				$net_product_price=0;	
				$one_item_added_discount=0;
				$one_item_default_discount=0;
				$one_item_added_discount=$product_discount_val/$product_qty;
				$default_discount_field="";
				$product_dis_id="";
				$o_i_discount=0;
				//get relevent discount item	
				$default_discount=$this->Product_Discount_Model->get_relevent_discount($product_id,$invoice_type,$product_qty,$warehouse_id);
							
					if(!$default_discount){						
					$net_product_price=($new_product_price*$product_qty)-$product_discount_val;										
					}
					else{						
						$default_discount_val=$default_discount['discount_value'];
						$default_discount_type=$default_discount['is_precentage'];						
						$product_dis_id=$default_discount['pd_discount_id'];
						if($default_discount_type==0){
						//if not presentage
						$one_item_default_discount=$default_discount_val;
						$net_product_price=	($new_product_price*$product_qty)-($one_item_default_discount*$product_qty)-($one_item_added_discount*$product_qty);		
						$default_discount_field=$default_discount_val;
						$total_default_discount_value+=$one_item_default_discount*$product_qty;
						$o_i_discount=$one_item_default_discount;
						}else{
						//if precentage
						$net_product_price=	($new_product_price*$product_qty)-((($new_product_price/100)*$one_item_default_discount)*$product_qty)-($one_item_added_discount*$product_qty);
						$default_discount_field=$default_discount_val."%";
						$total_default_discount_value+=((($new_product_price/100)*$one_item_default_discount)*$product_qty);
						$o_i_discount=(($new_product_price/100)*$one_item_default_discount);
						}						
					}	
					
					$total_invoice_value+=$net_product_price;
					$total_value+=$gross_total;
					$total_added_discount_value+=$one_item_added_discount*$product_qty;
	//--------------------------------------------------------------------------------------------------	
				$data_item=array(
					'sale_id'=>$sale_id,
					'direct_sale'=>1,
					'product_id'=>$product_id,
					'quantity'=>$product_qty,
					'discount'=>$product_discount,
					'discount_val'=>$product_discount_val+($o_i_discount*$product_qty),
					'unit_price'=>$new_product_price,
					'item_cost'=>$product_cost,					 
					'gross_total'=>$gross_total,
					'net_total'=>$net_product_price,
					'added_discount_val'=>$one_item_added_discount,
					'default_discount'=>$default_discount_field,
					'default_discount_val'=>$o_i_discount,
					'discount_id'=>$product_dis_id					
				);
				$this->Sales_Model->save_sales_item($data_item);
				$itemid=$this->db->insert_id();
				//insert user activity				
				}
			}
		}else {
			$disMsg='Please select these before adding any product:'.$disMsg;
		}		
		//---------------------------------------
		$gross_amount=$total_invoice_value;
		if($order_discount_availble){
			if($order_discount_type==1){
				$order_dis_val=($total_invoice_value/100)*$order_dis_val;
				$total_invoice_value=$total_invoice_value-$order_dis_val;				
			}
			if($order_discount_type==0){
				$total_invoice_value=$total_invoice_value-$order_dis_val;				
			}			
		}
		//--------------------------------------			
		$secondary_data=array(
			'sale_total'=>$total_invoice_value,
			'sale_inv_total'=>$total_value,
			'sale_status'=>1,
			'total_added_discount_value'=>$total_added_discount_value,
			'total_default_discount_value'=>$total_default_discount_value,
			'sale_inv_gross_total'=>$total_value-$total_added_discount_value
		);		
		$_insert=$this->Sales_Model->save_sales($secondary_data,$sale_id);		
		$sale_additional_data=array(
			'sale_id'=>$sale_id,
			'vehicle_no'=>$vehicle_no,
			'driver_name'=>$driver_id,
		);		
		$_insert=$this->Sales_Model->save_sales_additional($sale_additional_data);
		$this->session->set_flashdata('message', 'Sale successfully added!');
		
		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,));
		}//validation end 		
	}
	
	

	//convert crediit sale to cash sale
	function convert_credit_sale_to_cash()
	{
		$sale_id=$this->input->get('sale_id');
		$warehouse_id='';
		//get sale master details from DB
		$sale_details=$this->Sales_Model->get_sale_master_details($sale_id);
		$sale_item_list=$this->Sales_Model->get_sale_item_details($sale_id);
		
		$total_discount_added_value=0;
		$total_discount_default_value=0;
		$total_sale_gross_total=0;
		$total_sale_sub_total=0;
		$total_sale_net_total=0;
		
		foreach($sale_item_list as $key){	
			$sale_item_id=$key['id'];
			$product_id=$key['product_id'];
			$product_qty=$key['quantity'];
			$product_discount=$key['discount'];
			$invoice_type=1;
			if($invoice_type==1){
				$product_price=$this->Sales_Model->get_product_cash_price($product_id);
			}
			if($invoice_type==2){
				$product_price=$this->Sales_Model->get_product_credit_price($product_id);
			}		
			 //---------------------------------------------------				
			$product_dis_val=0;	
			$adedd_product_discount_value=0;
			$needle   = "%";			
			if( strpos( $product_discount, $needle ) !== false) {
				$product_dis_val=preg_replace('/[^0-9.]/', '', $product_discount);			
				if(is_numeric($product_dis_val)){ $adedd_product_discount_value=($product_price/100)*$product_dis_val;}else{$adedd_product_discount=0;}
			}
			else
			{
				if(is_numeric($product_discount)){$adedd_product_discount_value=$product_discount;}else{$adedd_product_discount=0;}				
			}
		//-----------------------------------------------			
			$default_discount=$this->Product_Discount_Model->get_relevent_discount($product_id,$invoice_type,$product_qty,$warehouse_id);
			
			$product_dis_id=0;
			$net_product_price=0;
			$total_net_product_price=0;
			$one_product_def_val=0;
			$default_discount_val=0;
			$default_discount_field='';
			if(!$default_discount){					
				$net_product_price=($product_price-$adedd_product_discount_value);
				$total_net_product_price=$net_product_price*$product_qty;
					}
					else{
						$default_discount_val=$default_discount['discount_value'];
						$default_discount_type=$default_discount['is_precentage'];						
						$product_dis_id=$default_discount['pd_discount_id'];
						if($default_discount_type==0){
						//if not presentage
						$net_product_price=	$product_price-($adedd_product_discount_value+$default_discount_val);
						$total_net_product_price=$net_product_price*$product_qty;	
						$default_discount_field=$default_discount_val;
						$one_product_def_val=$default_discount_val;
						}else{
						//if precentage
						$one_product_def_val=($product_price/100)*$default_discount_val;
						$net_product_price=	$product_price-($adedd_product_discount_value+$one_product_def_val);	
						$total_net_product_price=$net_product_price*$product_qty;
						$default_discount_field=$default_discount_val."%";
						}						
					}
			$gross_total=$product_price*$product_qty;			
			$total_discount_added_value+=$adedd_product_discount_value*$product_qty;
			$total_discount_default_value+=$one_product_def_val*$product_qty;
			$total_sale_gross_total+=$gross_total;
			$total_sale_sub_total+=$total_net_product_price;
			$data_item=array(
					'discount_val'=>($adedd_product_discount_value+$default_discount_val)*$product_qty,
					'unit_price'=>$product_price,			 
					'gross_total'=>$gross_total,
					'net_total'=>$total_net_product_price,
					'added_discount_val'=>$adedd_product_discount_value,
					'default_discount'=>$default_discount_field,
					'default_discount_val'=>$one_product_def_val,
					'discount_id'=>$product_dis_id					
				);
				$result=$this->Sales_Model->update_sale_item_by_sale_item_id($sale_item_id,$data_item);			
		}//end of foreace loop
		 //---------------------------------------------------	
		
		$sale_datetime=$sale_details['sale_datetime'];
		$invoice_discount=$sale_details['sale_inv_discount'];		
		$invoice_discount_val=0;	
		$invouce_discount_tot_value=0;
		
		$needle   = "%";
			if( strpos( $invoice_discount, $needle ) !== false) {
				$invoice_discount_val=preg_replace('/[^0-9.]/', '', $invoice_discount);
				if(is_numeric($invoice_discount_val)){$invouce_discount_tot_value=($total_sale_sub_total/100)*$invoice_discount_val;}else;{$invoice_discount_val=0;}
			}
			else
			{
				if(is_numeric($invoice_discount)){$invouce_discount_tot_value=$invoice_discount;}else{$invouce_discount_tot_value=0;}
			}		
		//-----------------------------------------------	
		//-----------------------------------------------		
			if($invoice_type!=2||$invoice_type!=1){
			$due_date=date('Y-m-d', strtotime("+1 days", strtotime($sale_datetime)));	
			}			
			if($invoice_type==1){
			$due_date=date('Y-m-d', strtotime("+10 days", strtotime($sale_datetime)));	
			}
			if($invoice_type==2){
			$due_date=date('Y-m-d', strtotime("+25 days", strtotime($sale_datetime)));	
			}
		//----------------------------------------------------------
			$data=array(
				'payment_status'=>0,
				'invoice_type'	=>	$invoice_type,				
				'total_added_discount_value'=>$total_discount_added_value,
				'sale_inv_discount_amount'=>$invouce_discount_tot_value,
				'total_default_discount_value'=>$total_discount_default_value,
				'sale_inv_total'=>$total_sale_gross_total,
				'sale_inv_gross_total'=>$total_sale_gross_total-$total_discount_added_value,
				'sale_total'=>$total_sale_sub_total-$invouce_discount_tot_value,
				'due_date'=>$due_date,				
			);
			$result=$this->Sales_Model->save_sales($data,$sale_id);	
			
		if($result==1){
			$this->session->set_flashdata('message', 'Sale successfully added!');
			echo json_encode(array('status'=>1,'error'=>0,'disMsg'=>'Sale successfully added!',));
		}
		else{
			$this->session->set_flashdata('message', 'Error!');
			echo json_encode(array('status'=>0,'error'=>1,'disMsg'=>'Somthing worng!. Please contact system administrators',));
		}		
	}
	
	public function return_cheque()
	{	
		$this->load->model('Management_Model');
		$id=$this->input->get('id');
		$data=array('sale_pymnt_paying_by'=>'Cheque_Return','cheque_return_date'=>date("Y-m-d H:i:s"),'payment_return_by'=>$this->session->userdata('ss_user_id'));
		$result=$this->Sales_Model->return_cheque($id,$data);	
		$customer_id=$this->Sales_Model->get_sale_payment_cus_id($id);
		
		$data = array(
			'cus_credit_status' =>3,
			'credit_rejected_by' => $this->session->userdata('ss_user_id'),
			'credit_rejected_date' => date('Y-m-d H:i:s'),
			'redit_rejected_reson' => 'Cheque Return',
		);	
		$result=$this->Management_Model->approval_credit_customer($customer_id,$data);
		
		
		if($result==true)
		{
		$st = array('error'=>0,'status' =>1,'validation'=>"Done");	
		}
		else
		{
		$st = array('error'=>1,'status' =>0,'validation'=>"Error ! Data not saved");		
		}
           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);
        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);
        echo json_encode($result);
    }
	
}