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

class Service extends CI_Controller {

    var $main_menu_name = "service";
	var $sub_menu_name = "service";

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Service_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('Sequerty_Model');
		$this->load->model('Product_Models');
		$this->load->model('Sales_Model');
		$this->load->model('User_Model');
		$this->load->model('Sales_Model');
		$this->load->model('purchases_model');
		$this->load->model('Purchases_Model');
		$this->load->model('Transfer_Model');
			$this->load->model('Product_Damage_Model');
			$this->load->model('Sales_Return_Model');
			$this->load->model('Service_Details_Model');
		
	}
	
	//Requisition list page load
	public function index()
	{
		$data['service'] = $this->Service_Model->get_all_service();
		$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('service',$data);
	}	
	
	
	  
    	  public function single_barcode($purchas_id='',$po_item_id='',$qty='')
  {
	 // if(
	  $service_id =intval($qty);
	 // $data['product_des'] =$this->Product_Models->get_product_by_id($product_id);
	 // $data['sn_list']=$this->purchases_model->get_purchese_serial_by_id($purchas_id,$po_item_id);
	  $data['sn_list']= array();//$this->purchases_model->get_purchese_serial_by_id($purchas_id,$po_item_id);
	  
   // $data['issue_card_items_details'] = $this->Issue_Cards_Model->get_issue_card_item_list_by_issue_card_id($issue_card_id);
	//echo "test";
	
	$service_id=$this->uri->segment(3);
	
//	echo "service_id:".$service_id;
	
	$data['service_details']= $this->Service_Model->get_service_details_by_id($service_id);
	
//	echo $this->db->last_query();
//	print_r($data['service_details']);
//	die();

//echo "3333333333";
	
    $this->load->view('barcode/service_barcode',$data);
  }	
	
	function service_sales(){
		$data['service'] = $this->Service_Model->get_all_service();
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'list_service_sales';
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $this->load->view('service_sales',$data);
	}
	function list_service_sales(){
		$this->load->model('Sales_Model');
	$requestData=$this->input->get();
	
	$search_key=$this->input->get('search');
	$warehouse_id= 15;
	//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);
		$tot_si_amount=$this->Sales_Model->get_total_interest_by_sale_id($sale_id);
		$rep_name='';
		if(!empty($row['rep_id'])){
		$rep_info=$this->User_Model->get_user_info($row['rep_id']);
		//echo $this->db->last_query();
		//print_r($rep_info);
		$rep_name=$rep_info['user_first_name'];
		}
		
		//get return invocie paid amount
		$sls_rtn_total_paid=0;
		if($row['sl_rtn_id']){
		$sale_rtn_details=$this->Sales_Return_Model->get_sale_return_info($row['sl_rtn_id']);
		$sls_rtn_total_paid=$sale_rtn_details['sls_rtn_total_paid'];
		}
		
		$to_be_paid=$row['sale_total']-$return_tot_amt+$tot_si_amount;
		$nestedData[] =display_date_time_format($row['sale_datetime']);
		$nestedData[] = $row['sale_reference_no'];
		$nestedData[] = $row['cus_name'];
		$nestedData[] = $rep_name;
		/*
		$nestedData[] = number_format($row['sale_total'], 2, '.', ',');
		$nestedData[] = number_format($total_paid_amount, 2, '.', ',');
		$nestedData[] = number_format($row['sale_total']-$total_paid_amount, 2, '.', ',');
		*/
		$nestedData[] = $row['sale_total'];
		$nestedData[] = $return_tot_amt;
		$tot_si_amount_des='';
		
		$total_paid_amount=$total_paid_amount+$sls_rtn_total_paid;
		//if($row['current_interest']!=0.00) 
		//$tot_si_amount_des="$row[current_interest] + ";
		 
		$tot_si_amount_des=$row['current_interest']+$tot_si_amount;
		$nestedData[] =$tot_si_amount_des;
		$nestedData[] = number_format($to_be_paid, 2, '.', '');
		$nestedData[] = $total_paid_amount;
		
		$nestedData[] = $to_be_paid-$total_paid_amount;
		
		
		/*
		if($row['payment_status']=='Paid') {
			$nestedData[]='<span class="label label-sm label-success">'.$row['payment_status'].'</span>'; 
		}else {
			$nestedData[]=$row['payment_status'];
		}
		*/
		if (empty($total_paid_amount)) {
		  $pay_st = '<span class="label label-warning">Pending</span>';
		}else{
		  if ($total_paid_amount >= $to_be_paid) {
			$pay_st = '<span class="label label-success">Paid</span>';
		  }else{
			$pay_st = '<span class="label label-info">Partial</span>';
		  }
		}
		
		$nestedData[]=$pay_st;
		
		
		//$nestedData[] = $row['sale_id'];
		$actionTxtDisble='';
		$actionTxtEnable='';
		$actionTxtUpdate='';
		$actionTxtDelete='';
		
		$url=base_url("sales/sale_details?sale_id=$sale_id");
		$actionTxtUpdate='<a onClick="fbs_click('.$row['sale_id'].')" data-toggle="modal" href="#" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="clip-zoom-in-2"></i></a> &nbsp;';
		
		$actionTxtViewDetails='<a href="'.base_url().'sales/view/'.$sale_id.'" class="btn btn-xs btn-blue tooltips" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-file-text-o"></i></a> &nbsp;';
		
		$nestedData[] = '<div class="btn-group text-left">
								<button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
								<ul role="menu" class="dropdown-menu pull-right">
									<li><a href="'.base_url().'sales/view/'.$sale_id.'"><i class="fa fa-file-text-o"></i> Sale Details</a></li>
									<li><a href="'.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;
	}
	
	/*
		<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>
		*/

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

	echo json_encode($json_data); 
}

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');
		$service_item_avalable=$this->input->get('service_item_avalable');
		
		//print_r($this->input->get());
		$sn_data=array();
		//echo "sn:".$sn;
		if($service_type=='Serial'){
		$sn_data = $this->Service_Model->get_serial_no_details($sn,$service_item_avalable);
		//echo $this->db->last_query();
		//print_r($sn_data);
		}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;
		
		$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;
			$product_name=$sn_data->product_name;
			$cus_id='';//$sn_data->customer_id;
			$supp_id=$sn_data->supplier_id;
			$warranty_months='';//$sn_data->product_w;
			$sale_datetime='';//$sn_data->sale_datetime;
			$sale_reference_no='';//$sn_data->sale_reference_no;
			$reference_no=$sn_data->reference_no;
			$supp_name=$sn_data->supp_name;
			
			$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->pis_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;
				//print_r($supp_des[0]);
				//$product_id=$supp_des[0]->product_id;
			}
			
			
			
			//echo "Test";
			
			//get serial number grn details
			
			
			//echo $supp_id;
			
			
		}
		
		//check varanti avalable
		
	
		$st = array('product_id'=>$product_id,'product_name'=>$product_name,'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,'grn_no'=>$reference_no,'supp_name'=>$supp_name);
        echo json_encode($st);
		
	}
	
