<?php
error_reporting(E_ALL & ~E_NOTICE);
ob_start();
$PageSecurity=0;
include ('includes/GetSalesTransGLCodes.inc');
/*defines the structure of the data required to hold the transaction as a session variable */
//include ('includes/DefineCartClass.php');
include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');
   ?>
  <script src="https://vsdc.staging.vms.frcs.org.fj/onlinepos/v1/taxcore.min.js"></script>
<?
	//echo $request->BuyerCostCenterId;

	
  
	 

	 
$_SESSION['transno']= $_GET['transno'];

$erpinvoicenumber= $_SESSION['transno'];


if (isset($_POST['ProcessCredit'])) {

	/* SQL to process the postings for sales credit notes... First Get the area where the credit note is to from the branches table */

	$sdcinvoicenumber2 = $_SESSION['invoicenumber1'];
   $erpinvoicenumber2 = $_SESSION['transno1'];

	$quotedate1= date('d/m/Y h:i a');
	$quotedate= date('m/d/Y h:i:s a');

    $date =date(DATE_ISO8601, strtotime($quotedate));
	
	
		$userid = $_SESSION['UserID'];
		
$SQLuser = "SELECT email,realname,tin,pac
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];
$realname= $myrowuser['realname'];
$usertin= $myrowuser['tin'];	
$pac = $myrowuser['pac'];	
		if ($myrowuser['tin'] == ''){
			
			$usertin = $userid;
		}

//retrieve header info from debtor trans
	  
	   $SQL = "SELECT 	*
							 
			FROM possales
			WHERE sdc_invoice_no ='" . $sdcinvoicenumber2. "'
			";
	
	$result = DB_query($SQL);
	
	$myrow = DB_fetch_array($result) ;

	$loccode = $myrow['loccode'];
 $terminal = $myrow['terminal'];

	/*Start an SQL transaction */
for($i=0; $i<$_POST["total_item"]; $i++)
      {
        
		  //get tax for line item
		  
		  
	
		$SQLtax = "SELECT sales_tax
				   
			FROM item_tax
			WHERE stockid='" . $_POST["stockid"][$i]. "'
			";
	
	$result = DB_query($SQLtax);
	$label =array();
	while( $rowtax = DB_fetch_array($result) ){
		
				$SQLlabel = "SELECT tax_label
				   
			FROM new_sales_tax
			WHERE id='" . $rowtax['sales_tax']. "'
			";
	
		
	$resultlabel = DB_query($SQLlabel);
		$rowlabel = DB_fetch_array($resultlabel);
		
		
		$label[] = $rowlabel['tax_label'];
		
		
	};
		$labeljson = json_encode($label);
		  
		  
		  $itemsdata[] = array(
			'Name'=>($_POST["stockname"][$i]),
			'Labels'=> json_decode($labeljson),
			'UnitPrice'=>trim($_POST["Price"][$i]),
			'Quantity'=>trim($_POST["Quantity"][$i]),
			'TotalAmount'=> $_POST["Quantity"][$i]* $_POST["Price"][$i]
			);
		  
		  $itemsother[] = array(
			'Stockid'=>trim($_POST["stockid"][$i]),
			'Name'=>($_POST["stockname"][$i]),
			'Labels'=> json_decode($labeljson),
			'UnitPrice'=>trim($_POST["Price"][$i]),
			'Quantity'=>trim($_POST["Quantity"][$i]),
			'TotalAmount'=> $_POST["Quantity"][$i]* $_POST["Price"][$i]
			);
		  
		
		  
	  }
	

			
	 $itemssdc = json_encode($itemsdata,true);
		
     $itemssdcother = json_encode($itemsother,true);
			$notes = $_POST['CreditText'];
	        

		//check if this is training or normal sales
		$SQLTT = "SELECT trainee
				   
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
	$resultTT = DB_query($SQLTT);
		$rowtt = DB_fetch_array($resultTT);
		
		if ($rowtt['trainee'] == 1){
			
			$invoicetype = "Training";
		}
		if ($rowtt['trainee'] == 0){
			
			$invoicetype = "Normal";
		}
		
	$notes =$_POST['CreditText'];
	
	$credittype = $_POST['CreditType'];
	
	$sqlref ="SELECT typeno from systypes where typeid = 70";
			
		$Result = DB_query($sqlref); 
			
			$myrow179 = DB_fetch_array($Result) ;
			
			$refundreceiptno = $myrow179['typeno']+1;
	
	       $refundreceiptno = "Refund-".$refundreceiptno;
	echo "


