<?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['balance'] = ($_GET['balance']);
	  $_SESSION['cancelled'] = ($_GET['cancelled']);
	 
$_SESSION['transno']= $_GET['transno'];

$erpinvoicenumber= $_SESSION['transno'];
if (isset($_GET['debtorno'])) {
		$_SESSION['debtorno'] = stripslashes($_GET['debtorno']);
	}
	$debtorno = $_SESSION['debtorno'];	


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'];	
	

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

$account = $myrow['account_number'];
	$department = $myrow['department'];

$projectno = $myrow['projectid'];
$lpo = $myrow['lpo'];
$delivery = $myrow['delivery_address'];
	$orderno = $myrow['order_'];
	//business customer tin
	  
	   $SQL77 = "SELECT 	departmentname
							 
			FROM department
			WHERE departmentid='" . $myrow['department'] . "'
			";
	
	$result77 = DB_query($SQL77);
	
	$myrow77 = DB_fetch_array($result77) ;
		
	$departmentname = $myrow77['departmentname'];	
//get debtor headoffice details:
		$SQL100 = "SELECT 	name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6,
							 taxref
							 
			FROM debtorsmaster
			WHERE debtorno='" . $debtorno . "'
			";
	
	$result100 = DB_query($SQL100);
	
	$myrow100 = DB_fetch_array($result100) ;
		$debtorname = $myrow100['name'];
		
		$address1 = $myrow100['address1'];
		$address2 = $myrow100['address2'];
		$address3 = $myrow100['address3'];
		$address4 = $myrow100['address4'];
		$address5 = $myrow100['address5'];
		$address6=  $myrow100['address6'];
		
			$customertaxref=  $myrow100['taxref'];
	
	if (!isset($customertaxref)){
		
		$customertaxref ="null";
	}
		


	
	$CreditNo = GetNextTransNo(11);

	$PeriodNo = GetPeriod($DefaultDispatchDate);

	/*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'];
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='Invoicing-sdc.php'>  <button type='button' name='invoicing'  id ="invoicebtt" class='btn btn-info'>Go to Invoice Listings</button></a>

  
  <a href='CreditNoteListings-sdc.php'>  <button type='button' name='refund'  id ="refundbtt" class='btn btn-info'>Go to  Credit Note/Refunds Listings</button></a>
  
 
   <?

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

 $('#results').hide();
 $('#invoiceRequest').hide();
	$('#otherRequest').hide();
  $('#complete').hide();
$('#signing1').hide();
	$('#signing').hide();
	$('#signing2').hide();
  $('#taxcore_sign_element').hide();
 $('#invoicebtt').hide();

    $('#refundbtt').hide();
	 
  $('#error').hide();
 function CreateExampleInvoiceRequest() {

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


function Other() {

 
 var otherRequest = {

 'AccountNumber': '$accountnumber',
 'Notes': '$notes',
 'Date': '$quotedate1',
 'Project': '$projectno',
 'LPO': '$lpo',
 'department':'$department',
 'Items': $itemssdcother,
 'UserTin':'$usertin',
 'Delivery':'$delivery',
 'OrderNo': '$orderno',
 'CreditType': '$credittype',
 'oldinvoice':'$erpinvoicenumber2',
 'Debtorno': '$debtorno'
 };
 return otherRequest;
 }



setTimeout(function() {


$('#smart').hide();
    $('#taxcore_sign_element').show();
 
 
   $('#signing').show();
	
	 
}, 4e3);

  

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

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


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

$('#signing1').show();

$(function() {
    var intervalID = setInterval(function() {
	
	         
 					
			 
        	var attrmethod = $('#taxcore_sign_element').attr('data-taxcore-signed-invoice-response');
 				var obj = JSON.parse(attrmethod);
				
			if (obj.status_code == 200){
					
				
				
					$('#signing1').hide();
					
				 	$('#complete').trigger('click');
					
 			        clearInterval(intervalID);
					   
 			}
			
			if (obj.status_code != 200){
			
	
			alert(attrmethod );
			$('#signing1').hide();
			$('#error').show();
			$('#invoicebtt').show();
			$('#newbtt').show();
			   $('#refundbtt').hide();
	  $('#refund').hide();
 			clearInterval(intervalID);
			
			}
			
    }, 2000);

	
    setTimeout(function() {
        clearInterval(intervalID);
		
    }, 10000);
	
	
});

 
  
});



</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.
	
	   
	   
	   $SQL77 = "SELECT 	departmentname
							 
			FROM department
			WHERE departmentid='" . $otherrequest->department. "'
			";
	
	$result77 = DB_query($SQL77);
	
	$myrow77 = DB_fetch_array($result77) ;
		
	$departmentname = $myrow77['departmentname'];	
//get debtor headoffice details:
		$SQL100 = "SELECT 	debtorno,
							name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6
							 
			FROM debtorsmaster
			WHERE debtorno='" . $otherrequest->Debtorno . "'
			";
	
	$result100 = DB_query($SQL100);
	
	$myrow100 = DB_fetch_array($result100) ;
		$debtorname = $myrow100['name'];
		
		$address1 = $myrow100['address1'];
		$address2 = $myrow100['address2'];
		$address3 = $myrow100['address3'];
		$address4 = $myrow100['address4'];
		$address5 = $myrow100['address5'];
		$address6=  $myrow100['address6'];
		
		
		
		
				$SQL21 = "SELECT branchcode,brname,
								braddress1,
								braddress2,
								braddress3,
								phoneno,
								contactname,
								email
				   
			FROM custbranch
			WHERE debtorno='" . $myrow100['debtorno'] . "'
			";
	
	$result21 = DB_query($SQL21);
	
	$myrow21 = DB_fetch_array($result2) ;
		
		$branchname = $myrow21['brname'];
		$branchad1 = $myrow21['braddress1'];
		$branchad2 = $myrow21['braddress2'];
		$branchad3 = $myrow21['braddress3'];
		$branchad4 = $myrow21['braddress3'];
		$branchad5 = $myrow21['braddress3'];
		$branchad6 = $myrow21['braddress3'];
		$phoneno = $myrow21['phoneno'];
		$contactname = $myrow21['contactname'];
		$email = $myrow21['email'];
		
		

		$SQLpaymentterms = "SELECT 	paymentterms
							 
			FROM debtorsmaster
			WHERE debtorno='" . $myrow100['debtorno'] . "'
			";
	
	$resultpaymentterms = DB_query($SQLpaymentterms);
	$myrowpaymentterms = DB_fetch_array($resultpaymentterms) ;
	
	$SQLterms = "SELECT 	terms,dayinfollowingmonth,daysbeforedue
							 
			FROM paymentterms 
			WHERE termsindicator='" . $myrowpaymentterms['paymentterms'] . "'
			";
	
	
	$resultterms = DB_query($SQLterms);
	$myrowterms = DB_fetch_array($resultterms) ;
	
	$paymentterms = $myrowterms['terms'];
	$DisplayDueDate = CalcDueDate(ConvertSQLDate($sqldate), $myrowterms['dayinfollowingmonth'], $myrowterms['daysbeforedue']);
	
	$DisplayDueDate1 =  date("Y/m/d", strtotime($DisplayDueDate)); 
	
$InvoiceNo = $request->InvoiceNumber;
			//get periodno 
	
	
	
	$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);
	 
	 
	 //update refund lineitems for future reference 
	  $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;

			
			
		 $sql6 = "INSERT INTO refund_item_details (
											orderlineno,
											orderno,
											stkcode,
										    stock_name,
											qtyinvoiced,
											
											unitprice,
											quantity,
											total,
											uom,
											discountpercent,
										
											poline,
											itemdue)
										VALUES  (
								'".   $count. "',
								'" . $otherrequest->OrderNo . "',
								'" .$stockid . "',
								'" .$stockname . "',
								'". $qty."',
								
								'". $unitprice."',
								'". $qty."',
								'". $lineitems->TotalAmount."',
								'". $uom."',
								
								0,
								
								'',
								'". $sqldate."'
								)";

							$ErrMsg = _('This salesorderdetails could not be added because');
			$result6 = DB_query($sql6,$ErrMsg);
  

			 $SQLlocstockonhand="SELECT locstock.quantity
								FROM locstock
								WHERE locstock.stockid='" . $stockid . "'
								AND loccode= 'SUVA'";
				 
				 
				  $resultstockonhand = DB_query($SQLlocstockonhand);
				  $rowstockonhand =  DB_fetch_array($resultstockonhand);
				 
				 $QtyOnHandPrior = $rowstockonhand['quantity'];
			
			
		
		
		
		
	
		
		$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. "',
								'WARE',
								'" . $sqldate. "',
								'" . $userid. "',
								'',
								'',
								'',
								'" . $PeriodNo . "',
								'Credit Note',
								'" . $qty . "',
								'',
								'',
								'" . ($QtyOnHandPrior + $qty) . "',
								'Credit Note',
								'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 = 'WARE'";


			$Result = DB_query($SQL); 
			
			
		$count++;

					

			
  }
			
	 
	 
	 
	 	$SQL = "SELECT(totalamount-alloc) AS baltoallocate
			FROM debtortrans
			WHERE transno=" . $otherrequest->oldinvoice . "
			AND type=10";
	$Result = DB_query($SQL);
	$MyRow = DB_fetch_row($Result);



	$Allocate_amount = 0;
	$Settled = 0;
	$SettledInvoice = 0;
	if ($MyRow[0] > 0) { /*the invoice is not already fully allocated */

		if ($MyRow[0] > $response->TotalAmount) {

			$Allocate_amount = $response->TotalAmount;
			$SettledInvoice = 0;
			$Settled = 1;
	
		} elseif ($MyRow[0] < $response->TotalAmount) {
			/*the balance left to allocate is less than the credit note value */
			$Allocate_amount = $MyRow[0];
			$SettledInvoice = 1;
			$Settled = 0;
		} else {
			$Allocate_amount = $MyRow[0];
			$SettledInvoice = 1;
			$Settled = 1;
		}

	/*Now need to update the invoice DebtorTrans record for the amount to be allocated and if the invoice is now settled*/

		$SQL = "UPDATE debtortrans
				SET alloc = alloc +  " . $Allocate_amount . ",
					settled='" . $SettledInvoice . "',entered_by='" . $userid . "'
				WHERE transno= '" . $otherrequest->oldinvoice . "'
				AND type=10";

		$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The alteration to the invoice record to reflect the allocation of the credit note to the invoice could not be done because');
		$DbgMsg = _('The following SQL to update the invoice allocation was used');
		$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);
	}

	/*Now insert the Credit Note into the DebtorTrans table with the allocations as calculated above*/
	$SQL = "INSERT INTO debtortrans(transno,
									sdc_invoice_no,
									invoice_type,
									type,
									debtorno,
									delivery_address,
									projectid,
									branchcode,
									trandate,
									inputdate,
									prd,
									settled,
									reference,
									tpe,
									order_,
									lpo,
									rate,
									totalamount,
								   invtext,
									account_number,
									department,
									
									entered_by)
						VALUES(" . $request->InvoiceNumber . ",
									'" . $response->IN. "',
									'" . $request->IT. "',
							11,
							
					'" . $myrow100['debtorno']. "',
					'" . $otherrequest->Delivery. "',
					'" . $otherrequest->Project. "',
					'" .$myrow100['debtorno']. "',
					
					'" . $sqldate. "',
					'" . $sqldate . "',
					
					'" . $PeriodNo . "',
					'" . $Settled . "',
					'Inv-" . $otherrequest->oldinvoice . "',
						'DE',				
					 '" . $otherrequest->OrderNo . "',
					 '" . $otherrequest->lpo . "',
					'1',
					
					'" . -($Allocate_amount) . "',
					
					'" . $otherrequest->Notes . "',
					'" . $otherrequest->AccountNumber. "',
					'" . $otherrequest->department. "',
					
					'" . $userid . "')";

	$ErrMsg = _('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The customer credit note transaction could not be added to the database because');
	$DbgMsg = _('The following SQL to insert the customer credit note was used');
	$Result = DB_query($SQL, $ErrMsg, $DbgMsg, true);

	$CreditTransID = DB_Last_Insert_ID('debtortrans', 'id');

	 
		
	 $itemtaxes = $response->TaxItems; 

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

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			if ($lineitemtax->Label =='A'){
				
				
			$SQL = "UPDATE debtortrans SET	ovgst ='" . -$lineitemtax->Amount . "'
									WHERE  id = '" . $CreditTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			if ($lineitemtax->Label =='E'){
				
				
			$SQL = "UPDATE debtortrans SET	stt ='" . -$lineitemtax->Amount . "'
									WHERE  id = '" . $CreditTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			if ($lineitemtax->Label =='F'){
				
				
			$SQL = "UPDATE debtortrans SET	ecal ='" . -$lineitemtax->Amount . "'
									WHERE  id = '" . $CreditTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
				
			}
			
			
			$totaltax = $totaltax + $lineitemtax->Amount;
		}
	
		$SQL = "UPDATE debtortrans SET	total_tax ='" . -$totaltax. "'
									WHERE  id = '" . $CreditTransID. "'";

			$ErrMsg = _('The cost details for the stock item could not be updated because');
			$DbgMsg = _('The SQL that failed was');
			$Result = DB_query($SQL,$ErrMsg,$DbgMsg,true);
	
	
	 $itemtaxes = $response->TaxItems; // Replace ... with your PHP Object
	
	

		foreach($itemtaxes as $key1 => $lineitemtax) {
	  
      $uom= 'each';
  
			
			
		 $SQLdebtortax = "INSERT INTO debtortranstaxes (debtortransid,invoicenumber,
											
											taxlabel,categoryname,rate,
											
											taxamount)
								VALUES ('" . $CreditTransID  . "',
								'" . $request->InvoiceNumber. "',
									'" . $lineitemtax->Label. "',
									'" . $lineitemtax->CategoryName. "',
									'" . $lineitemtax->Rate. "',
									'" . -($lineitemtax->Amount). "')";

		$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The debtor transaction taxes records could not be inserted because');
		$DbgMsg = _('The following SQL to insert the debtor transaction taxes record was used');
 		$Result = DB_query($SQLdebtortax,$ErrMsg,$DbgMsg,true);
  



					

			
  }

	 
	 
	 
	
	$_SESSION['results'] = $_POST['results'];
	$_SESSION['invoiceRequest'] = $_POST['invoiceRequest'];
	$_SESSION['otherRequest'] = $_POST['otherRequest'];