public function get_product_sn(){
        $str = $this->input->post('search_string');
		$srh_warehouse_id = $this->input->get('srh_warehouse_id');
		$service_item_avalable = $this->input->post('service_item_avalable');
		
		//echo "test";
       // $result = $this->Service_Model->get_product_sn($str);
		 $result=$this->Sales_Model->get_products_suggestions_get_by_warehouse_id($str,$srh_warehouse_id,$service_item_avalable);
        echo json_encode($result);
    }
	
	
	public function update_service_status()
	{
        $service_id = $this->input->post('service_id');
		
		//get sms apt
		//$sms_api=$this->Common_Model->check_option_valable_by_setting_id(2);
		
		$type = $this->input->get('type');
		$data_edit=array();
		
		
		$disMsg='';
		$prepared_user=0;
		$prepared_date_time=0;
		$prepared_status=0;
		
		$snd_to_supp_user=0;
		$snd_to_supp_date_time=0;
		$snd_to_supp_status=0;
		
		$ready_user=0;
		$ready_date_time=0;
		$ready_status=0;
		
		$hand_over_user=0;
		$hand_over_date_time=0;
		$hand_over_status=0;
		
		$send_to_sc_status=0;
		$send_to_sc_date_time=0;
		$send_to_sc_user=0;
		if($this->input->post('send_to_sc_status')=='Sent')  $send_to_sc_user=$this->session->userdata('ss_user_id');
		if($type=='send_to_sc_status'){
			$data_edit=array(
				'send_to_sc_status'=>$this->input->post('send_to_sc_status'),
				'send_to_sc_user'=>$send_to_sc_user,
				'send_to_sc_date_time'=>date("Y-m-d H:i:s"),
			);
		}
		
		$reserved_to_sc_status=0;
		$reserved_to_sc_date_time=0;
		$reserved_to_sc_user=0;
		if($this->input->post('reserved_to_sc_status')=='Reserved')  $reserved_to_sc_user=$this->session->userdata('ss_user_id');
		if($type=='reserved_to_sc_status'){
			$data_edit=array(
				'reserved_to_sc_status'=>$this->input->post('reserved_to_sc_status'),
				'reserved_to_sc_user'=>$reserved_to_sc_user,
				'reserved_to_sc_date_time'=>date("Y-m-d H:i:s"),
			);
		}
		

		$hand_over_to_tech_status=0;
		$hand_over_to_tech_date_time=0;
		$hand_over_to_tech_user=0;
		if($this->input->post('hand_over_to_tech_status')=='Handed Over')  $hand_over_to_tech_user=$this->session->userdata('ss_user_id');
		if($type=='hand_over_to_tech_status'){
			$data_edit=array(
				'hand_over_to_tech_status'=>$this->input->post('hand_over_to_tech_status'),
				'hand_over_to_tech_user'=>$hand_over_to_tech_user,
				'hand_over_to_tech_date_time'=>date("Y-m-d H:i:s"),
				'hand_over_to_tech_id'=>$this->input->post('hand_over_to_tech_id'),
			);
		}
		
		$return_from_tech_status=0;
		$return_from_tech_date_time=0;
		$return_from_tech_user=0;
		if($this->input->post('return_from_tech_status')=='Returned')  $return_from_tech_user=$this->session->userdata('ss_user_id');
		if($type=='return_from_tech_status'){
			$data_edit=array(
				'return_from_tech_status'=>$this->input->post('return_from_tech_status'),
				'return_from_tech_user'=>$return_from_tech_user,
				'return_from_tech_date_time'=>date("Y-m-d H:i:s"),
				'return_from_tech_note'=>$this->input->post('return_from_tech_note'),
			);
		}
		
		$return_to_branch_status=0;
		$return_to_branch_date_time=0;
		$return_to_branch_user=0;
		if($this->input->post('return_to_branch_status')=='Returned')  $return_to_branch_user=$this->session->userdata('ss_user_id');
		if($type=='return_to_branch_status'){
			$data_edit=array(
				'return_to_branch_status'=>$this->input->post('return_to_branch_status'),
				'return_to_branch_user'=>$return_to_branch_user,
				'return_to_branch_date_time'=>date("Y-m-d H:i:s"),
			);
		}
		
		$reserved_to_branch_status=0;
		$reserved_to_branch_date_time=0;
		$reserved_to_branch_user=0;
		if($this->input->post('reserved_to_branch_status')=='Reserved')  $reserved_to_branch_user=$this->session->userdata('ss_user_id');
		if($type=='reserved_to_branch_status'){
			$data_edit=array(
				'reserved_to_branch_status'=>$this->input->post('reserved_to_branch_status'),
				'reserved_to_branch_user'=>$reserved_to_branch_user,
				'reserved_to_branch_date_time'=>date("Y-m-d H:i:s"),
			);
		}
		
		
		if($this->input->post('prepared_status')=='Prepared')  $prepared_user=$this->session->userdata('ss_user_id');
		if($this->input->post('snd_to_supp_status')=='Send to Supplier')  $snd_to_supp_user=$this->session->userdata('ss_user_id');
		if($this->input->post('ready_status')=='Returned')  $ready_user=$this->session->userdata('ss_user_id');
		if($this->input->post('hand_over_status')=='Hand Over')  $hand_over_user=$this->session->userdata('ss_user_id');
		
		
		
		//if($this->input->post('serial_no')=='serial_no')  $hand_over_user=$this->session->userdata('ss_user_id');
		
		
		 
		if($type=='prepared'){
			$data_edit=array(
				'prepared_status'=>$this->input->post('prepared_status'),
				'prepared_user'=>$prepared_user,
				'prepared_date_time'=>date("Y-m-d H:i:s"),
			);
		}
		
		if($type=='snd_to_supp'){
			$data_edit=array(
				'snd_to_supp_status'=>$this->input->post('snd_to_supp_status'),
				'snd_to_supp_user'=>$snd_to_supp_user,
				'snd_to_supp_date_time'=>date("Y-m-d H:i:s"),
			);
		}
		
		if($type=='ready'){
			$data_edit=array(
				'ready_status'=>$this->input->post('ready_status'),
				'ready_user'=>$ready_user,
				'ready_date_time'=>date("Y-m-d H:i:s"),
				'ready_note'=>$this->input->post('ready_note'),
			);
		}
		
		if($type=='hand_over'){
			$data_edit=array(
				'hand_over_status'=>$this->input->post('hand_over_status'),
				'hand_over_user'=>$hand_over_user,
				'hand_over_date_time'=>date("Y-m-d H:i:s"),
			);
		}
		
		
		
		$disMsg='';
		$error=false;
		if($type=='serial_no'){
			
		//validate serial no correct
		$product_sn=$this->input->post('product_sn');
		$product_sn_new=$this->input->post('product_sn_new');
		
		$sn_data = $this->Sales_Model->check_serial_no_valid($product_sn_new);
		
		
		
		$is_registed_sn=count($sn_data);
		//print_r($sn_data);
		//echo "count:".$is_registed_sn;
		if($is_registed_sn){
			//echo "11111";
			$error=true;
			$disMsg="Serial no allredy registed";
		}else if(!$product_sn){
			//echo "2222";
			$error=true;			
		}else if(!$product_sn_new){
		//	echo "333";
			$error=true;	
		}else{
			//echo "444";
			$data = array(
				'pis_number' =>$product_sn_new
			);	
			if($this->purchases_model->change_product_sn_by_sn($product_sn,$data)) {
				//echo $this->db->last_query();
  				$this->Common_Model->add_user_activitie("Serial No Updated, GRN: , OLD SN:$product_sn New SN: $product_sn_new");
				
				$data_edit=array(
				'product_sn_new'=>$this->input->post('product_sn_new'),
				'product_sn_new_note'=>$this->input->post('product_sn_new_note'),
				'product_sn_new_upated_user'=>$this->session->userdata('ss_user_id'),
				'product_sn_new_upated_date'=>date("Y-m-d H:i:s"),
			);
				
  			} 
			else{
				$error=true;		
			}
  
 // echo $this->db->last_query();
			
		}
			
			
		}
		
		if(!$error){
			$_insert=$this->Service_Model->save_service($data_edit,$service_id);
			
			//$service_id=$this->uri->segment('3');
			if($type=='ready'){
				$data['service_details']=array();
				$product_name_des='';
				$send_phone_first='';
				$service_reference_no='';
				$service_charge='';
				$service_customer_id=0;
				if(isset($service_id)){
				$service_details=$this->Service_Model->get_service_details_by_id($service_id);
				$product_name_des=$service_details->service_rep_item_name;
				$send_phone_first=$service_details->service_walking_cus_phone;
				$service_reference_no=$service_details->service_reference_no;
				$service_customer_id=$service_details->service_customer_id;;
				$service_charge=number_format($service_details->service_charge, 2, '.', ',');
				}
				
				
				
				//status ready send message
				//$send_phone_first='0714617137';
				$message="SmartFix Service Center \nInv no : $service_reference_no \nStatus : Done \nAmount = $service_charge \nYour Job has been ready to Collect - 0112851615";
				//$message="SmartFixServiceCenter Sanath";
				//$myStr=123456789;

                //echo "send_phone_first:$service_customer_id";
				
				if($service_customer_id==1){
					$send_phone_first=$send_phone_first;//'0714617137';
                   // echo "<br/>1";
				}else{
                    //echo "<br/>2";
					if(!empty($service_customer_id)){
						$customer_details=$this->Customer_Model->get_customer_info($service_customer_id);
						$send_phone_first=$customer_details['cus_phone'];
						
						//echo "send_phone_first:".$send_phone_first;	
					}
				}
				//echo "send_phone_first:".$send_phone_first;
				$send_phone = substr($send_phone_first, 0, 10);	
				//$this->Common_Model->send_sms($message,$send_phone);	
				
				
				
				//var_dump($result);			
			}
			
			
			//end status ready send message
			
			
		}
			//echo $this->db->last_query();
        
        echo json_encode(array('service_id'=>$service_id,'error'=>"$error",'disMsg'=>$disMsg,));
	}
		
	public function service_add_row()
	{
		$product_id=$this->input->post('id');
		
		$rowCount=$this->input->post('rowCount');
		$warehouse_id=$this->input->post('warehouse_id');
		$service_datetime=$this->input->post('service_datetime');
		$service_return_date=$this->input->post('service_return_date');
		$service_customer_id=$this->input->post('service_customer_id');
		$product_charge_type=$this->input->post('product_charge_type');
		$service_diposit=$this->input->post('service_diposit');
		$service_responsible_person=$this->input->post('service_responsible_person');
		
		
		$pro_dlts=$this->Product_Models->get_product_by_id($product_id);
		
		
		//print_r($pro_dlts);
		$row_details='';
		$msg='';
		$error=false;
		
		$selbox='';
		//test 
		//$rowCount_e=1;
		$tmp_th_e=$rowCount;
		$pymnt_cheque_date='';
		$required_date=date('m/d/Y');
		$serviceitm_qty=1;
		
		//get pr item qty by id
		//$serviceitm_qty=
		
		$sub_total_item=0.00;
		
		
		//validate
		$this->load->library('form_validation');
		//$this->form_validation->set_rules('bank_id_'.$tmp_th_e, 'Bank', 'required');
		//if ($this->form_validation->run() != FALSE)
		
		if(!$warehouse_id){
			$error=true;
			$msg.="Project, ";
		}
		if(!$service_datetime){
			$error=true;
			$msg.="Service Date, ";
		}
		if(!$service_return_date){
			$error=true;
			$msg.="Return Date, ";
		}
		if(!$service_customer_id){
			$error=true;
			$msg.="Service Place, ";
		}
		if(!$service_responsible_person){
			$error=true;
			$msg.="Responsible Person , ";
		}
		
		//$error=false;
		if (!$error)
        {
             $itm_charge_type=$product_charge_type;
			 $product_service_charge=0.00;
			
			 
			 
			$row_details="
			<tr id=\"row_e_$tmp_th_e\">
			<td class=\"text-left\">
			$pro_dlts->product_name
			<input type=\"hidden\" style=\"width:100%; text-align:left\" name=\"row_e[$tmp_th_e][product_name][]\" id=\"product_name_$tmp_th_e\" value=\"$pro_dlts->product_name\" class=\"pymnt_amount\">
			<input type=\"hidden\" style=\"width:100%; text-align:left\" name=\"row_e[$tmp_th_e][product_id][]\" id=\"product_id_$tmp_th_e\" value=\"$pro_dlts->product_id\" class=\"product_id\">
			</td>
			<td>$pro_dlts->unit_code
			<input type=\"hidden\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][product_unit][]\" id=\"product_unit_$tmp_th_e\" value=\"$pro_dlts->product_unit\" class=\"product_unit\">
			</td>
			
			<td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][serviceitm_qty][]\" id=\"serviceitm_qty_$tmp_th_e\" value=\"$serviceitm_qty\" class=\"serviceitm_qty\" onchange=\"changeQtyByProductID(this.value,$tmp_th_e);\" onclick=\"this.select(); setTmpVal(this.value);\"></td>
			
			<td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][product_service_charge][]\" id=\"product_cost_$tmp_th_e\" value=\"$product_service_charge\" class=\"product_service_charge\"></td>
			
			<td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][serviceitm_dis][]\" id=\"serviceitm_dis_$tmp_th_e\" value=\"0\" class=\"serviceitm_dis\" onchange=\"changeDiscountByProductID(this.value,1);\" onclick=\"this.select(); setTmpVal(this.value);\">
			<input type=\"hidden\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][serviceitm_dis_val][]\" id=\"serviceitm_dis_val_$tmp_th_e\" value=\"0\" class=\"serviceitm_dis_val\">
			</td>
			<td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][sub_total_item][]\" id=\"sub_total_item_$tmp_th_e\" value=\"$sub_total_item\" class=\"\"></td>
			<td><a onclick=\"deleteServiceItem(1)\"><i style=\"cursor:pointer;\" title=\"Remove\" id=\"1446800197032\" class=\"fa fa-times tip podel\"></i></a></td>
			</tr>
			";
			
		 $e = array('status' =>1,'row_details' =>$row_details);
		 echo json_encode($e);
		
		}else {
			$e = array('status' =>0,'row_details' =>'','msg'=>$msg);
		 	echo json_encode($e);
		}
		
	}
	
	public function service_print()
	{	
		$service_id=$this->uri->segment('3');
		$data['service_details']=$this->Service_Model->get_service_details_by_id($service_id);
		$service_details=$data['service_details'];
		
		//get sale item list
		$data['service_item_list']=$this->Service_Model->get_service_items_by_id($service_id);
		
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($service_details->service_customer_id);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['service_details']->warehouse_id);
		
		//print_r($data['service_details']);
		$data['service_payments_list']= $this->Sales_Model->get_service_payments_by_sale_id($service_id);	
		
		//get sale info
		$sale_id='';
		$sale_total='';
		$sale_details=$this->Sales_Model->get_sale_info_by_sale_id($service_id);
		if(!empty($sale_details)){
		$sale_id=$sale_details['sale_id'];
		$sale_total=$sale_details['sale_total'];
		}
		
		$data['sale_id']='';
		$data['sale_total']='';
		$data['sale_item_list']='';
		if(!empty($sale_total)){
			$data['sale_id']=$sale_id;
			$data['sale_total']=$sale_total;
			$data['sale_item_list']=$this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		}
		
		//	$data['service_details_select']=$this->Service_Details_Model->get_all_details_by_id($service_id);
		
	//	$data['service_types']=$this->Service_Details_Model->get_all_types();
		
			$data['service_details_select']=$this->Service_Details_Model->get_all_details_by_id($service_id);
		$data['service_details_items']=$this->Service_Details_Model->get_all_enable_details();
		$data['service_types']=$this->Service_Details_Model->get_all_types();
		
	//	echo $this->db->last_query();
		
		//print_r($data['sale_item_list']);
        $this->load->view('models/service_print',$data);
	}
		
		
			public function service_print_invoice()
	{	
		$service_id=$this->uri->segment('3');
		$data['service_details']=$this->Service_Model->get_service_details_by_id($service_id);
		$service_details=$data['service_details'];
		
		//get sale item list
		$data['service_item_list']=$this->Service_Model->get_service_items_by_id($service_id);
		
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($service_details->service_customer_id);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['service_details']->warehouse_id);
		
		//print_r($data['service_details']);
		$data['service_payments_list']= $this->Sales_Model->get_service_payments_by_sale_id($service_id);	
		
		//get sale info
		$sale_id='';
		$sale_total='';
		$sale_details=$this->Sales_Model->get_sale_info_by_sale_id($service_id);
		if(!empty($sale_details)){
		$sale_id=$sale_details['sale_id'];
		$sale_total=$sale_details['sale_total'];
		}
		
		
			$data['sale_details']=$sale_details;
			
		$data['sale_id']='';
		$data['sale_total']='';
		$data['sale_item_list']='';
		if(!empty($sale_total)){
			$data['sale_id']=$sale_id;
			$data['sale_total']=$sale_total;
			$data['sale_item_list']=$this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		}
		
		//print_r($data['sale_item_list']);
        $this->load->view('models/service_print_invoice',$data);
	}
		
	
	//Requisition details view
	public function view()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		
		//get sale id
		$service_id=$this->uri->segment('3');
		$data['service_item_list']= $this->Service_Model->get_service_item_list_by_service_id($service_id);
		$data['service_details']= $this->Service_Model->get_service_info($service_id);
		
	
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['service_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['service_details']['warehouse_id']);
		
			
		
		$data['service_id']=$service_id;
        $this->load->view('service_view',$data);
	}

	//Requisition add page
	public function add_service_payments()
	{
		$service_pymnt_amount=$this->input->post('service_pymnt_amount');
		$service_id=$this->input->post('service_id');
		$service_pymnt_ref_no=$this->input->post('service_pymnt_ref_no');
		$service_pymnt_paying_by=$this->input->post('service_pymnt_paying_by');
		$service_pymnt_date_time=$this->input->post('service_pymnt_date_time');
		$service_pymnt_date_time_send=date('Y-m-d H:i:s', strtotime($service_pymnt_date_time));
		$service_pymnt_cheque_no=$this->input->post('service_pymnt_cheque_no');
		$service_pymnt_crdt_card_no=$this->input->post('service_pymnt_crdt_card_no');
		$service_pymnt_crdt_card_holder_name=$this->input->post('service_pymnt_crdt_card_holder_name');
		$service_pymnt_crdt_card_month=$this->input->post('service_pymnt_crdt_card_month');
		$service_pymnt_crdt_card_year=$this->input->post('service_pymnt_crdt_card_year');
		$service_pymnt_crdt_card_type=$this->input->post('service_pymnt_crdt_card_type');
		$service_type = $this->input->post('service_type');

		$service_pymnt_note=$this->input->post('service_pymnt_note');
		$user_id=$this->session->userdata('ss_user_id');
		$service_pymnt_added_date_time=date("Y-m-d H:i:s");
		$service_pymnt_id='';
		
        $this->load->library('form_validation'); //form validation lib
        $this->form_validation->set_rules('service_pymnt_amount', 'Amount', 'required');
		if($service_pymnt_paying_by=='Credit Card'){
			$this->form_validation->set_rules('service_pymnt_crdt_card_type', 'Card Type', 'required');
			$this->form_validation->set_rules('service_pymnt_crdt_card_no', 'Credit Card No', 'required');
			$this->form_validation->set_rules('service_pymnt_crdt_card_holder_name', 'Holder Name', 'required');
			$this->form_validation->set_rules('service_pymnt_crdt_card_month', 'Month', 'required');
			$this->form_validation->set_rules('service_pymnt_crdt_card_year', 'Year', 'required');
		}
		if($service_pymnt_paying_by=='Cheque'){
			$this->form_validation->set_rules('service_pymnt_cheque_no', 'Cheque No', 'required');
		}
		$this->form_validation->set_rules('service_id', 'System Error', 'required');


        if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
			$data=array(
				'service_pymnt_amount'=>$service_pymnt_amount,	
				'service_pymnt_ref_no'=>$service_pymnt_ref_no,
				'service_pymnt_paying_by'=>$service_pymnt_paying_by,
				'service_pymnt_date_time'=>$service_pymnt_date_time_send,
				'service_pymnt_note'=>$service_pymnt_note,
				'user_id'=>$user_id,
				'service_id'=>$service_id,
				'service_pymnt_added_date_time'=>$service_pymnt_added_date_time,
				'service_pymnt_cheque_no'=>$service_pymnt_cheque_no,
				'service_pymnt_crdt_card_no'=>$service_pymnt_crdt_card_no,
				'service_pymnt_crdt_card_holder_name'=>$service_pymnt_crdt_card_holder_name,
				'service_pymnt_crdt_card_type'=>$service_pymnt_crdt_card_type,
				'service_pymnt_crdt_card_month'=>$service_pymnt_crdt_card_month,
				'service_pymnt_crdt_card_year'=>$service_pymnt_crdt_card_year,
				'service_payment_type' => $service_type
			);
			
               if ($this->Service_Model->save_service_payments($data,$service_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);
               }
		}
	}	
	
	//Requisition payment page 
	public function payments()
	{
        $data['service_id'] = $this->input->get('id');
        $data['service_type'] = $this->input->get('service_type');
        $this->load->view('models/service_payment',$data);	
	}
	
	
