<?php
require_once ("secure_area.php");
class Sales extends Secure_area
{
	function __construct()
	{
		parent::__construct('sales','items');
		$this->load->library('sale_lib');
	}

	function index()
	{
		$this->_reload();
	}

	function item_search()
	{
		$suggestions = $this->Item->get_item_search_suggestions($this->input->post('q'),$this->input->post('limit'));
		$suggestions = array_merge($suggestions, $this->Item_kit->get_item_kit_search_suggestions($this->input->post('q'),$this->input->post('limit')));
		echo implode("\n",$suggestions);
	}

	function customer_search()
	{
		$suggestions = $this->Customer->get_customer_search_suggestions($this->input->post('q'),$this->input->post('limit'));
		echo implode("\n",$suggestions);
	}

	function select_customer()
	{
		$customer_id = $this->input->post("customer");
		$this->sale_lib->set_customer($customer_id);
		$this->_reload();
	}

	function change_mode()
	{
		$stock_location = $this->input->post("stock_location");
		if (!$stock_location || $stock_location == $this->sale_lib->get_sale_location()) 
		{
			$this->sale_lib->clear_all();
			$mode = $this->input->post("mode");
			$this->sale_lib->set_mode($mode);
		} 
		else
		{
			$this->sale_lib->set_sale_location($stock_location);
		}
		$this->_reload();
	}
	
	function set_comment() 
	{
 	  $this->sale_lib->set_comment($this->input->post('comment'));
	}
	
	function set_invoice_number()
	{
		$this->sale_lib->set_invoice_number($this->input->post('sales_invoice_number'));
	}
	
	function set_invoice_number_enabled()
	{
		$this->sale_lib->set_invoice_number_enabled($this->input->post('sales_invoice_number_enabled'));
	}
	
	function set_email_receipt()
	{
 	  $this->sale_lib->set_email_receipt($this->input->post('email_receipt'));
	}

	//Alain Multiple Payments
	function add_payment()
	{		
		$data = array();
		$this->form_validation->set_rules( 'amount_tendered', 'lang:sales_amount_tendered', 'numeric' );
		
		if ( $this->form_validation->run() == FALSE )
		{
			if ( $this->input->post( 'payment_type' ) == $this->lang->line( 'sales_gift_card' ) )
				$data['error']=$this->lang->line('sales_must_enter_numeric_giftcard');
			else
				$data['error']=$this->lang->line('sales_must_enter_numeric');
				
 			$this->_reload( $data );
 			return;
		}
		
		$payment_type = $this->input->post( 'payment_type' );
		if ( $payment_type == $this->lang->line( 'sales_giftcard' ) )
		{
			$payments = $this->sale_lib->get_payments();
			$payment_type = $this->input->post( 'payment_type' ) . ':' . $payment_amount = $this->input->post( 'amount_tendered' );
			$current_payments_with_giftcard = isset( $payments[$payment_type] ) ? $payments[$payment_type]['payment_amount'] : 0;
			$cur_giftcard_value = $this->Giftcard->get_giftcard_value( $this->input->post( 'amount_tendered' ) ) - $current_payments_with_giftcard;
			
			if ( $cur_giftcard_value <= 0 )
			{
				$data['error'] = 'Giftcard balance is ' . to_currency( $this->Giftcard->get_giftcard_value( $this->input->post( 'amount_tendered' ) ) ) . ' !';
				$this->_reload( $data );
				return;
			}

			$new_giftcard_value = $this->Giftcard->get_giftcard_value( $this->input->post( 'amount_tendered' ) ) - $this->sale_lib->get_amount_due( );
			$new_giftcard_value = ( $new_giftcard_value >= 0 ) ? $new_giftcard_value : 0;
			$data['warning'] = 'Giftcard ' . $this->input->post( 'amount_tendered' ) . ' balance is ' . to_currency( $new_giftcard_value ) . ' !';
			$payment_amount = min( $this->sale_lib->get_amount_due( ), $this->Giftcard->get_giftcard_value( $this->input->post( 'amount_tendered' ) ) );
		}
		if ($payment_type == 'Local Credit Card'|| $payment_type =='Overseas Debit/Credit Card'){
			$payments = $this->sale_lib->get_payments();	
			$payment_amount1 = $this->sale_lib->get_amount_due();
			
				$payment_amount= $payment_amount1 * 1.035;
				$this->input->post( 'amount_tendered' )= $payment_amount;
			}
		else
		{
			
			
			$payment_amount = $this->input->post( 'amount_tendered' );
		}
		
		if( !$this->sale_lib->add_payment( $payment_type, $payment_amount ) )
		{
			$data['error']='Unable to Add Payment! Please try again!';
		}
		
		$this->_reload($data);
	}

	//Alain Multiple Payments
	function delete_payment( $payment_id )
	{
		$this->sale_lib->delete_payment( $payment_id );
		$this->_reload();
	}