//database done now throw message in new page and option to print it in pdf.
	
 header('Location: CompleteReturns.php');
	
	
} elseif ( $_SESSION['balance'] <= 0 OR $_SESSION['settled'] == 1 ){
		 
		 
		 $message = "Cant do Refund or Credit Note since the balance is less than zero";
	echo "<script type='text/javascript'>alert('$message');</script>";
		echo "<script type='text/javascript'>javascript:history.go(-1)</script>"; 
	exit();
		
	 }

else{
	 
	 

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

	$sdcinvoicenumber = $_SESSION['invoicenumber'];
	

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

  $erpinvoice = $_SESSION['erpinvoice'];
//	$_SESSION['CreditItems' . $identifier] = new cart;
	

	$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
	  
	   $SQL = "SELECT 	*
							 
			FROM debtortrans
			WHERE sdc_invoice_no ='" . $sdcinvoicenumber. "'
			";
	
	$result = DB_query($SQL);
	
	$myrow = DB_fetch_array($result) ;

$account = $myrow['account_number'];
	$department = $myrow['department'];

$projectno = $myrow['projectid'];
$lpo = $myrow['lpo'];
$delivery = $myrow['delivery_address'];
	$orderno = $myrow['order_'];
	//business customer tin
	  
	   $SQL77 = "SELECT 	departmentname
							 
			FROM department
			WHERE departmentid='" . $myrow['department'] . "'
			";
	
	$result77 = DB_query($SQL77);
	
	$myrow77 = DB_fetch_array($result77) ;
		
	$departmentname = $myrow77['departmentname'];	
//get debtor headoffice details:
		$SQL100 = "SELECT 	name,
							address1,
						     address2,
				   			 address3,
							 address4,
							 address5,
							 address6,
							 taxref
							 
			FROM debtorsmaster
			WHERE debtorno='" . $myrow['debtorno'] . "'
			";
	
	$result100 = DB_query($SQL100);
	
	$myrow100 = DB_fetch_array($result100) ;
		$debtorname = $myrow100['name'];
		
		$address1 = $myrow100['address1'];
		$address2 = $myrow100['address2'];
		$address3 = $myrow100['address3'];
		$address4 = $myrow100['address4'];
		$address5 = $myrow100['address5'];
		$address6=  $myrow100['address6'];
		
			$customertaxref=  $myrow100['taxref'];

	/*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,stkcode,stock_name,qtyinvoiced,unitprice,quantity,uom FROM salesorderdetails WHERE orderno = '" . $myrow['order_'] . "'
									";
		$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["stkcode"];  
		  $_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='Invoicing.php'>  <button type='button' name='invoicing'  class='btn btn-info'>Go to Invoice 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);


	
	 $(".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>