<div id='printarea' style='text-align: center'>
<div id='printdata'  style='font-size:18px'>
<img src='https://ebusinescloudservers.com/demo/smalllogo1.jpg' width='300px' height='100px'>
<div style='font-weight:bold'>Tebara Prime Cuts</div>
<div >Terminal: Counter 1 Shop: Main Branch</div>
<div >Ph:XXXXXXX Mob:XXXXXXX</div>
<div >Email:info@domain.com</div>
<pre class='output'></pre>

<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:12px'>--------------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 '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
	?>
	<div style='text-align: center'>
  <textarea name= 'results' id='results' cols='100' rows='30' style='display:block'></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="complete" id="complete" class="btn btn-info" value="Complete"/>


</form>	
    <div id="smart" style='text-align: center'> Communicating with VSDC....</div>
  
  
  <div id ="signing" style='text-align: center'> Click this button to sign invoice with FRCS VMS </div>
               <div id ="signing1" style='text-align: center'> Signing Refund Invoice. Please hold.... </div>
               <div id ="signing2" style='text-align: center'> Success. Please check the pdf copy thats downloaded below</div>
                </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>
                </div>
                
<a href='POSTrans.php'>  <button type='button' name='invoicing'  id ="posbtt" class='btn btn-info'>Go to POS Trans Listings</button></a>
<input type='button' id='btn' value='RePrint' onclick='printData();'>
  
 
   <?

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 Refund Invoice to FRCS Tax System</button></div>";
 

			
 
 
	
 
 echo"<script src='https://vsdc.staging.vms.frcs.org.fj/onlinepos/v1/taxcore.min.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());

$('#complete').hide();
$('#invoiceRequest').hide();
$('#otherRequest').hide();
$('#printdata').hide();
	$('#receipt').hide();
	$('#results').hide();
  $('#taxcore_sign_element').hide();

 $('#btn').hide();
		$('#error').hide();
		
	$('#receipt_wrapper').hide();	
	
		$('#signing').hide();
	$('#signing1').hide();
	$('#signing2').hide();
	$('#error').hide();
  $('#taxcore_sign_element').hide();
 $('#smart').show();
  $('#posbtt').hide();
  
 
 function CreateExampleInvoiceRequest() {

 var invoiceRequest = {
 'DateAndTimeOfIssue': '$quotedate',
 'Cashier': '$usertin',
 'BD': '',
 'BuyerCostCenterId': null,
 'IT': '$invoicetype',
 'TT': 'Refund',
 'PaymentType': 'cash',
 'InvoiceNumber': '$refundreceiptno',
 'ReferentDocumentNumber': '$sdcinvoicenumber2',
 'PAC': '$pac',
 'Options': {
 'OmitTextualRepresentation': 0,
 'OmitQRCodeGen': 0
	 },
 'Items': $itemssdc
 
 };
 return invoiceRequest;
 
 
 }


function Other() {

 
 var otherRequest = {

 
 'Notes': '$notes',
 'Date': '$quotedate1',
 'Loccode': '$loccode',
 'Terminal': '$terminal',
 'Items': $itemssdcother,
 'UserTin':'$usertin'

 };
 return otherRequest;
 }







		
setTimeout(function() {


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

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

  

$('#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');
             
 
  					$('#posbtt').show();
					$('#btn').show();
				 
					$('#printdata').show();
					 
		 $('#complete').trigger('click');
     
	
	 
}, 1e3);
	}
			
			if (obj.status_code != 200){
			
		$('#error').show();
			alert(attrmethod);
			
			 parent.history.back();
			
			}
    }, 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();
}


	
	
	


	
</script>
";
	


}
	
	
	//gather sdc data
	