	function add()
	{
		$data=array();
		$mode = $this->sale_lib->get_mode();
		
		$scanitem = $this->input->post("item");
		
		$checkfirsttwodigit = mb_substr($scanitem, 0,3);
		
		if ($checkfirsttwodigit == 208 ) {
		
		
		
		$itemscanprice= mb_substr($scanitem, -6, 5);
		
		$tpprice = ($itemscanprice/ 100);
		
	  		
		$itemnumber = mb_substr($scanitem, 3,3);
		$item_id_or_number_or_item_kit_or_receipt = $itemnumber ;
		
		
		//$up = $unitprice->unit_price;
		
		
		$quantity = 1;
		
		
		$quantity = ($mode=="return")? -$quantity :$quantity ;
	
		$item_location = $this->sale_lib->get_sale_location();

		$item_location = $this->sale_lib->get_sale_location();

		if($mode == 'return' && $this->sale_lib->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->sale_lib->return_entire_sale($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif($this->Sale_suspended->invoice_number_exists($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->sale_lib->clear_all();
			$sale_id=$this->Sale_suspended->get_sale_by_invoice_number($item_id_or_number_or_item_kit_or_receipt)->row()->sale_id;
			$this->sale_lib->copy_entire_suspended_sale($sale_id);
			$this->Sale_suspended->delete($sale_id);
		}
		elseif($this->sale_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->sale_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt,$item_location);
		}
		elseif(!$this->sale_lib->add_item($item_id_or_number_or_item_kit_or_receipt,$quantity,$tpprice,$checkfirsttwodigit,$item_location))
		{
			$data['error']=$this->lang->line('sales_unable_to_add_item');
		}
		
		if($this->sale_lib->out_of_stock($item_id_or_number_or_item_kit_or_receipt,$item_location))
		{
			$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
		}
		//$this->_reload($data);
	}
						
		elseif ($checkfirsttwodigit !== 2080 ) {
			
	
		
		$data=array();
		$mode = $this->sale_lib->get_mode();
			$item_id_or_number_or_item_kit_or_receipt = $this->input->post("item");
		$quantity = ($mode=="return")? -1:1;
		$item_location = $this->sale_lib->get_sale_location();

		if($mode == 'return' && $this->sale_lib->is_valid_receipt($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->sale_lib->return_entire_sale($item_id_or_number_or_item_kit_or_receipt);
		}
		elseif($this->Sale_suspended->invoice_number_exists($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->sale_lib->clear_all();
			$sale_id=$this->Sale_suspended->get_sale_by_invoice_number($item_id_or_number_or_item_kit_or_receipt)->row()->sale_id;
			$this->sale_lib->copy_entire_suspended_sale($sale_id);
			$this->Sale_suspended->delete($sale_id);
		}
		elseif($this->sale_lib->is_valid_item_kit($item_id_or_number_or_item_kit_or_receipt))
		{
			$this->sale_lib->add_item_kit($item_id_or_number_or_item_kit_or_receipt,$item_location);
		}
		elseif(!$this->sale_lib->add_item($item_id_or_number_or_item_kit_or_receipt,$quantity,$tpprice=0,$checkfirsttwodigit=0,$item_location))
		{
			$data['error']=$this->lang->line('sales_unable_to_add_item');
		}
		
		if($this->sale_lib->out_of_stock($item_id_or_number_or_item_kit_or_receipt,$item_location))
		{
			$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
		}
		}
		
			$this->_reload($data);
		
			
			
	
	}
		

	function edit_item($line)
	{
		$data= array();

		$this->form_validation->set_rules('price', 'lang:items_price', 'required|numeric');
		$this->form_validation->set_rules('quantity', 'lang:items_quantity', 'required|numeric');

        $description = $this->input->post("description");
        $serialnumber = $this->input->post("serialnumber");
		$price = $this->input->post("price");
		$quantity = $this->input->post("quantity");
		$discount = $this->input->post("discount");
		$item_location = $this->input->post("location");


		if ($this->form_validation->run() != FALSE)
		{
			$this->sale_lib->edit_item($line,$description,$serialnumber,$quantity,$discount,$price);
		}
		else
		{
			$data['error']=$this->lang->line('sales_error_editing_item');
		}
		
		if($this->sale_lib->out_of_stock($this->sale_lib->get_item_id($line),$item_location))
		{
			$data['warning'] = $this->lang->line('sales_quantity_less_than_zero');
		}


		$this->_reload($data);
	}

	function delete_item($item_number)
	{
		$this->sale_lib->delete_item($item_number);
		$this->_reload();
	}

	function remove_customer()
	{
		$this->sale_lib->clear_invoice_number();
		$this->sale_lib->remove_customer();
		$this->_reload();
	}

	function complete()
	{
		
		date_default_timezone_set("Pacific/Fiji");
		$mode=$this->sale_lib->get_mode();
	 	$data['cart']=$this->sale_lib->get_cart();
		$data['subtotal']=$this->sale_lib->get_subtotal();
		$data['taxes']=$this->sale_lib->get_taxes();
		$data['total']=$this->sale_lib->get_total();
		$data['receipt_title']=$this->lang->line('sales_receipt');
		$data['transaction_time']= date('m/d/Y h:i:s a');
		$date =date(DATE_ISO8601, strtotime($data['transaction_time']));
		$stock_locations=$this->Stock_locations->get_undeleted_all()->result_array();
		$data['show_stock_locations']=count($stock_locations) > 1;
		$customer_id=$this->sale_lib->get_customer();
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$usernamepos = $this->Employee->get_logged_in_employee_info()->username;
		$comment=$this->sale_lib->get_comment();
		$emp_info=$this->Employee->get_info($employee_id);
		$data['payments']=$this->sale_lib->get_payments();
		$data['amount_change']=to_currency($this->sale_lib->get_amount_due() * -1);
		$data['employee']=$emp_info->first_name.' '.$emp_info->last_name;
		
	   // $payments =$data['payments'];
		
     $amountchange= $data['amount_change'];

				$valueInString = strval(round($amountchange,2));
if (strpos($valueInString, ".") == 0)
$valueInString = $valueInString.".00";
$valueArray = explode(".", $valueInString);
$substringValue = substr($valueArray[1], 1);

if ($substringValue >= 3 && $substringValue <= 7) {
$tempValue = str_replace(substr($valueArray[1], 1), 5, substr($valueArray[1], 1));
$tempValue = substr($valueArray[1],0,1).$tempValue;
$newvalue = floatval($valueArray[0].".".$tempValue);
} elseif ($substringValue == 1 ) {
$newvalue = $amountchange-0.01;
	} elseif ($substringValue == 2 ) {
	
	$newvalue = $amountchange-0.02;
	} elseif($substringValue == 0) {
$newvalue = floatval($amountchange);
} else {
$newFloat = floatval($valueArray[0].".".substr($valueArray[1],0,1));
$newvalue = ($newFloat+0.1);
}
		
		$roundedchange = $newvalue;
		$roundedchange1 = round($roundedchange,2);
		
	//	$cartitems = json_encode($data['cart'],JSON_UNESCAPED_SLASHES);
	
		//$data1=$data['cart'];
		
         // $items = array();
		//	foreach($data1 as $t)
		//	{
			//	$items[] =  $t['name'];
				//	$items[] =  $t['Labels'];
				
					//		}

		//$cartitems1 = json_encode($items,true);
		
	//	$output = array_slice($data1,12);
		
	//	$cartitems5 = json_encode($output,JSON_UNESCAPED_SLASHES);
	
	//	$testdata = array()			;
	//	$connect = new mysqli("localhost", "erpgloba_vms", "4Compassion*", "erpgloba_erp-vms"); 
			$connect = new mysqli("localhost", "sooggoo", "4Compassion*", "pacifichome_erp");
		
		//check for vms
	$SQLvms = "SELECT coyname,gstno,vms
	               
			FROM companies
			";
	
			$result = mysqli_query($connect,$SQLvms);
	
			$myrowvms = mysqli_fetch_array($result) ;
$vmsstatus =  $myrowvms['vms'];
$companyname = $myrowvms['coyname'];
$companytin = $myrowvms['gstno'];
		
		
		$SQLvms1 = "SELECT confvalue
	               
			FROM config 
			Where confname = 'InventoryCashSales'
			";
	
			$result1 = mysqli_query($connect,$SQLvms1);
	
			$myrowvms1 = mysqli_fetch_array($result1) ;
$stocklogic =  $myrowvms1['confvalue'];
		
		
		if ($vmsstatus == '0'){
	
		$totaltax = 0;
	$ninevat = 0;
	$fifteenvat =0;
		foreach($data['cart'] as $result) {
			
			$sqltt = "SELECT sales_tax from item_tax 
			        Where stockid = '". $result['item_id']."'";
			
 $resulttt = mysqli_query($connect,$sqltt);
 while ($myrowtt = mysqli_fetch_array($resulttt)){
 
 $sqlttlabel = "SELECT abbr,tax_label,rate from new_sales_tax 
			        WHERE id = '".  $myrowtt['sales_tax']."'";
 
  $resulttt3 = mysqli_query($connect,$sqlttlabel);
 $myrowtaxlabl = mysqli_fetch_array($resulttt3);
 
		$taxlabel=	$myrowtaxlabl['tax_label'] ;
		$abbr=	$myrowtaxlabl['abbr'] ;
		$taxrate=	$myrowtaxlabl['rate'] ;
	$labels[] = $myrowtaxlabl['tax_label'] ;
	 
	 if ($result['discount'] ==""){
		 
		 $linetotalVIP = $result['quantity']* $result['price'];
	 }else{
		  $linetotalVIP = ($result['quantity']* $result['price']) - ($result['quantity']* $result['price'] *$result['discount']/100);
		 
	 }
	 
		
		 $linetotalVEP = $linetotalVIP / (1 + $taxrate) ;
	 if ($taxlabel =='P'){
				
				$plastic = $result['quantity'] * $taxrate ;
				
			
				//$totaltax = $totaltax + $vat;	
			}
		
				if ($taxlabel =='A'){
				
				$vat = round(($linetotalVEP * $taxrate),2);
				
		
			}
		
		
			if ($taxlabel =='D'){
				
				$vat1 = round(($linetotalVEP * $taxrate),2);
				
			
				
			}
	 
	 if ($taxlabel =='E'){
				
				$stt = round(($linetotalVEP * $taxrate),2);
				
			
					
			}
	 
	 if ($taxlabel =='F'){
				
				$ecal = round(($linetotalVEP * $taxrate),2);
				
			
				
			}
	 
 }
	$totaltax = $vat +$vat1 + $ecal + $stt;
			
		$labeljson = json_encode($labels);
	 
	 
		  $labelimplode = implode(', ', $labels);
		//	if ($result['item_id'] == '12'){
				
		//			$labels= array("P");
		//	}
		//	else{
		//	$labels= array("A");	
				
		//	}
			
			
			
	
		//$labeljson = json_encode('A');
	
    
			$itemsdata[] = array(
			'Name'=>$result['name'],
			'Labels'=> $labels,
			'UnitPrice'=>$result['price'],
			'Quantity'=>$result['quantity'],
			'TotalAmount'=> $result['quantity']*$result['price']
			);
			
			$itemsdataother[] = array(
			'Stockid'=>$result['item_id'],
			'Name'=>$result['name'],
			'Labels'=> $labels,
			'UnitPrice'=>$result['price'],
			'Quantity'=>$result['quantity'],
			'TotalAmount'=> $result['quantity']*$result['price']
			);
		
			
			
	}//data cart ends
	 $itemssdc = json_encode($itemsdata,true);
			
		$itemssdcother =json_encode($itemsdataother,true);

	//$payment_types="";
		foreach($data['payments'] as $payment)
		{
			$payment_types=$payment['payment_type'];
			
			if ($payment['payment_type'] =='Local Credit Card'|| $payment['payment_type'] =='Overseas Debit/Credit Card'){
				
				$payment_amount= $payment['payment_amount'] * 1.035;
				
			}else{
			
			$payment_amount=$payment['payment_amount'];
				
			}
		}
		$paymenttypes = $payment_types;
		$paymentamount = $payment_amount;
		
			if ($paymenttypes =='Local Credit Card'|| $paymenttypes =='Overseas Debit/Credit Card'){
				
			$data['total'] = $data['total'] * 1.035;	
				
				$cardfees = $data['total'] * 0.035;
				//$data['cardfees'] = $cardfees ;
			}
			
			$grossamount=$data['total'];
		
		$valueInString = strval(round($grossamount,2));
if (strpos($valueInString, ".") == 0)
$valueInString = $valueInString.".00";
$valueArray = explode(".", $valueInString);
$substringValue = substr($valueArray[1], 1);

if ($substringValue >= 3 && $substringValue <= 7) {
$tempValue = str_replace(substr($valueArray[1], 1), 5, substr($valueArray[1], 1));
$tempValue = substr($valueArray[1],0,1).$tempValue;
$newvalue = floatval($valueArray[0].".".$tempValue);
} elseif ($substringValue == 1 ) {
$newvalue = $grossamount-0.01;
	} elseif ($substringValue == 2 ) {
	
	$newvalue = $grossamount-0.02;
	} elseif($substringValue == 0) {
$newvalue = floatval($grossamount);
} else {
$newFloat = floatval($valueArray[0].".".substr($valueArray[1],0,1));
$newvalue = ($newFloat+0.1);
}
		
		$roundedamount = $newvalue;
		$roundedamount =round($roundedamount,2);
		$rounding = round(($grossamount - $roundedamount),2);
		
		

		if ($paymenttypes !='Cash'){
			$roundedamount = $grossamount;
			$rounding = '0.00';
			
		}
		if ($rounding < 0 ){
			
			$rounding = -($rounding);
		}
		 
			$rounded_amount = $roundedamount;
			$roundings = $rounding;
		$totalamount = $grossamount;
		$query = "SELECT trainee,tin,email,realname,location
				   
			FROM www_users
			WHERE userid='" . $usernamepos. "'
			";
 $result = mysqli_query($connect,$query);  
		
		$row = mysqli_fetch_array($result);
		
		$emailm= $row['email'];
$realname= $row['realname'];
$userid= $row['userid'];
			

$location = $row['location'];	
		
	if ($row['trainee'] == 1){
			
			$invoicetype = "Training";
		}
		if ($row['trainee'] == 0){
			
			$invoicetype = "Normal";
		}
		
		
		
		$cashiertin=$row['tin'];
		
		if ($row['tin'] == ''){
			
			$cashiertin = $usernamepos;
		}
		
        $cust_info='';
		if($customer_id!=-1)
		{
			$cust_info=$this->Customer->get_info($customer_id);
			$data['customer']=$cust_info->first_name.' '.$cust_info->last_name;
		}
		$invoice_number=$this->_substitute_invoice_number($cust_info);
		if ($this->sale_lib->is_invoice_number_enabled() && $this->Sale->invoice_number_exists($invoice_number))
		{
			$data['error']=$this->lang->line('sales_invoice_number_duplicate');
			$this->_reload($data);
		}
		else 
		{
			
			$invoice_number = $this->sale_lib->is_invoice_number_enabled() ? $invoice_number : NULL;
			$data['invoice_number']=$invoice_number;
			$data['sale_id']='POS '.$this->Sale->save($data['cart'], $customer_id,$employee_id,$comment,$invoice_number,$data['payments'],$roundings,$rounded_amount,$vat,$plastic,$srt,$ecal,$totalamount,$cardfees);
			$receiptno = $data['sale_id'];
			if ($data['sale_id'] == 'POS -1')
			{
				$data['error_message'] = $this->lang->line('sales_transaction_failed');
			}
			
		
	
	
		
	$this->load->view("sales/receipt",$data);
		
			$this->sale_lib->clear_all();
		}

		$this->_remove_duplicate_cookies();
		
		
		}
		else{
			
			foreach($data['cart'] as $result) {
			
			
	$SQLtax = "SELECT sales_tax
				   
			FROM item_tax
			WHERE stockid='" . $result['item_id']. "'
			";
	
	$result1 = mysqli_query($connect,$SQLtax);
	$label =array();
	while( $rowtax = mysqli_fetch_array($result1) ){
		
				$SQLlabel = "SELECT tax_label
				   
			FROM new_sales_tax
			WHERE id='" . $rowtax['sales_tax']. "'
			";
	
		
	$resultlabel = mysqli_query($connect,$SQLlabel);
		$rowlabel = mysqli_fetch_array($resultlabel);
		
		
		$label[] = $rowlabel['tax_label'];
		
		
	};
		$labeljson = json_encode($label);
			
			
			
	
		//$labeljson = json_encode('A');
		  	
    
			$itemsdata[] = array(
			'Name'=>$result['name'],
			'Labels'=> json_decode($labeljson),
			'UnitPrice'=>($result['price'])-($result['price']*$result['discount']/100),
			'Quantity'=>$result['quantity'],
			'TotalAmount'=> ($result['quantity']*$result['price'])-($result['quantity']*$result['price']*$result['discount']/100)
			);
			
			$itemsdataother[] = array(
			'Stockid'=>$result['item_id'],
			'Name'=>$result['name'],
			'Labels'=> json_decode($labeljson),
			'UnitPrice'=>($result['price'])-($result['price']*$result['discount']/100),
			'Quantity'=>$result['quantity'],
			'TotalAmount'=> ($result['quantity']*$result['price'])-($result['quantity']*$result['price']*$result['discount']/100),
			'Serial'=>$result['serialnumber'],
			'Discount'=>$result['discount']	
			);
		
	}
	 $itemssdc = json_encode($itemsdata,true);
			
		$itemssdcother =json_encode($itemsdataother,true);

	//$payment_types="";
		foreach($data['payments'] as $payment)
		{
			$payment_types=$payment['payment_type'];
			$payment_amount=$payment['payment_amount'];
		}
		$paymenttypes = $payment_types;
		$paymentamount = $payment_amount;
		$grossamount=$data['total'];
		
		$valueInString = strval(round($grossamount,2));
if (strpos($valueInString, ".") == 0)
$valueInString = $valueInString.".00";
$valueArray = explode(".", $valueInString);
$substringValue = substr($valueArray[1], 1);

if ($substringValue >= 3 && $substringValue <= 7) {
$tempValue = str_replace(substr($valueArray[1], 1), 5, substr($valueArray[1], 1));
$tempValue = substr($valueArray[1],0,1).$tempValue;
$newvalue = floatval($valueArray[0].".".$tempValue);
} elseif ($substringValue == 1 ) {
$newvalue = $grossamount-0.01;
	} elseif ($substringValue == 2 ) {
	
	$newvalue = $grossamount-0.02;
	} elseif($substringValue == 0) {
$newvalue = floatval($grossamount);
} else {
$newFloat = floatval($valueArray[0].".".substr($valueArray[1],0,1));
$newvalue = ($newFloat+0.1);
}
		
		$roundedamount = $newvalue;
		$roundedamount =round($roundedamount,2);
		$rounding = round(($grossamount - $roundedamount),2);
		
		

		if ($paymenttypes !='Cash'){
			$roundedamount = $grossamount;
			$rounding = '0.00';
			
		}
		if ($rounding < 0 ){
			
			$rounding = -($rounding);
		}
		 
		
		$query = "SELECT trainee,tin,pac
				   
			FROM www_users
			WHERE userid='" . $usernamepos. "'
			";
 $result = mysqli_query($connect,$query);  
		
		$row = mysqli_fetch_array($result);
	if ($row['trainee'] == 1){
			
			$invoicetype = "Training";
		}
		if ($row['trainee'] == 0){
			
			$invoicetype = "Normal";
		}
		
		$pac =$row['pac'];
		
		$cashiertin=$row['tin'];
		
		if ($row['tin'] == ''){
			
			$cashiertin = $usernamepos;
		}
		
        $cust_info='';
		if($customer_id!=-1)
		{
			$cust_info=$this->Customer->get_info($customer_id);
			$data['customer']=$cust_info->first_name.' '.$cust_info->last_name;
		}
		$invoice_number=$this->_substitute_invoice_number($cust_info);
		if ($this->sale_lib->is_invoice_number_enabled() && $this->Sale->invoice_number_exists($invoice_number))
		{
			$data['error']=$this->lang->line('sales_invoice_number_duplicate');
			$this->_reload($data);
		}
		else 
		{
			
			$invoice_number = $this->sale_lib->is_invoice_number_enabled() ? $invoice_number : NULL;
			$data['invoice_number']=$invoice_number;
			$data['sale_id']='POS '.$this->Sale->save($data['cart'], $customer_id,$employee_id,$comment,$invoice_number,$data['payments']);
			$receiptno = $data['sale_id'];
			if ($data['sale_id'] == 'POS -1')
			{
				$data['error_message'] = $this->lang->line('sales_transaction_failed');
			}
			
date_default_timezone_set("Pacific/Fiji");
			
			$quotedate1= date('d/m/Y h:i:s a');
			$quotedate= date('m/d/Y h:i:s a');
			error_reporting(E_ERROR | E_PARSE);
			echo '<div class="container">
            <div class="row">
                <div class="col-lg-9 col-xs-12 col-centered">
				
             ';
	$counter = 'Counter 1';
	
	//echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
		mysqli_close($connect);	
echo "


<div id='printarea' style='text-align: center'>
<div id='printdata'  style='font-size:18px'>
<img src='../smalllogo1.jpg' width='300px' height='100px'>
<div style='font-weight:bold'>Counter 1</div>
<div >Ph:9223300 Mob:9223300</div>
<div >Email:sales@ebusinesserp.com</div>
<pre class='output'></pre>
<div id='tendered'>Rounding:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp$$rounding</div>
<div id='tendered'>Actual Amount:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp$$roundedamount</div>
<div id='tendered'>Tendered Amount:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp$$roundedamount</div>
<div id='changetogive'>Change:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$amountchange</div>
<div style='text-align: center'><image id='qrcode' style='width:250px;height:250px;'/></div>

<br>
<div >--------END OF FISCAL INVOICE-----------</div>


<div id='copyright'style='font-size:14px'>---------Powered by E-Business ERP 2.0-----------</div>
</div>";
			echo '<form method="post" id= "completeform" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
			echo "
  <textarea name= 'results' id='results' cols='100' rows='30' style='display:block'></textarea><br>
 
  <textarea class= 'journal' id='receipt' cols='50' rows='45' style='display:block,font-size:19px' readonly></textarea><br>
   
      <textarea name= 'invoiceRequest' id='invoiceRequest' cols='100' rows='30' style='display:block' ></textarea><br>
	   <textarea name= 'otherRequest' id='otherRequest' cols='100' rows='30' style='display:block'></textarea><br>
	  
<input type='submit' name='complete1' id='complete1' class='btn btn-info' value='Complete'/>


</form>	
     
               
                 <div id ='signing' style='text-align: center'> Signing invoice. Please hold.... </div>
               
        
                
                       <div id ='error' style='text-align: center'> Fiscalization process Failed! Please check the error message that has show earlier and contact your admin manager </div>
         
                
                

<a href='index.php'>  <button type='button' id ='newbtt' name='newinvoice' class='btn btn-success'>Create New SALE/REFUND</button></a><input type='button' id='btn' value='RePrint' onclick='printData();'></div></div></div></div>";
			

 
echo "
<div class='row'>

  <div tyle='text-align: center'>
 <button id='taxcore_sign_element'
 data-taxcore-vsdc-url='https://vsdc.staging.vms.frcs.org.fj/'
 data-taxcore-input-id='invoiceRequest'
 data-taxcore-output-id='results'
 data-taxcore-invoice-request=''
 data-taxcore-debug='true'
 data-taxcore-signed-invoice-response=''>Sign Invoice to FRCS Tax System</button></div>";
 

			
 
 
	
 
 
	echo"<script src='https://vsdc.staging.vms.frcs.org.fj/onlinepos/v1/taxcore.min.js'></script>
	
	 <script src='https://code.jquery.com/jquery-1.12.4.js'></script>
  <script src='https://code.jquery.com/ui/1.12.1/jquery-ui.js'></script>
 <script>

 document.getElementById('invoiceRequest').innerHTML = JSON.stringify(CreateExampleInvoiceRequest(), undefined, 4);
 
document.getElementById('otherRequest').innerHTML =JSON.stringify(Other(),undefined, 4);



 
 
document.getElementById('taxcore_sign_element').dataset.taxcoreInvoiceRequest = JSON.stringify(CreateExampleInvoiceRequest());



	
 function CreateExampleInvoiceRequest() {

 
 var invoiceRequest = {
 'DateAndTimeOfIssue': '$quotedate',
 'Cashier': '$cashiertin',
 'BD': null,
 'BuyerCostCenterId': null,
 'IT': '$invoicetype',
 'TT': '$mode',
 'PaymentType': '$paymenttypes',
 'InvoiceNumber': '$receiptno',
 'ReferentDocumentNumber': '',
 'PAC': '$pac',
 'Options': {
 'OmitTextualRepresentation': 0,
 'OmitQRCodeGen': 0
	 },
 'Items': $itemssdc
 
 };
 return invoiceRequest;
 }
 
 
function Other() {
 
 var otherRequest = {
 
 'Notes': '$comment',
 'Date': '$quotedate1',
 'Items': $itemssdcother,
 'User':'$usernamepos',
 'RoundedAmount':'$roundedamount',
 'Rounding':'$rounding',
 'Terminal':'$counter'
 };
 return otherRequest;
 }

 
 

$(document).ready(function(){

$('#complete1').hide();

$('#printdata').hide();
	$('#receipt').hide();
		$('#invoiceRequest').hide();
	$('#otherRequest').hide();
	$('#results').hide();
  $('#taxcore_sign_element').hide();
   $('#invoicebtt').hide();
  $('#newbtt').hide();
 $('#btn').hide();
		$('#error').hide();
		
	$('#receipt_wrapper').hide();	
		
setTimeout(function() {


if ($('#invoiceRequest').length > 0){
 

    $('#taxcore_sign_element').trigger('click');
 
 }
 else{
 alert('Session Expired. Please Retry. Taking you back again');
 }
  
	
	 
}, 2e3);

  

$('#taxcore_sign_element' ).click(function() {



$(function() {
    var intervalID = setInterval(function() {
	
	         
			 	$('#signing').hide();
      var attrmethod = $('#taxcore_sign_element').attr('data-taxcore-signed-invoice-response');
	  var results = $('#results').val();
	  var invoiceRequest = $('#invoiceRequest').val();
	  var otherRequest = $('#otherRequest').val();
	  	var objprint = JSON.parse(results);
 				var obj = JSON.parse(attrmethod);
				
			if (obj.status_code == 200){
			
			 clearInterval(intervalID);
					$('#taxcore_sign_element').hide();
				$('#invoicebtt').show();
			   $('#newbtt').show();
				
		
				
				var journal1 = objprint.Journal;
				
				
			
			
				
						$('#qrcode').attr('src', 'data:image/gif;base64,' + objprint.VerificationQRCode);
						
			
						
						setTimeout(function() {



				$('.output').text(journal1);
				   
				  					
				
		
 			       	$('#btn').trigger('click');
 
 
  
					$('#btn').show();
				 
					$('#printdata').show();
					
		             					   var invoiceRequest=$('#invoiceRequest').val();
                 var otherRequest=$('#otherRequest').val();
				  var results=$('#results').val();
					
				     $.ajax({
            url: 'postrans',
           
            type: 'POST',
		
			data:{results:results,
                        otherRequest:otherRequest,
						invoiceRequest:invoiceRequest
                    },
            success: function(){
       
           
            },
			
         error: function(jqxhr, status, exception) {
             alert('Exception:', exception);
         }
        });
           
     
	
	 
}, 1e3);
	}
			
			if (obj.status_code != 200){
			
		$('#error').show();
			alert(attrmethod);
			
			 $('#newbtt').trigger('click');
			
			}
    }, 2000);
	
    setTimeout(function() {
        clearInterval(intervalID);
		
    }, 4000);
	
	
});

 });
  
});

function printData()
{
   var divToPrint=document.getElementById('printdata');
   newWin= window.open('');
   newWin.document.write(divToPrint.innerHTML);
   newWin.print();
   newWin.close();
}


	
	
	
		$(window).keydown(function(e) {
  switch (e.keyCode) {
   
	  case 117:
		  $('#newbtt').trigger('click');
		  
	
 
  }
});

	
</script>
";
			 

		
	
		
			$this->sale_lib->clear_all();
		}

		$this->_remove_duplicate_cookies();
		
		
			
		}
		
		
		
		}
	
	
	
	function _substitute_invoice_number($customer_info='')
	{
		$invoice_number=$this->sale_lib->get_invoice_number();
		if (empty($invoice_number))
		{
			$invoice_number=$this->config->config['sales_invoice_format'];
		}
		$invoice_count=$this->Sale->get_invoice_count();
		$invoice_number=str_replace('$CO',$invoice_count,$invoice_number);
		$invoice_count=$this->Sale_suspended->get_invoice_count();
		$invoice_number=str_replace('$SCO',$invoice_count,$invoice_number);
		$invoice_number=strftime($invoice_number);
	
		$customer_id=$this->sale_lib->get_customer();
		if($customer_id!=-1)
		{
			$invoice_number=str_replace('$CU',$customer_info->first_name . ' ' . $customer_info->last_name,$invoice_number);
			$words = preg_split("/\s+/", $customer_info->first_name . ' ' . $customer_info->last_name);
			$acronym = "";
			foreach ($words as $w) {
				$acronym .= $w[0];
			}
			$invoice_number=str_replace('$CI',$acronym,$invoice_number);
		}
		$this->sale_lib->set_invoice_number($invoice_number);
		return $invoice_number;
	}
	
	function receipt($sale_id)
	{
		$sale_info = $this->Sale->get_info($sale_id)->row_array();
		$this->sale_lib->copy_entire_sale($sale_id);
		$stock_locations = $this->Stock_locations->get_undeleted_all()->result_array();
		$data['show_stock_locations'] = count($stock_locations) > 1;
		$data['cart']=$this->sale_lib->get_cart();
		$data['payments']=$this->sale_lib->get_payments();
		$data['subtotal']=$this->sale_lib->get_subtotal();
		$data['taxes']=$this->sale_lib->get_taxes();
		$data['total']=$this->sale_lib->get_total();
		$data['receipt_title']=$this->lang->line('sales_receipt');
		$data['transaction_time']= date('m/d/Y h:i:s a', strtotime($sale_info['sale_time']));
		$customer_id=$this->sale_lib->get_customer();
		$emp_info=$this->Employee->get_info($sale_info['employee_id']);
		$data['payment_type']=$sale_info['payment_type'];
		$data['invoice_number']=$sale_info['invoice_number'];
		$data['amount_change']=to_currency($this->sale_lib->get_amount_due() * -1);
		$data['employee']=$emp_info->first_name.' '.$emp_info->last_name;

		if($customer_id!=-1)
		{
			$cust_info=$this->Customer->get_info($customer_id);
			$data['customer']=$cust_info->first_name.' '.$cust_info->last_name;
		}
		$data['sale_id']='POS '.$sale_id;
		$this->load->view("sales/receipt",$data);
		$this->sale_lib->clear_all();
		$this->_remove_duplicate_cookies();
	}
	
	function edit($sale_id)
	{
		$data = array();

		$data['customers'] = array('' => 'No Customer');
		foreach ($this->Customer->get_all()->result() as $customer)
		{
			$data['customers'][$customer->person_id] = $customer->first_name . ' '. $customer->last_name;
		}

		$data['employees'] = array();
		foreach ($this->Employee->get_all()->result() as $employee)
		{
			$data['employees'][$employee->person_id] = $employee->first_name . ' '. $employee->last_name;
		}

		$sale_info = $this->Sale->get_info($sale_id)->row_array();
		$person_name = $sale_info['first_name'] . " " . $sale_info['last_name'];
		$data['selected_customer'] = !empty($sale_info['customer_id']) ? $sale_info['customer_id'] . "|" . $person_name : "";
		$data['sale_info'] = $sale_info;
		
		$this->load->view('sales/form', $data);
	}
	
	function delete($sale_id = -1, $update_inventory=TRUE) {
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$sale_ids= $sale_id == -1 ? $this->input->post('ids') : array($sale_id);

		if($this->Sale->delete_list($sale_ids, $employee_id, $update_inventory))
		{
			echo json_encode(array('success'=>true,'message'=>$this->lang->line('sales_successfully_deleted').' '.
			count($sale_ids).' '.$this->lang->line('sales_one_or_multiple'),'ids'=>$sale_ids));
		}
		else
		{
			echo json_encode(array('success'=>false,'message'=>$this->lang->line('sales_unsuccessfully_deleted')));
		}
	}
	
	function save($sale_id)
	{
		$sale_data = array(
			'sale_time' => date('Y-m-d', strtotime($this->input->post('date'))),
			'customer_id' => $this->input->post('customer_id') ? $this->input->post('customer_id') : NULL,
			'employee_id' => $this->input->post('employee_id'),
			'comment' => $this->input->post('comment'),
			'invoice_number' => $this->input->post('invoice_number') ? $this->input->post('invoice_number') : NULL
		);
		
		if ($this->Sale->update($sale_data, $sale_id))
		{
			echo json_encode(array(
				'success'=>true,
				'message'=>$this->lang->line('sales_successfully_updated'),
				'id'=>$sale_id)
			);
		}
		else
		{
			echo json_encode(array(
				'success'=>false,
				'message'=>$this->lang->line('sales_unsuccessfully_updated'),
				'id'=>$sale_id)
			);
		}
	}
	
	function _payments_cover_total()
	{
		$total_payments = 0;

		foreach($this->sale_lib->get_payments() as $payment)
		{
			$total_payments += $payment['payment_amount'];
		}

		/* Changed the conditional to account for floating point rounding */
		if ( ($this->sale_lib->get_mode() == 'sale') && 
		      ( ( to_currency_no_money( $this->sale_lib->get_total() ) - $total_payments ) > 1e-6 ) )
		{
			return false;
		}
		
		return true;
	}
	
	function _reload($data=array())
	{
		$person_info = $this->Employee->get_logged_in_employee_info();
		$data['cart']=$this->sale_lib->get_cart();	 
        $data['modes']=array('sale'=>$this->lang->line('sales_sale'),'return'=>$this->lang->line('sales_return'));
        $data['mode']=$this->sale_lib->get_mode();
                     
        $data['stock_locations']=$this->Stock_locations->get_allowed_locations();
        $data['stock_location']=$this->sale_lib->get_sale_location();
        
		$data['subtotal']=$this->sale_lib->get_subtotal();
		$data['taxes']=$this->sale_lib->get_taxes();
		$data['total']=$this->sale_lib->get_total();
		$data['items_module_allowed']=$this->Employee->has_grant('items', $person_info->person_id);
		$data['comment']=$this->sale_lib->get_comment();
		$data['email_receipt']=$this->sale_lib->get_email_receipt();
		$data['payments_total']=$this->sale_lib->get_payments_total();
		$data['amount_due']=$this->sale_lib->get_amount_due();
		$data['payments']=$this->sale_lib->get_payments();
		$data['payment_options']=array(
			$this->lang->line('sales_cash') => $this->lang->line('sales_cash'),
			$this->lang->line('sales_check') => $this->lang->line('sales_check'),
			$this->lang->line('sales_giftcard') => $this->lang->line('sales_giftcard'),
			$this->lang->line('sales_debit') => $this->lang->line('sales_debit'),
			$this->lang->line('sales_credit') => $this->lang->line('sales_credit'),
				$this->lang->line('sales_creditcard') => $this->lang->line('sales_creditcard'),
					$this->lang->line('sales_debitcard') => $this->lang->line('sales_debitcard'),
						$this->lang->line('sales_mpaisa') => $this->lang->line('sales_mpaisa'),
							$this->lang->line('sales_mycash') => $this->lang->line('sales_mycash'),
			$this->lang->line('sales_overseas') => $this->lang->line('sales_overseas')
		);

		$customer_id=$this->sale_lib->get_customer();
		$cust_info='';
		if($customer_id!=-1)
		{
			$cust_info=$this->Customer->get_info($customer_id);
			$data['customer']=$cust_info->first_name.' '.$cust_info->last_name;
			$data['customer_email']=$cust_info->email;
		}
		$data['invoice_number']=$this->_substitute_invoice_number($cust_info);
		$data['invoice_number_enabled']=$this->sale_lib->is_invoice_number_enabled();
		$data['payments_cover_total']=$this->_payments_cover_total();
		$this->load->view("sales/register",$data);
		$this->_remove_duplicate_cookies();
	}

    function cancel_sale()
    {
    	$this->sale_lib->clear_all();
    	$this->_reload();
    }
	
	function suspend()
	{
		$data['cart']=$this->sale_lib->get_cart();
		$data['subtotal']=$this->sale_lib->get_subtotal();
		$data['taxes']=$this->sale_lib->get_taxes();
		$data['total']=$this->sale_lib->get_total();
		$data['receipt_title']=$this->lang->line('sales_receipt');
		$data['transaction_time']= date('m/d/Y h:i:s a');
		$customer_id=$this->sale_lib->get_customer();
		$employee_id=$this->Employee->get_logged_in_employee_info()->person_id;
		$comment = $this->input->post('comment');
		$invoice_number=$this->sale_lib->get_invoice_number();
		
		$emp_info=$this->Employee->get_info($employee_id);
		$payment_type = $this->input->post('payment_type');
		$data['payment_type']=$this->input->post('payment_type');
		//Alain Multiple payments
		$data['payments']=$this->sale_lib->get_payments();
		$data['amount_change']=to_currency($this->sale_lib->get_amount_due() * -1);
		$data['employee']=$emp_info->first_name.' '.$emp_info->last_name;
		
		if ($this->Sale_suspended->invoice_number_exists($invoice_number))
		{
			$this->_reload(array('error' => $data['error']=$this->lang->line('sales_invoice_number_duplicate')));
		}
		else
		{
			if($customer_id!=-1)
			{
				$cust_info=$this->Customer->get_info($customer_id);
				$data['customer']=$cust_info->first_name.' '.$cust_info->last_name;
			}
	
			$total_payments = 0;
	
			foreach($data['payments'] as $payment)
			{
				$total_payments += $payment['payment_amount'];
			}
	
			//SAVE sale to database
			$data['sale_id']='POS '.$this->Sale_suspended->save($data['cart'], $customer_id,$employee_id,$comment,$invoice_number,$data['payments']);
			if ($data['sale_id'] == 'POS -1')
			{
				$data['error_message'] = $this->lang->line('sales_transaction_failed');
			}
			$this->sale_lib->clear_all();
			$this->_reload(array('success' => $this->lang->line('sales_successfully_suspended_sale')));
		}
	}
	
	function suspended()
	{
		$data = array();
		$data['suspended_sales'] = $this->Sale_suspended->get_all()->result_array();
		$this->load->view('sales/suspended', $data);
	}
	
	function unsuspend()
	{
		$sale_id = $this->input->post('suspended_sale_id');
		$this->sale_lib->clear_all();
		$this->sale_lib->copy_entire_suspended_sale($sale_id);
		$this->Sale_suspended->delete($sale_id);
    	$this->_reload();
	}
	
	function check_invoice_number()
	{
		$sale_id=$this->input->post('sale_id');
		$invoice_number=$this->input->post('invoice_number');
		$exists=!empty($invoice_number) && $this->Sale->invoice_number_exists($invoice_number,$sale_id);
		echo json_encode(array('success'=>!$exists,'message'=>$this->lang->line('sales_invoice_number_duplicate')));
	}
		function postrans()
		{
			

	$trimmed = str_replace("\\n", "", $_POST['results']);
	
	$finaldata = str_replace("\\r", "", $trimmed);
	$finaldata1 = str_replace("\\", "", $finaldata);
	$response = json_decode($finaldata1);
	 
		$trimmed1 = str_replace("\\n", "", $_POST['invoiceRequest']);
	
	$finaldata1 = str_replace("\\r", "", $trimmed1);
	$finaldata2 = str_replace("\\", "", $finaldata1);
	$request = json_decode($finaldata2);
	
	$trimmedother = str_replace("\\n", "", $_POST['otherRequest']);
	
	$finaldataother = str_replace("\\r", "", $trimmedother);
	$finaldata2other = str_replace("\\", "", $finaldataother);
	$otherrequest = json_decode($finaldata2other);
	
	
			
	   $servername = "localhost";
$username = "sooggoo";
$password = "4Compassion*";
$dbname = "pacifichome_erp";

// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
    die("Connection failed: " . $connect->connect_error);
} 

		
			
		$tin = $request->Cashier;
		
		
$SQLuser = "SELECT userid,tin,email,realname,pac,location
	               
			FROM www_users
			WHERE tin='" . $tin. "' OR userid = '" . $tin. "'
			";
	
			 $resultuser = mysqli_query($connect,$SQLuser); 
	
			$myrowuser = mysqli_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];
$realname= $myrowuser['realname'];
$userid= $myrowuser['userid'];
			$tin1= $myrowuser['tin'];
$pac = $myrowuser['pac'];	
$location = $myrowuser['location'];	

				$sqldate = date("Y-m-d H:i:s");
	
$yeardate = date('Y',strtotime($sqldate));
$monthdate =date('m',strtotime($sqldate));
$monthname =date('M',strtotime($sqldate)); 

			
	    $query22 = "SELECT 
						periodno,
		             lastdate_in_period
		                 
					  
		          FROM periods
				    WHERE YEAR(lastdate_in_period) = '" . $yeardate. "'
					AND MONTH(lastdate_in_period)  = '" . $monthdate. "'";
				
        $result22=mysqli_query($connect,$query22); 
        $myrow22=mysqli_fetch_array($result22);
      
				$PeriodNo = $myrow22['periodno'];
			
				if ($request->PaymentType !='Cash'){
				
				$otherrequest->RoundedAmount = $response->TotalAmount;
				
			}
$SQLdebtor = "INSERT INTO possales (transno,
									
									sdc_invoice_no,
									invoice_type,
									type,
									trandate,
								
									loccode,
									terminal,
									department,
								    paymenttype,
									totalamount,
									rounding,
									rounded_amount,
								    invtext,
									
								    entered_by)
				VALUES (
					'" . $request->InvoiceNumber. "',
					
					'" . $response->IN. "',
					'" . $request->IT. "',
				    '69',
					'" . $sqldate . "',
					
					'SHOP1',
					'Counter 1',
						'26',
					'" . $request->PaymentType. "',
					'" . $response->TotalAmount . "',
					'" . $otherrequest->Rounding . "',
					'" . $otherrequest->RoundedAmount . "',
					'" . $otherrequest->Notes . "',
					
					'" . $userid . "'
				
					)";
		
	$result = mysqli_query($connect,$SQLdebtor);
		 	
      
//	if (mysqli_query($connect, $SQLdebtor)) {
 //   echo "New record created successfully";
//} else {
//    echo "Error: " . $SQLdebtor . "<br>" . mysqli_error($connect);
//}
	

	$sql = "SELECT id from possales WHERE loccode= 'SHOP1' AND terminal ='Counter 1' ORDER BY id DESC";
			
 $resultid = mysqli_query($connect,$sql); 
	
			$myrowid = mysqli_fetch_array($resultid) ;
			
			$DebtorTransID = $myrowid['id'];
//get line items from response

	 $items = $otherrequest->Items; // Replace ... with your PHP Object
	
	

$count=0;
		foreach($items as $key => $lineitems) {
	  
      $uom= 'each';
  $stockid =$lineitems->Stockid;
$stockname = $lineitems->Name;
$qty =$lineitems->Quantity;
			$unitprice = $lineitems->UnitPrice;

		$SQLcost = "SELECT materialcost
	               
			FROM stockmaster
			Where stockid = '".$stockid."'
			";
	
			$resultcost  = mysqli_query($connect,$SQLcost);
	
			$myrowcost  = mysqli_fetch_array($resultcost) ;
$costprice=  $myrowcost['materialcost'];
			
		 $sql61 = "INSERT INTO possales_details (
											orderlineno,
											orderno,
											stockid,
										    stock_name,
											qtyinvoiced,
											
											unitprice,
											quantity,
											cost_price,
											total,
											uom,
											discountpercent,
											serialnumber
										)
										VALUES  (
								'".   $count. "',
								'" . $DebtorTransID. "',
								'" .$stockid . "',
								'" .$stockname . "',
								'". $qty."',
								
								'". $unitprice."',
								'". $qty."',
								'". $costprice."',
								'". $lineitems->TotalAmount."',
								'". $uom."',
								'". $lineitems->Discount."',
							'". $lineitems->Serial."'
								
								)";

		
			//$result6 = mysqli_query($connect,$sql6,$ErrMsg);
 
			 $resultlineitems = mysqli_query($connect,$sql61); 
			
		$SQLvms1 = "SELECT confvalue
	               
			FROM config 
			Where confname = 'InventoryCashSales'
			";
	
			$result1 = mysqli_query($connect,$SQLvms1);
	
			$myrowvms1 = mysqli_fetch_array($result1) ;
$stocklogic =  $myrowvms1['confvalue'];
		
			
			if ($stocklogic ==0) {
			 $SQLlocstockonhand="SELECT locstock.quantity
								FROM locstock
								WHERE locstock.stockid='" . $stockid . "'
								AND loccode= '2'";
				 
				 
				  $resultstockonhand = mysqli_query($connect,$SQLlocstockonhand);
				  $rowstockonhand =  mysqli_fetch_array($resultstockonhand);
				 
				 $QtyOnHandPrior = $rowstockonhand['quantity'];
			
			
		
		
		
		
		$datetime = date('Y-m-d H:i:s') ;
		
		$sql17 ="SELECT typeno from systypes where typeid = 17";
			
		$Result = mysqli_query($connect,$sql17); 
			
			$myrow17 = mysqli_fetch_array($Result) ;
			
			$AdjustmentNumber = $myrow17['typeno']+1;
			
			
				$SQLstockmoves = "INSERT INTO stockmoves (stockid,
												type,
												transno,
												loccode,
												trandate,
												userid,
												debtorno,
												branchcode,
												price,
												prd,
												reference,
												qty,
												discountpercent,
												standardcost,
												newqoh,
												narrative,
												status)
						VALUES ('" . $stockid . "',
								17,
								'" . $AdjustmentNumber. "',
								'2',
								'" . $datetime. "',
								'" . $userid. "',
								'',
								'',
								'',
								'" . $PeriodNo . "',
								'Counter 1 POS Sales - ReceiptNo:- ".$request->InvoiceNumber."',
								'" . -$qty . "',
								'',
								'',
								'" . ($QtyOnHandPrior - $qty) . "',
									'Counter 1 POS Sales - ReceiptNo:-  ".$request->InvoiceNumber."',
								'1')";
					 
	
			$Result = mysqli_query($connect,$SQLstockmoves);
			
			
					$sql18 ="UPDATE systypes SET	typeno ='" . $AdjustmentNumber . "' WHERE typeid = 17";
			
		$Result = mysqli_query($connect,$sql18);
			
			
				$SQL = "UPDATE locstock SET	quantity= locstock.quantity -'" . $qty . "',
											lastupdate ='" . $sqldate."'
									WHERE stockid='" . $stockid . "' AND loccode = 'SHOP1'";


			$Result = mysqli_query($connect,$SQL); 
			}
		$count++;

				

			
  }
			
//taxes
	
		
	 $itemtaxes = $response->TaxItems; 

					
$totaltax= 0;
		foreach($itemtaxes as $key => $lineitemtax) {
			
			if ($lineitemtax->Label =='P'){
				
				
			$SQL = "UPDATE possales SET	plastic ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

			
			$Result = mysqli_query($connect,$SQL);
				
			}
			if ($lineitemtax->Label =='A'){
				
				
			$SQL = "UPDATE possales SET	ovgst ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

		$Result = mysqli_query($connect,$SQL);
				
			}
			if ($lineitemtax->Label =='E'){
				
				
			$SQL = "UPDATE possales SET	stt ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

			$Result = mysqli_query($connect,$SQL);
				
			}
			if ($lineitemtax->Label =='F'){
				
				
			$SQL = "UPDATE possales SET	ecal ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

			$Result = mysqli_query($connect,$SQL);
				
			}
			
			
			$totaltax = $totaltax + $lineitemtax->Amount;
		}
	
		$SQL = "UPDATE possales SET	total_tax ='" . $totaltax. "'
									WHERE id  = '" . $DebtorTransID. "'";

		$Result = mysqli_query($connect,$SQL);
	

			
			$sql614 = "INSERT INTO possales_payments (
											possalesid,
											
											payment_type,
											payment_amount
										)
										VALUES  (
								'" . $DebtorTransID. "',
								
								'".   $request->PaymentType. "',
								'". $otherrequest->RoundedAmount."'
								)";

		
			//$result6 = mysqli_query($connect,$sql6,$ErrMsg);
 
			 $resultlineitems4 = mysqli_query($connect,$sql614);
			
			mysqli_close($connect);	

			
		}
	
	
		
	
		
}
?>