/*	public function update_service_status()
	{
        $service_id = $this->input->post('service_id');
		$disMsg='';
		
				$data_edit=array(
				'service_prepared_status'=>$this->input->post('service_prepared_status'),
				'service_authorized_status'=>$this->input->post('service_authorized_status'),
			    'service_checked_status'=>$this->input->post('service_checked_status'),
				'service_approved_status'=>$this->input->post('service_approved_status'),
			);
			$_insert=$this->Service_Model->save_service($data_edit,$service_id);
			
			//echo $this->db->last_query();
        
        echo json_encode(array('service_id'=>$service_id,'error'=>'','disMsg'=>$disMsg,));
	}
	*/
	
	//Requisition save 
	//Requisition item save
	//Add service items to 54 table
	public function save_service()
	{
		
		//echo "cus:".$this->input->post('service_customer_id');
		//	die();
		$warehouse_id=$this->input->post('warehouse_id');
		$service_id=$this->input->post('service_id');
		$rowCount=$this->input->post('rowCount');
		
		//$service_return_date=date('Y-m-d H:i:s', strtotime($this->input->post('service_return_date')));
		$service_customer_id=$this->input->post('service_customer_id');
		$product_id=intval($this->input->post('product_id'));
		$product_sn=$this->input->post('product_sn');
		$service_diposit=$this->input->post('service_diposit');
		$service_responsible_person=$this->input->post('service_responsible_person');
		//$=$this->input->post('');
		
		
		$service_net_total=$this->input->post('service_net_total');
		$service_vat=$this->input->post('service_vat');
		$service_discount=$this->input->post('service_discount');
		$service_discount_amt=$this->input->post('service_discount_amt');
		$current_mileage=$this->input->post('current_mileage');
		$nature_of_work=$this->input->post('nature_of_work');
		$service_warranty_available=intval($this->input->post('service_warranty_available'));
			$power_on_status=intval($this->input->post('power_on_status'));
		

		
		$service_reference_no=$this->input->post('service_reference_no');
		$service_type=$this->input->post('service_type');
		$service_item_avalable=$this->input->post('service_item_avalable');
		
		$detail_item=$this->input->post('detail_item');
		
		
	
		
		$error='';
		$disMsg='';
		$lastid='';
		//$service_id='';
		//echo 'dis:'.$service_discount;
		
		if(!$error){
			$data_save=array(
			'service_reference_no'=>$service_reference_no,
				'service_item_avalable'=>$service_item_avalable,
				
				'service_customer_id'=>$service_customer_id,
				'product_id'=>intval($product_id),
				'product_sn'=>$product_sn,
				'service_net_total'=>$service_net_total,
				'service_diposit'=>$service_diposit,
				'service_vat'=>$service_vat,
				'service_discount'=>$service_discount,
				'service_discount_amt'=>$service_discount_amt,
				 'warehouse_id'=>$warehouse_id,
				 'service_responsible_person'=>$service_responsible_person,
				 'nature_of_work'=>$nature_of_work,
				 'current_mileage'=>$current_mileage,
				 'service_warranty_available'=>intval($service_warranty_available),
				  'service_remark'=>$this->input->post('service_remark'),
				  'estimate_amount'=>$this->input->post('estimate_amount'),
				  'service_charge'=>floatval($this->input->post('service_charge')),
				  'supp_id'=>intval($this->input->post('supp_id')),
				  'service_type'=>$this->input->post('service_type'),
				   'service_rep_item_sn'=>$this->input->post('service_rep_item_sn'),
				  'service_rep_item_name'=>$this->input->post('service_rep_item_name'),
				  'service_marks'=>$this->input->post('service_marks'),
				   'service_burn'=>$this->input->post('service_burn'),
				    'service_physical'=>$this->input->post('service_physical'),
					 'service_tempered'=>$this->input->post('service_tempered'),
					  'service_scratch'=>$this->input->post('service_scratch'),
					   'service_walking_cus_name'=>$this->input->post('service_walking_cus_name'),
					    'service_walking_cus_phone'=>$this->input->post('service_walking_cus_phone'),
						
						 'no_power'=>$this->input->post('no_power'),
						 'water_damage'=>$this->input->post('water_damage'),
						 'no_service'=>$this->input->post('no_service'),
						 'service_drop'=>$this->input->post('service_drop'),
						 'phone_struck'=>$this->input->post('phone_struck'),
						 'auto_switch_off'=>$this->input->post('auto_switch_off'),
						 'speaker'=>$this->input->post('speaker'),
						 'mic'=>$this->input->post('mic'),
						 'ringer'=>$this->input->post('ringer'),
						 'lock'=>$this->input->post('lock'),
						 'drop'=>$this->input->post('drop'),
						 'short'=>$this->input->post('short'),
						 'display'=>$this->input->post('display'),
						 'charging'=>$this->input->post('charging'),
						 'other'=>$this->input->post('other'),
						 'aa_battery'=>$this->input->post('aa_battery'),
						 'aa_charger'=>$this->input->post('aa_charger'),
						  'aa_back_cover'=>$this->input->post('aa_back_cover'),
						 'aa_mem_card'=>$this->input->post('aa_mem_card'),
						  'aa_others'=>$this->input->post('aa_others'),
						 'short'=>$this->input->post('short'),
						 'power_on_status'=>$this->input->post('power_on_status'),
						 
						  'pc_1'=>$this->input->post('pc_1'),
						  'pc_2'=>$this->input->post('pc_2'),
						  'pc_3'=>$this->input->post('pc_3'),
						  'pc_4'=>$this->input->post('pc_4'),
						  'pc_5'=>$this->input->post('pc_5'),
						  'pc_6'=>$this->input->post('pc_6'),
						  'pc_7'=>$this->input->post('pc_7'),
						  'pc_8'=>$this->input->post('pc_8'),
						  'pc_9'=>$this->input->post('pc_9'),

				);
			
			
			

			if($service_id){
				
				//echo '111111111111';
				
				$service_id=$service_id;
				$this->Service_Model->save_service($data_save,$service_id);
				
				//echo $this->db->last_query();
				//delete old req items
				$this->Service_Model->delete_old_service_items($service_id);
				$disMsg='Requisition successfully updated';
				
				
				//development by nirmala 20-07-17
				$item_data_selected=[];
				$count=0;
				if($detail_item){
				foreach($detail_item as $index=>$row){
					$item_data_selected[$count]=array(
						'service_id' => $service_id, 
						'mstserdtl_id' => $row,
						'mstserdtpe_id' => 1,
								 
						);
						$count++;
				}
				
			}
		
				
			$this->Service_Model->save_detail_items($item_data_selected,$service_id);
				
			}else {
				$service_datetime=date('Y-m-d H:i:s');
				$data_save['service_datetime']=$service_datetime;
				
				//create ref no
				//$query=$this->Service_Model->get_next_ref_no();
				//$result = $query->row();
				//print_r($result);
				//$service_reference_no=sprintf("%05d", $result->service_id+1);
				
				
				//start get next referance no
				$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
				$warehouse_code=$warehouse_dtls['code'];
				$warehouse_last_id=(1+$this->Common_Model->get_next_warehouse_ref_no($warehouse_id,'warehouse_id','warehouse_last_id','service'));
				$service_reference_no=$warehouse_code.'/SER/'.sprintf("%04d",$warehouse_last_id);
				//end get next referance no
				
				$data_save['warehouse_last_id']=$warehouse_last_id;
				$data_save['service_reference_no']=$service_reference_no;
			$_insert=$this->Service_Model->save_service($data_save,'');
			
			
			$lastid=$this->db->insert_id();
			
			// start service details
			if($lastid){
				$item_data_selected=[];
				$count=0;
				if($detail_item){
				foreach($detail_item as $index=>$row){
					$item_data_selected[$count]=array(
						'service_id' => $lastid, 
						'mstserdtl_id' => $row,
						'mstserdtpe_id' => 1,
								 
						);
						$count++;
				}

				
				$this->Service_Model->save_detail_items($item_data_selected,$lastid);
			}
			}
			
			
			 //end service details
			
			$service_id=$lastid;
			$disMsg='Requisition successfully added';
			
			//set sms
			if($this->input->post('service_customer_id')==1){
				$send_phone_first=$this->input->post('service_walking_cus_phone');//'0714617137';
			}
			else{
				//get customer mobile
				//echo "service_customer_id:".$this->input->post('service_customer_id');
				$customer_details=$this->Customer_Model->get_customer_info($this->input->post('service_customer_id'));
				//print_r($customer_details);
				$send_phone_first=$customer_details['cus_phone'];
			}
				$message="SmartFix Service Center \nJob no : $service_reference_no \nWe will update you with the Job status near in future \nThank You!";
				//$message="SmartFixServiceCenter Sanath";
				//$myStr=123456789;
				$send_phone = substr($send_phone_first, 0, 10);	
			//	$this->Common_Model->send_sms($message,$send_phone);	
				//echo "send sms";
			//end send sms
			}
			
			//
			
			//insert sale item data
			$row=$this->input->post('row_e');
			$rowCount=$this->input->post('rowCount');
			//echo 'test:'.$rowCount;
			$data_item=array();

		
		}	
		
	//	echo "Test:".$service_id;;
		
		$this->session->set_flashdata('message', 'Service successfully added!');
		
		echo json_encode(array('service_id'=>$service_id,'error'=>$error,'disMsg'=>$disMsg,));
	}

	//Requisition reference no jenarate	
	public function get_next_ref_no(){
		$query=$this->Service_Model->get_next_ref_no();
		$result = $query->row();
		//print_r($result);
		$service_reference_no=sprintf("%05d", $result->service_id+1);
		$service_reference_no=$service_reference_no;
		echo json_encode(array('service_reference_no'=>$service_reference_no));
	}
	
	//Requisition 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->Service_Model->get_avalable_product_qty($product_id,$warehouse_id);
		echo json_encode(array('remmnaingQty'=>$data['total']));
	}
	
	//equisition details view
	public function service_details()
	{
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = '';
		
		//get sale id
		$service_id=$this->uri->segment('3');
		$data['technician_list'] = $this->User_Model->get_user_list_by_group_id(7);
		if(isset($service_id)){
			$data['service_details']=$this->Service_Model->get_service_details_by_id($service_id);
			$data['sale_payments_list']= $this->Sales_Model->get_service_payments_by_sale_id($service_id);	
			//$data['serviceitm_list']=$this->Service_Model->get_service_items_by_id($service_id);
		}
		$data['service_id'] =$service_id;
		
		//get sale info
		$sale_id='';
		$sale_total='';
		$sale_details=$this->Sales_Model->get_sale_info_by_sale_id($service_id);
		if(!empty($sale_details)){
		$sale_id=$sale_details['sale_id'];
		$sale_total=$sale_details['sale_total'];
		}
		
		$data['sale_id']='';
		$data['sale_total']='';
		$data['sale_item_list']='';
		if(!empty($sale_total)){
			$data['sale_id']=$sale_id;
			$data['sale_total']=$sale_total;
			$data['sale_item_list']=$this->Sales_Model->get_sale_item_list_by_sale_id($sale_id);
		}
		
		
		$data['service_details_select']=$this->Service_Details_Model->get_all_details_by_id($service_id);
		$data['service_details_items']=$this->Service_Details_Model->get_all_enable_details();
		$data['service_types']=$this->Service_Details_Model->get_all_types();
		
        $this->load->view('service_details',$data);
		
	}

	//Requisition add form
    public function service_add()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'service_add';
		
		
		
		$service_id=$this->uri->segment('3');
		$data['serviceitm_list']=array();
		if(isset($service_id)){
			$data['service_details']=$this->Service_Model->get_service_details_by_id($service_id);
			$data['serviceitm_list']=$this->Service_Model->get_service_items_by_id($service_id);
		}
		
		$data['service_id'] =$service_id;
		//get suppliers list
		$data['suppliers'] = $this->Supplier_Model->get_all_supplier();
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['tax_rates_list'] = $this->Tax_Rates_Model->get_all_tax_rates();
		$data['customer_list'] = array();//$this->Customer_Model->get_all_customers();
		$data['product_list'] = array();//$this->Sales_Model->get_products_suggestions_for_service();
		//echo $this->db->last_query();
		$data['all_product_list'] = array();//$this->Product_Models->getProducts("","","");
		$data['sales_list'] = array();//$this->Sales_Model->get_all_sales();
		//echo $this->db->last_query();
		$data['status_list'] = $this->Common_Model->get_all_status();
		//$data['pr_list'] = $this->Requisition_Model->get_all_requisition_names();
		$data['service_details_select']=$this->Service_Details_Model->get_all_details_by_id($service_id);
		$data['service_details_items']=$this->Service_Details_Model->get_all_enable_details();
		$data['service_types']=$this->Service_Details_Model->get_all_types();
		
        $this->load->view('service_add',$data);
    }
	
	