elseif (isset($_POST['complete'])&& isset($_POST['results'])){
	
	

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

		$userid = $_SESSION['UserID'];
	
		//open projectdetail table to start gathering informations which we will first insert at salesorders table  and get pdf headers written. Salesorders will assist in converting quotation to invoice. This below is simply a quote generation.
	
	   
	
	
	$quotedated = $response->DT;
	
	$sqldate = date("Y-m-d");
	$sqldate1 = date("Y-m-d h:i:s");
$yeardate = date('Y',strtotime($sqldate));
$monthdate =date('m',strtotime($sqldate));
$monthname =date('M',strtotime($sqldate)); 
	
	$sdctime =  date("Y-m-d h:i:s a",$quotedated );
	    $query22 = "SELECT 
						periodno,
		             lastdate_in_period
		                 
					  
		          FROM periods
				    WHERE YEAR(lastdate_in_period) = '" . $yeardate. "'
					AND MONTH(lastdate_in_period)  = '" . $monthdate. "'";
				
        $result22=DB_query($query22);
        $myrow22=DB_fetch_array($result22);
      
				$PeriodNo = $myrow22['periodno'];
		     	$data = $myrow22['lastdate_in_period'];	
				
	
		$userid = $_SESSION['UserID'];
		
$SQLuser = "SELECT email,realname
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];
$realname= $myrowuser['realname'];
	//database abstraction layer
	 $DefaultDispatchDate = FormatDateForSQL($DefaultDispatchDate);
	 
	
		 	
	
	
$SQLdebtor = "INSERT INTO possales (
									transno,
									sdc_invoice_no,
									ReferentDocumentNumber,
									invoice_type,
									type,
									trandate,
									loccode,
									terminal,
								    paymenttype,
									totalamount,
								    invtext,
									
								    entered_by)
				VALUES (
				
					'" . $request->InvoiceNumber. "',
					'" . $response->IN. "',
					'" . $request->ReferentDocumentNumber. "',
					'" . $request->IT. "',
				    '70',
					'" . $sqldate . "',
					
					'" . $otherrequest->Loccode . "',
					'" . $otherrequest->Terminal . "',
					
					'Cash',
					'" . $response->TotalAmount . "',
					
					'" . $otherrequest->Notes . "',
					
					'" . $userid . "'
				
					)";
		
	//	$result = DB_query($connect,$SQLdebtor);
			
$results = DB_query($SQLdebtor);

	$sql = "SELECT id from possales WHERE loccode = '" . $otherrequest->Loccode . "' AND terminal = '" . $otherrequest->Terminal . "'
	ORDER BY id DESC";
			
$resultsid = DB_query($sql);
	
			$myrowid = DB_fetch_array($resultsid) ;
			
			$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;

		
			
		 $sql61 = "INSERT INTO possales_details (
											orderlineno,
											orderno,
											stockid,
										    stock_name,
											qtyinvoiced,
											
											unitprice,
											quantity,
											total,
											uom,
											discountpercent
										)
										VALUES  (
								'".   $count. "',
								'" . $DebtorTransID. "',
								'" .$stockid . "',
								'" .$stockname . "',
								'". $qty."',
								
								'". $unitprice."',
								'". $qty."',
								'". $lineitems->TotalAmount."',
								'". $uom."',
								
								0
								
								)";

		
			//$result6 = DB_query($connect,$sql6,$ErrMsg);
 
			 $resultlineitems = DB_query($sql61); 
			
			
			
			
			 $SQLlocstockonhand="SELECT locstock.quantity
								FROM locstock
								WHERE locstock.stockid='" . $stockid . "'
								AND loccode= '" . $otherrequest->Loccode . "'";
				 
				 
				  $resultstockonhand = DB_query($SQLlocstockonhand);
				  $rowstockonhand =  DB_fetch_array($resultstockonhand);
				 
				 $QtyOnHandPrior = $rowstockonhand['quantity'];
			
			
		
		
		
		
		$datetime = date('Y-m-d H:i:s') ;
		
		$sql17 ="SELECT typeno from systypes where typeid = 17";
			
		$Result = DB_query($sql17); 
			
			$myrow17 = DB_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. "',
								'" . $otherrequest->Loccode . "',
								'" . $datetime. "',
								'" . $userid. "',
								'',
								'',
								'',
								'" . $PeriodNo . "',
								'POS Refund',
								'" . $qty . "',
								'',
								'',
								'" . ($QtyOnHandPrior + $qty) . "',
								'POS Refund',
								'1')";
					 
	
			$Result = DB_query($SQLstockmoves);
			
			
					$sql18 ="UPDATE systypes   SET	typeno ='" . $AdjustmentNumber . "' WHERE typeid = 17";
			
		$Result = DB_query($sql18);
			
			
				$SQL = "UPDATE locstock SET	quantity= locstock.quantity +'" . $qty . "',
											lastupdate ='" . $sqldate."'
									WHERE stockid='" . $stockid . "' AND loccode = '" . $otherrequest->Loccode . "'";


			$Result = DB_query($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 = DB_query($SQL);
				
			}
			if ($lineitemtax->Label =='A'){
				
				
			$SQL = "UPDATE possales SET	ovgst ='" . $lineitemtax->Amount . "'
									WHERE id  = '" . $DebtorTransID. "'";

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

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

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

		$Result = DB_query($SQL);
	
$sqlref ="SELECT typeno from systypes where typeid = 70";
			
		$Result = DB_query($sqlref); 
			
			$myrow179 = DB_fetch_array($Result) ;
			
			$refundreceiptno = $myrow179['typeno']+1;

	$sql188 ="UPDATE systypes   SET	typeno ='" . $refundreceiptno . "' WHERE typeid = 70";
			
		$Result888 = DB_query($sql188);
	
 header('Location: POSTrans.php');

	
	
}



else{
	 
	 

	$_SESSION['invoicenumber'] = ($_GET['invoicenumber']);
	

	$sdcinvoicenumber = $_SESSION['invoicenumber'];
	

	
	$_SESSION['erpinvoice']= $_GET['transno'];
	 

  $erpinvoice = $_SESSION['erpinvoice'];
//	$_SESSION['CreditItems' . $identifier] = new cart;
	
	
	
	//check if its a refund
	  $SQL = "SELECT 	*
							 
			FROM possales
			WHERE sdc_invoice_no ='" . $sdcinvoicenumber. "'
			";
	
	$result = DB_query($SQL);
	
	$myrow = DB_fetch_array($result) ;

	if ($myrow['type'] =='70'){
		
		 $message = "Cant do Refund since this is a refund iteself";
	echo "<script type='text/javascript'>alert('$message');</script>";
		echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	exit();
		
	}

	
	//check if its duplicate refund
	  $SQL = "SELECT 	*
							 
			FROM possales
			WHERE ReferentDocumentNumber ='" . $sdcinvoicenumber. "'
			";
	
	$resultsdc = DB_query($SQL);
	
	$myrowsdc = DB_fetch_array($resultsdc) ;
	
	if (isset($myrowsdc['id'])){
		
		 $message = "Cant do Refund since this transaction with that invoice number already processed for refund";
	echo "<script type='text/javascript'>alert('$message');</script>";
		echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	exit();
		
	}
	
	$quotedate1= date('d/m/Y h:i:s a');
	$quotedate= date('m/d/Y h:i:s a');
    $date =date(DATE_ISO8601, strtotime($quotedate));
	
		$userid = $_SESSION['UserID'];
		
$SQLuser = "SELECT email,realname,tin
	               
			FROM www_users
			WHERE userid='" . $userid. "'
			";
	
			$resultuser = DB_query($SQLuser);
	
			$myrowuser = DB_fetch_array($resultuser) ;
		$emailm= $myrowuser['email'];
$realname= $myrowuser['realname'];
$usertin= $myrowuser['tin'];	
	

//retrieve header info from debtor trans
	  
	 

	/*read in all the guff from the selected invoice into the Items cart	*/



/* Always display credit quantities
 NB QtyDispatched in the LineItems array is used for the quantity to credit */
echo '<p class="page_title_text"><img src="' . $RootPath . '/css/' . $Theme . '/images/credit.png" title="' . _('Search') . '" alt="" />' . $Title . '</p>';

echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') .'" method="post">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';



	echo '<table cellpadding="2" class="selection">';
	echo '<tr><th colspan="13">';
	echo '<div class="centre"><b>' . _('Credit ERP InvoiceNO:') . ' ' . $erpinvoice . '</b>
		<b>' . ' - ' . $debtorname . '</b>
		 - ' .  _('Credit SDC  InvoiceNO:') . ' ' . $sdcinvoicenumber .'</div>';
	echo '</th></tr>';
	echo '<tr>
			<th>' . _('Orderline') . '</th>
			<th>' . _('Item Code') . '</th>
			<th>' . _('Item Description') . '</th>
			<th>' . _('Invoiced') . '</th>
			<th>' . _('Units') . '</th>
			
			<th>' . _('Credit') . '<br />' . _('Quantity') . '</th>
			<th>' . _('Price') . '</th>
			
			<th>' . _('Total') . '<br />' . _('') . '</th>
		
			<th>&nbsp;</th>
		</tr>';




/*show the line items on the invoice with the quantity to credit and price being available for modification */

	               

		 
			  
			   if (isset($_GET["action"])){
        if ($_GET["action"] == "delete"){
           
			foreach ($_SESSION["cart"] as $keys => $value){
               if ($value["orderlineno"] == $_GET["orderlineno"]){
                    unset($_SESSION["cart"][$keys]);
                    //echo '<script>alert("Product has been Removed...!")</script>';
                    //echo '<script>window.location="CreditInvoice.php"</script>';
                }
            }

			  }
        }
    

$SQL = "SELECT orderlineno,stockid,stock_name,qtyinvoiced,unitprice,quantity,uom FROM possales_details WHERE orderno = '" . $myrow['id'] . "'
									";
		$ErrMsg = _('Failed to retrieve salesoderdetails to compare if the order has been invoiced and that it is possible that the credit note may not already have been done');
		$Result = DB_query($SQL, $ErrMsg);
		

$tabindex = 1; 
$DisplayGrossLineTotal = 0;

			  $i = 0; //counter for input controls
			  
			    $_SESSION['count'] = 0;

    $_SESSION['cart'][$_SESSION['count']] = array();
			  
while($rowsalesdetails =DB_fetch_array($Result))
      {
		  
		 		  
		  
	  $_SESSION['cart'][$_SESSION['count']]['orderlineno'] = $rowsalesdetails['orderlineno'];
		$_SESSION['cart'][$_SESSION['count']]['stkcode'] = $rowsalesdetails["stockid"];  
		  $_SESSION['cart'][$_SESSION['count']]['stock_name'] = $rowsalesdetails["stock_name"];
		$_SESSION['cart'][$_SESSION['count']]['quantity'] = $rowsalesdetails["quantity"];  
$_SESSION['cart'][$_SESSION['count']]['unitprice'] = $rowsalesdetails["unitprice"];
		$_SESSION['cart'][$_SESSION['count']]['qtyinvoiced'] = $rowsalesdetails["qtyinvoiced"];  
			$_SESSION['cart'][$_SESSION['count']]['uom'] = $rowsalesdetails["uom"]; 
		  
		   $_SESSION['count'] = $_SESSION['count'] + 1;
	  }
			  
			$cnt= 0;  
			  $totalitemcount=0;
			  foreach($_SESSION['cart'] as $key => $value)
    {
		
		$Identifier = 'orderline_'.$cnt;
		 echo '<tr  id="row_id_' . $Identifier . '" class="striped_row">
		    <td><input  maxlength="6" class = "form-control input-sm number_only orderline" id="orderline_' . $Identifier . '"  size="6"  tabindex="' . $tabindex++ . '"  type="text" value="' . $value["orderlineno"]. '"  disabled ="disabled"/></td>
			<td><input  maxlength="6" name="stockid[]" class = "form-control input-sm number_only stockid" id="stockid_' . $Identifier . '"  size="6"  tabindex="' . $tabindex++ . '"  type="text" value="' . $value["stkcode"]. '" readonly/></td>
			<td><input  maxlength="6" name="stockname[]" class = "form-control input-sm stockname" id="stockname_' . $Identifier . '"  size="6"  tabindex="' . $tabindex++ . '"  type="text" value="' . $value["stock_name"]. '" readonly/></td>
			<td><input  maxlength="6" class = "form-control input-sm number_only QuantityInvoiced" id="invoiced_' . $Identifier . '"  size="6"  tabindex="' . $tabindex++ . '"  type="text" value="' . $value["quantity"]. '" disabled ="disabled"/></td>
			<td>' . $value["uom"] . '</td>
			
			';
            
		

			echo '<td><input  maxlength="6" class = "form-control input-sm number_only Quantity" id="' . $Identifier . '" name="Quantity[]" required="required" size="6"  tabindex="' . $tabindex++ . '" title="' . _('Enter the quantity of this item to credit') . '" type="text" value="' . $value["quantity"]. '" /></td>';

		
		echo '<td><input maxlength="12" class="form-control input-sm number_only Price" id="Price_' . $Identifier . '"  name="Price[]" required="required" size="6" tabindex="' . $tabindex++ . '" title="' . _('Enter the price at which to credit this item') . '" type="text" value="' . $value["unitprice"] . '" /></td>';
			
			
			$LineTotal = $value["quantity"] * $value["unitprice"] ;
			echo '<td><input  maxlength="12" class="form-control input-sm number_only linetotal" id="linetotal_' . $Identifier  . '"  name="linetotal_' . $i . '"  size="6" disabled ="disabled"/></td>';

		/*Need to list the taxes applicable to this line */

	
		echo '</td>';

		echo '
				<td><button class = "remove" id="' . $Identifier  . '"> X </button></td>
			</tr>';

	
		  
		$cnt++; 	
$i++;
		  
		 
		  $DisplayGrossLineTotal =  $DisplayGrossLineTotal + $LineTotal ;
			  
		  $totalitemcount++;
	  
		  }
  

	echo '<tr>
			<td class="number" colspan="7">' . _('Credit Totals') . '</td>
			<td class="number"><hr /><b><input  maxlength="12" class="form-control input-sm number_only grandtotal" id="grandtotal"  name="grandtotal"  size="6" disabled ="disabled"/></b><hr /></td>
			
			<td>&nbsp;</td>
		</tr>
		</table>';
			  
			
	echo '<br />
		<table class="selection">
		<tr>
			<td>' . _('Credit Note Type') . '</td>
			<td><select name="CreditType" tabindex="' . $tabindex++ . '" ">';

	if (!isset($_POST['CreditType']) or $_POST['CreditType'] == 'Return') {
		echo '<option selected="selected" value="Return">' . _('Goods returned to store') . '</option>';
		echo '<option value="WriteOff">' . _('Goods written off') . '</option>';
		echo '<option value="ReverseOverCharge">' . _('Reverse overcharge') . '</option>';
	} elseif ($_POST['CreditType'] == 'WriteOff') {
		echo '<option selected="selected" value="WriteOff">' . _('Goods written off') . '</option>';
		echo '<option value="Return">' . _('Goods returned to store') . '</option>';
		echo '<option value="ReverseOverCharge">' . _('Reverse overcharge') . '</option>';
	} else {
		echo '<option value="WriteOff">' . _('Goods written off') . '</option>';
		echo '<option value="Return">' . _('Goods returned to store') . '</option>';
		echo '<option selected="selected" value="ReverseOverCharge">' . _('Reverse overcharge') . '</option>';
	}
	echo '</select></td>
		</tr>';
	$j++;

	
	if (!isset($_POST['CreditText'])) {
		$_POST['CreditText'] = '';
	}
	echo '<tr>
			<td>' . _('Credit note text') . '</td>
			<td><textarea name="CreditText" cols="31" rows="5" tabindex="' . $tabindex++ . '">' . $_POST['CreditText'] . '</textarea></td>
		</tr>
		</table>
		<br />
		<div class="centre">
			
			<br />';
	$j++;
	if (!isset($_POST['CreditText'])) {
		$_POST['CreditText'] = '';
	}
	echo ' <input type="hidden" name="total_item" id="total_item" value="' . $totalitemcount . '" />';
	echo '<input name="ProcessCredit" id = "processcredit" type="submit" tabindex="' . $tabindex++ . '" value="' . _('Process Credit') . '" />';
	echo "<a href='POSTrans.php'>  <button type='button' name='invoicing'  class='btn btn-info'>Go to POS Listings</button></a>";
		echo '</div>';

echo '</div>';
echo '</form>';
//echo $i;
//	echo "<br>";
	//echo $totalitemcount;
	//echo "<br>";
	//echo $Identifier;
	
	$_SESSION['invoicenumber1'] = 	$sdcinvoicenumber;
	
$_SESSION['transno1'] = $erpinvoicenumber;


 }
	
	