public function suggestions($value='')
    {
		
		//print_r($_GET);
		$term=$this->input->get('term');
		$in_type=$this->input->get('t');
		$cus_type=$this->input->get('cus_type');
		$city_id=$this->input->get('city_id');
		$cat_id=$this->input->get('cat_id');
		$srh_warehouse_id=$this->input->get('srh_warehouse_id');
		$cat_id=$this->input->get('cat_id');
		$manual_search= '';//$this->input->get('manual_search');
		
//	echo $status;	
		//if()
		if($cus_type == 'Special' && $in_type=='Wholesale'){
//		if enabled
		
		$result = $this->Country_Model->get_area_info_by_id($city_id);
		$status = $result[0]['status'];

		if($status == 1){
		//$data['sales'] = $this->Cus_Pricing_Model->get_products_suggestions_sale($term,$city_id);
		//$data['sales'] = $this->Sales_Model->get_products_suggestions($term);
		}
		
		else {
		//$data['sales'] = $this->Sales_Model->get_products_suggestions($term);
		}//end if
		
		}
		else if($cus_type == 'Normal'){
		//$data['sales'] = $this->Sales_Model->get_products_suggestions($term);
 	}
	
	
	$data['sales'] = $this->Sales_Model->get_products_suggestions($term,$cat_id,$srh_warehouse_id);
		
		$json = array();
		$json_itm=array();
		foreach ($data['sales'] as $row)
		{
			//set price
			$price_tmp=0;
			if($in_type=='Wholesale'){
			$price_tmp=floatval($row['wholesale_price']);
			}else {
			$price_tmp=$row['product_price'];
			}
			
			
			$price_tmp_sn='';
			$price_tmp_sn=$row['pis_cash_price'];
			if($price_tmp_sn){
				$price_tmp=$price_tmp_sn;
				
			}else{
				$price_tmp=$price_tmp;
			}
			
		//	echo "price_tmp:".$price_tmp;
			
		//	$price_tmp=$row['product_price'];
			//quantity for label
				$quantity =0;
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$purchased_qty=0;
				$sales_return_qty=0;
				$product_damaged_qty=0;
				$sold_qty=0;
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($this->session->userdata('ss_warehouse_id'),$row['product_id']);
				$quantity = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 2, '.', ',');
			//end qty for label
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_sn=$row['pis_number'];
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_w=$row['product_w'];
			$product_sn_exissts=$row['product_sn_exissts'];
			$product_price=$price_tmp;
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			//$extraName.=", Serial No: $product_sn";
			$extraName.=",  Price: ".number_format($product_price, 2, '.', ',').", Qty. :".$quantity;			
			
			$is_search_by_sn=0;
			if($row['pis_number']==$term){
				$is_search_by_sn=1;
			}
			
			//product have serial no get grn item serial table cost, val empty set def val
			//if($product_sn_exissts){
				//get cost by sn
				//	get_serial_no_supp_id($sn='');
				
			//}
			
			$json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $product_price,
					'product_part_no'=> $row['product_part_no'],
					'item_cost'=> $row['product_cost'],
					'product_sn'=> $row['pis_number'],
					'pis_cost_price'=> $row['pis_cost_price'],
					'product_w'=> $product_w,
					'product_sn_exissts'=> $product_sn_exissts,
					'is_search_by_sn'=> $is_search_by_sn,
					'product_oem_part_number'=> $row['product_oem_part_number'],
                    'value'=> $row['product_name']." (".$row['product_code'].")",
                    'label'=> $row['product_name']." (".$row['product_code'].")$extraName | SN: $row[pis_number]"
                    );
					
					//echo "Test:";
					array_push($json,$json_itm);	
					
		}	
		
		
		
		
		$data['sales_non_seril'] = $this->Sales_Model->get_non_serial_products_suggestions($term,$cat_id);
		foreach ($data['sales_non_seril'] as $row)
		{
			//set price
		//	$price_tmp=0;
			
		//	$price_tmp=$row['product_price'];
		$price_tmp=0;
			if($in_type=='Wholesale'){
			$price_tmp=floatval($row['wholesale_price']);
			}else {
			$price_tmp=$row['product_price'];
			}
			//quantity for label
				$quantity =0;
				$transferd_qty=0;
				$transfer_reseve_qty=0;
				$purchased_qty=0;
				$sales_return_qty=0;
				$product_damaged_qty=0;
				$sold_qty=0;	
				
				$transferd_qty=$this->Transfer_Model->getTransferdQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$transfer_reseve_qty=$this->Transfer_Model->getTransferResevedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$sold_qty=$this->Sales_Model->getSoldQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$purchased_qty=$this->Purchases_Model->getPurchasedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$product_damaged_qty=$this->Product_Damage_Model->getProductDamagedQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				
				$sales_return_qty=$this->Sales_Return_Model->getSalesReturnQtyByWarehouseId($srh_warehouse_id,$row['product_id']);
				$quantity = number_format(($purchased_qty+$transfer_reseve_qty+$sales_return_qty-$sold_qty-$transferd_qty-$product_damaged_qty), 0, '.', ',');
			//end qty for label
			$product_name=$row['product_name'];
			$product_code=$row['product_code'];
			$product_sn='';
			$product_part_no=$row['product_part_no'];
			$product_oem_part_number=$row['product_oem_part_number'];
			$product_id=$row['product_id'];
			$product_w='';//need check
			$product_price=$price_tmp;
			$sendParameters="'$product_id','$product_name','$product_code','$product_price'";
			$sendParameters="$product_id,$product_name,$product_code,$product_price";
			$extraName='';
			if($product_sn){
				//$extraName.=", Serial No: $product_sn";
			}
			$extraName.=", Selling Price: ".number_format($product_price, 2, '.', ',')." ,Qty. :".$quantity;			
			
			//$json_itm=array();
			//if($srh_warehouse_id!=2){//not smart phone maharagama
			
			$add_details=0;
			
		//	if($quantity){
			///	$add_details=1;
		//	}
		
		
		if($srh_warehouse_id==9 || $srh_warehouse_id==10 || $srh_warehouse_id==11 || $srh_warehouse_id==13){
		    if($quantity){
		        $add_details=1;
		    }
		    
		}else /*{
		    $add_details=1;
		}*/
		if($srh_warehouse_id == 15){
			if($term == "111111"){
				 $add_details=1;
			}else if($term == "222222"){
				$add_details=1;
			}
		}
		
			
			if($add_details)
			{
			$json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $price_tmp,
					'product_part_no'=> $row['product_part_no'],
					'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);		
    }
	
	
	
	//Requisition product items get
	 public function suggestions_del($value='')
    {
		$term=$this->input->get('term');
		$data['service'] = $this->Service_Model->get_products_suggestions($term);
		$json = array();
		//echo "Count:".count($data['service']);
		//print_r($data['service']);
		foreach ($data['service'] as $row)
		{
			$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=$row['product_price'];
			$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";
			
			 $json_itm=array(
			 		'id'=> $row['product_id'],
					'product_id'=> $row['product_id'],
					'product_code'=> $row['product_code'],
					'product_name'=> $row['product_name'],
					'product_price'=> $row['product_price'],
					'product_part_no'=> $row['product_part_no'],
					'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 service_details_print()
	{
		
		$service_id=$this->input->get('service_id');
		$data['service_details']= $this->Service_Model->get_service_info($service_id);
		
		//get sale item list
		$data['service_item_list']= $this->Service_Model->get_service_item_list_by_service_id($service_id);
		
		$data['customer_details']= $this->Customer_Model->get_customer_info($data['service_details']['customer_id']);
		$data['warehouse_details']= $this->Warehouse_Model->get_warehouse_info($data['service_details']['warehouse_id']);
		
		$data['cr_limit_list'] = $this->Common_Model->get_all_cr_limit();
		
	
		
		//echo 'test';
		//print_r($data['service_payments_list']);
        $this->load->view('models/service_print',$data);
	}
	

	
	//Service list
	public function list_service()
	{
	$requestData= $_REQUEST;
	$search_key=$this->input->get('search');

	$search_key_val=$search_key['value'];

	$start=$this->input->get('start');

	$length=$this->input->get('length');
	
	$columns = array( 
		0 =>'service_id', 
		1 => 'service_id',
		2=> 'service_id',
		3 =>'service_id', 
		4 => 'service_id',
		5=> 'service_id'
	);
	
	$data = array();
	
	$warehouse_id=$this->input->get('warehouse_id');
	$service_item_avalable=$this->input->get('service_item_avalable');
	//echo "service_item_avalable:$service_item_avalable";
	//$service = $this->Service_Model->get_all_service($warehouse_id);
	$service = $this->Service_Model->get_all_service($warehouse_id,"","","","","","",$service_item_avalable,$start,$length,$search_key_val,'');
	
	$totalData =$this->Service_Model->get_all_service($warehouse_id,"","","","","","",$service_item_avalable,'','',$search_key_val,'get_count');
	//$totalData = count($service);
	$totalFiltered = $totalData;  
	
	foreach ($service as $row){
		$nestedData=array(); 
		$service_id=$row['service_id'];
		$total_paid_amount='';
		
		$nestedData[] = $row['service_reference_no'];
		$nestedData[] = $row['service_item_avalable'];
		$nestedData[] = $row['service_type'];
		$nestedData[] =$row['cus_name']." (".$row['service_walking_cus_name']." / ".$row['service_walking_cus_phone'].")";
			$nestedData[]=$row['service_rep_item_name'];
				$nestedData[]=$row['service_rep_item_sn'];
		//$nestedData[]=$row['supp_company_name'];
		$nestedData[] = date('d/M/Y', strtotime($row['service_datetime']));
		
		$nestedData[] = $row['service_charge'];
		$prepared_status_dis='';
		$checked_status_dis='';
		$approved_status_dis='';
		$authorized_status_dis='';
		
		//$nestedData[] = $row['service_id'];
		$actionTxtDisble='';
		$actionTxtEnable='';
		$actionTxtUpdate='';
		$actionTxtDelete='';
		
		$url=base_url("service/service_details?service_id=$service_id");
		$actionTxtUpdate='<a onClick="fbs_click('.$row['service_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().'service/details/'.$service_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().'service/details/'.$service_id.'"><i class="fa fa-file-text-o"></i> Service Details</a></li>
							 <li><a href="'.base_url().'service/manage/'.$service_id.'"><i class="fa fa-file-text-o"></i> Update Service Details</a></li>
                            <li><a onClick="fbs_click('.$row['service_id'].')" data-toggle="modal" href="#" data-placement="top" data-original-title="Edit suppliers"><i class="fa fa-print"></i> Print Service</a></li>
							
							
							
                            </ul></div>';
		
		
		if (empty($row['prepared_status'])) {
		  $prepared_status_dis = '<span class="label label-warning">Pending</span>';
		}else if($row['prepared_status']=='Prepared'){
			$prepared_status_dis = '<span class="label label-success">Prepared</span>';
		}
		
		if (empty($row['snd_to_supp_status'])) {
		  $checked_status_dis = '<span class="label label-warning">Pending</span>';
		}else if($row['snd_to_supp_status']=='Send to Supplier'){
			$checked_status_dis = '<span class="label label-success">Send to Supplier</span>';
		}
		 if($row['service_warranty_available']=='0') $checked_status_dis ='';
		
		
		if (empty($row['ready_status'])) {
		  $approved_status_dis = '<span class="label label-warning">Pending</span>';
		}else if($row['ready_status']=='Returned'){
			$approved_status_dis = '<span class="label label-success">Ready</span>';
		}
		if($row['service_warranty_available']=='0') $approved_status_dis ='';
	
//	$approved_status_dis=$approved_status_dis.$row['service_warranty_available'];
		
		
		if (empty($row['hand_over_status'])) {
		  $authorized_status_dis = '<span class="label label-warning">Pending</span>';
		}else if($row['hand_over_status']=='Hand Over'){
			$authorized_status_dis = '<span class="label label-success">Hand Over</span>';
		}
		if($row['service_item_avalable']=='Showroom') $authorized_status_dis ='';
		

		$send_to_sc_status_des='';
		if (empty($row['send_to_sc_status'])) {
			$send_to_sc_status_des = '<span class="label label-warning">Pending</span>';
		}else{
			$send_to_sc_status_des = "<span class='label label-success'>$row[send_to_sc_status]</span>";
		}
		
$reserved_to_sc_status_des='';
if (empty($row['reserved_to_sc_status'])) {
	$reserved_to_sc_status_des = '<span class="label label-warning">Pending</span>';
}else{
	$reserved_to_sc_status_des = "<span class='label label-success'>$row[reserved_to_sc_status]</span>";
}

$hand_over_to_tech_status_des='';
if (empty($row['hand_over_to_tech_status'])) {
	$hand_over_to_tech_status_des = '<span class="label label-warning">Pending</span>';
}else{
	$hand_over_to_tech_status_des = "<span class='label label-success'>$row[hand_over_to_tech_status]</span>";
}
 if($row['service_warranty_available']=='1') $hand_over_to_tech_status_des ='';

$return_from_tech_status_des='';
if (empty($row['return_from_tech_status'])) {
	$return_from_tech_status_des = '<span class="label label-warning">Pending</span>';
}else{
	$return_from_tech_status_des = "<span class='label label-success'>$row[return_from_tech_status]</span>";
}
 if($row['service_warranty_available']=='1') $return_from_tech_status_des ='';

$return_to_branch_status='';
if (empty($row['return_to_branch_status'])) {
	$return_to_branch_status = '<span class="label label-warning">Pending</span>';
}else{
	$return_to_branch_status = "<span class='label label-success'>$row[return_to_branch_status]</span>";
}

$reserved_to_branch_status='';
if (empty($row['reserved_to_branch_status'])) {
	$reserved_to_branch_status = '<span class="label label-warning">Pending</span>';
}else{
	$reserved_to_branch_status = "<span class='label label-success'>$row[reserved_to_branch_status]</span>";
}

	
	

		
		
		
                            
                            
                            		$nestedData[] = $prepared_status_dis;
	//	$nestedData[] =$send_to_sc_status_des;
	//	$nestedData[] =$reserved_to_sc_status_des;
		$nestedData[] =$hand_over_to_tech_status_des;
		$nestedData[] =$return_from_tech_status_des;
		$nestedData[] = $checked_status_dis;
		$nestedData[] = $approved_status_dis;
	//	$nestedData[] =$return_to_branch_status;
	//	$nestedData[] =$reserved_to_branch_status;
		$nestedData[]=$authorized_status_dis;
	
	$data[] = $nestedData;
}

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

	echo json_encode($json_data); 
	}
	

	    public function item_add()
    {
		$data['main_menu_name'] = $this->main_menu_name;
		$data['sub_menu_name'] = 'service_add';
		
		
		$service_id=$this->uri->segment('3');
		$sale_id=$this->uri->segment('4');
		$data['sale_id'] =$sale_id;
		//echo "sale_id:".$sale_id;
		$data['serviceitm_list']=array();
		if(isset($service_id)){
			$data['service_details']=$this->Service_Model->get_service_details_by_id($service_id);
			$data['serviceitm_list']=$this->Service_Model->get_service_items_by_id($service_id);
		}
		
		$data['sale_item_list']=array();
		$data['sale_details']=array();
		if($sale_id){
			$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['service_id'] =$service_id;
		//get suppliers list
		$data['suppliers'] = array();//$this->Supplier_Model->get_all_supplier();
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['tax_rates_list'] = $this->Tax_Rates_Model->get_all_tax_rates();
		$data['customer_list'] = array();//$this->Customer_Model->get_all_customers();
		$data['product_list'] = array();//$this->Sales_Model->get_products_suggestions_for_service();
		//echo $this->db->last_query();
		$data['all_product_list'] =array();// $this->Product_Models->getProducts("","","");
		$data['sales_list'] =array();// $this->Sales_Model->get_all_sales();
		//echo $this->db->last_query();
		$data['status_list'] = $this->Common_Model->get_all_status();
		//$data['pr_list'] = $this->Requisition_Model->get_all_requisition_names();
			$w_data = $this->Sales_Model->get_warranty_types();
			
			$data['w_data'] = $w_data;
		
        $this->load->view('service_item_add',$data);
    }
		
	public function save_service_items()
	{
		$warehouse_id=$this->input->post('warehouse_id');
		$sale_id=$this->input->post('sale_id');
		$service_id=$this->input->post('service_id');
		
		$type='';
		if($sale_id){
			$type='E';
		}else{
			$type='A';
		}
		
		
		
		//start get next referance no
		$warehouse_dtls=$this->Warehouse_Model->get_warehouse_info($warehouse_id);
		$warehouse_code=$warehouse_dtls['code'];
		$warehouse_last_id=(1+$this->Sales_Model->get_next_warehouse_ref_no($warehouse_id));
		$sale_reference_no =$warehouse_code.'/S/'.sprintf("%04d",$warehouse_last_id);
		//end get next referance no
		
		
		
		$customer_id=$this->input->post('customer_id');
		$rowCount=$this->input->post('rowCount');
		
		$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_datetime'=>$sale_datetime,
				'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,

			);
			
			if($type=='A'){
				$data['sale_reference_no']=$sale_reference_no;
				$data['warehouse_last_id']=$warehouse_last_id;
				$data['warehouse_id']=$warehouse_id;
				$data['customer_id']=$customer_id;
				$data['service_id']=$service_id;
			}
			$_insert=$this->Sales_Model->save_sales($data,$sale_id);
			$lastid=$this->db->insert_id();
			if(!$sale_id){
			$sale_id=$lastid;
			}
			//insert user activity
			$this->Common_Model->add_user_activitie("Added Sale, (Invoice No:$sale_reference_no)");
			$disMsg='Sale successfully added';
			
			//delete old sale items by sale id
			if($sale_id){
				$this->Sales_Model->delete_sales_items_by_sale_id($sale_id);
			}
			
			//insert sale item data
			$row=$this->input->post('row');
			$rowCount=$this->input->post('rowCount');
			$data_item=array();
			$is_added_item='';
			for($i=1; $i<=$rowCount; $i++){
				$is_added_item=0;
				//echo "/ $rowCount , Test:".$row[$i]['product_id'][0];
				if(isset($row[$i]['product_id'][0]))
				{	
				
				
				//if(!empty($row[$i]['is_added_item'][0])){
				//	$is_added_item=$row[$i]['is_added_item'][0];	
				//}
				//echo "is_added_item:".$is_added_item;
				$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])
				);
				
				if(!$is_added_item){
				$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);
				
				//insert user activity
				$this->Common_Model->add_user_activitie("Added Sale Item, (Id:$itemid)");
				
					}
					}//end edit item
                    //end add serial numbers
				}
				
				
				
				
				//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;
		}	
		
		//update service charge
		//if($type=='hand_over'){
			$data_edit=array(
				'service_charge'=>$sale_total,
			);
		//}
		
			$this->Service_Model->save_service($data_edit,$service_id);
		
		$this->session->set_flashdata('message', 'Service items successfully added!');
		$error=0;
		echo json_encode(array('sale_id'=>$lastid,'error'=>$error,'disMsg'=>$disMsg,'service_id'=>$service_id));
	}
}