//echo 'Quotation Created Successfully'. $jobno.'!';
echo '</div>';
echo '</div>';
		  
 	echo '</div >';
	?>
						

		
					</div>
				</div>
			</div>
					
		  
	 
	 
 
	
	
	
 







	
					

						<!--end:: Widgets/Stats-->

						<!--Begin::Section-->
						

		<!-- end::Quick Sidebar -->

		<!-- begin::Scroll Top -->
		<div id="m_scroll_top" class="m-scroll-top">
			<i class="la la-arrow-up"></i>
		</div>

		<!-- end::Scroll Top -->

		<!-- begin::Quick Nav -->
		

		<!-- begin::Quick Nav -->
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>

		<!--end::Page Scripts -->
	</body>

	<!-- end::Body -->
</html>
 
      
<?php



/*The module link codes are hard coded in a switch statement below to determine the options to show for each tab */
include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p>
			</td>
			</tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p>
			</td>
			</tr>
			<tr>
			<td class="menu_group_item">
				<p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p>
			</td>
			</tr>
		</table>';

	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){ /*This is sent by this page (to itself) when the user clicks on a tab */
	$_SESSION['Module'] = $_GET['Application'];
}








//include('includes/footer.inc');

function GetRptLinks($GroupID) {
/*
This function retrieves the reports given a certain group id as defined in /reports/admin/defaults.php
in the acssociative array $ReportGroups[]. It will fetch the reports belonging solely to the group
specified to create a list of links for insertion into a table to choose a report. Two table sections will
be generated, one for standard reports and the other for custom reports.
*/
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id,
				reporttype,
				defaultreport,
				groupname,
				reportname
			FROM reports
			ORDER BY groupname,
					reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) { // then there are reports to show, show by grouping
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			// now fetch the form groups that are a part of this group (List after reports)
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']); // break into main group and form group array
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
	
?>
<!-- Modal HTML embedded directly into document -->
<div id="ex1" class="modal">
  <p>Thanks for clicking. That felt good.</p>
  <a href="#" rel="modal:close">Close</a>
</div>


<!-- Modal -->
 <div class="modal fade" id="getCodeModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
   <div class="modal-dialog modal-lg">
      <div class="modal-content">
       <div class="modal-header">
         <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
         <h4 class="modal-title" id="myModalLabel"> API CODE </h4>
       </div>
       <div class="modal-body" id="getCode" style="overflow-x: scroll;">
       
          
          
       </div>
    </div>
   </div>
 </div>
<script>
jQuery(document).ready(function($){

   // event must be delegated from .xcrud
	
	
	
	
function disableF5(e) {
		
if ((e.which || e.keyCode) == 116) 
	
	e.preventDefault(); 
	
	};
// To disable f5
    /* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);

// To re-enable f5

$(document).keydown(function (event) {
    if (event.keyCode == 123) { // Prevent F12
        return false;
    } else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) { // Prevent Ctrl+Shift+I        
        return false;
    }
});
	
	$(document).on("contextmenu", function (e) {        
    e.preventDefault();
});
// To disable f5
    /* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);


	
	 $(".Quantity").change(function(){
                 var identifier = $(this).attr('id');
		 
		 var qtyinvoiced = $("#invoiced_"+identifier).val();
		 
                 var Qty = $(this).val();
		 if (Qty <= qtyinvoiced && Qty !=0) {
			 
                 var Price = $("#Price_"+identifier).val();//price value
                 var Total =  parseFloat(Qty) * parseFloat(Price);  
		 var linetotal = parseFloat(Total).toFixed(2)
                 $("#linetotal_"+identifier).val(linetotal);              
                       GrandTotal();
			 
		 }
	
		 else{
			alert('Credit Quantity should be less than qty invoiced. For zero qty please delete the lineitem instead Correct this')
			   $(this).focus();
              return false; 
			 
		 }
               });
             GrandTotal();   

          function GrandTotal(){
            var GrandTotal=0;
             $(".Quantity").each(function(){
                 var identifier = $(this).attr('id');
                 var Qty = $(this).val();
                 var Price = $("#Price_"+identifier).val();//price value
                 var Total = parseFloat(Qty) * parseFloat(Price);                   
				 var linetotal = parseFloat(Total).toFixed(2)
                 GrandTotal += Total;
                 $("#linetotal_"+identifier).val(linetotal);    
               });
var GrandTotal = parseFloat(GrandTotal).toFixed(2)
          $("#grandtotal").val(GrandTotal);

        }

    	 $(".remove").click(function(){
                 var identifier = $(this).attr('id');
			 var total_item_amount = $('#linetotal_'+identifier).val();
          var final_amount = $('#grandtotal').val();
          var result_amount = parseFloat(final_amount) - parseFloat(total_item_amount);
			 var GrandTotal = parseFloat(result_amount).toFixed(2)
          $('#grandtotal').val(GrandTotal);
			 
			  var totalitem = $('#total_item').val();
			  var finalitemtotal = parseFloat(totalitem) - parseFloat(1);
			 $('#total_item').val(finalitemtotal);
		  $('#row_id_'+identifier).remove();
			  
               });

         
	
	
});
	
</script>