<?php

session_start();
if($HTTP_SESSION_VARS['dbName']==""){
header("location:../index.php");
}


include("config.inc.php");
include("Functions_Sales.php");
include("function.inc.php");

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($HTTP_SESSION_VARS['dbName'],$connection) or die("Could not find DB");

//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}
							
//Read From Module Table
$querymodule=" Select Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ".
             " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit ".
             " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage from setup ";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='additemserials' method='post' action=''>
<input type='hidden' name='ItemSerialNo' id='ItemSerialNo' value='$ItemSerialNo' size='20' maxlength='40'/>
<input type='hidden' name='SerialId' id='SerialId' value='$SerialId' size='10' maxlength='40'/>
<input type='hidden' name='RSaId' id='RSaId' value='$RSaId' size='10' maxlength='40'/>
<input type='hidden' name='PerPage' id='PerPage' value='$PerPage' size='10' maxlength='40'/>
<input type='hidden' name='Mode' id='Mode' value='$Mode' size='10' maxlength='40'/>		    
HERE;

if ($Mode == 'insert' && $ItemSerialNo != '') {

	$query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
			" From Purchasesserialno ".
			" where Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
			" And Purchasesserialno.Journal_Type =  'DI' ";
			  
	$result = selectData($connection, $query);
	$SerialNoExists = $result[0];
	
	$IsAvailable = 1;
	$ErrorExists = 0;
	$SelectedSerialID = 0;
	$SelectedSerialQty     = 0;
	$SelectedSerialQtySold = 0;
	$SelectedItemCode      = '';
	$SelectedDeliveryDtID  = '';
	
	if ($SerialNoExists != '') {
		if ($lstWarehouse != '' && isset($lstWarehouse)) {
		
			$sub_query= " Select *  ".
						" From temp_purchasesserialno ".
						" where SerialNo_Code =  '".$ItemSerialNo."' ".
						" And Journal_Type in ('DR')";
			 //echo $sub_query; exit;	 
			$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
			$RecCount=mysql_num_rows($sub_result);
		
			if ($RecCount == 0 || $RecCount == '') {
				$sub_query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, Item_Code, ifNull(PurchaseDt_ID, DeliveryDt_ID)  ".
							" From purchasesserialno ".
							" where SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Warehouse_Code =  '".$lstWarehouse."' ".
							" And Journal_Type = 'DI' ";
							
							
				//echo $sub_query; exit;			
				$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
				$sub_row=mysql_fetch_array($sub_result);
				$RecCount=mysql_num_rows($sub_result);
				
				if ($RecCount == 0) {
					$IsAvailable = 0;
					$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available in the warehouse (".$lstWarehouse.") . "; 
				}	
				else {
					
					if ($sub_row[1] == 1)
					{
						//In Edit Case And Delete A Serial For The Return Invoice Then
					    // Allow To Add That Serial Again By Getting The Serials Related For That Return Invoice(First Part Of Query Below)
						$sub_query= " Select RelatedSerial_Id As Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ".
									" ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, DeliveryDt.Item_Code, DeliveryDt.RelatedDt_ID As DeliveryDtID, 1 As OrderColumn ".
									" From purchasesserialno ".
									" Inner Join DeliveryDt on DeliveryDt.DeliveryDt_ID = Purchasesserialno.PurchaseDt_ID ".
									" Where DeliveryDt.Delivery_ID = '".$RSaId."' ".
									" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
									" And Purchasesserialno.Warehouse_Code =  '".$lstWarehouse."' ".
									" And Purchasesserialno.Journal_Type = 'DR' ".
									" And DeliveryDt.Journal_Type = 'DR' ".
									" Union ".
									" Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0), ".
									" Item_Code, ifNull(PurchaseDt_ID, DeliveryDt_ID) As DeliveryDtID, 2 As OrderColumn  ".
									" From purchasesserialno ".
									" where SerialNo_Code =  '".$ItemSerialNo."' ".
									" And Warehouse_Code =  '".$lstWarehouse."' ".
									" And ifNull(SerialNo_Used,0) = 0 ".
									" And Journal_Type = 'DI' ".
									" Order by OrderColumn ";
						$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
						$sub_row=mysql_fetch_array($sub_result);
						$RecCount=mysql_num_rows($sub_result);
						
						if ($RecCount == 0) {
							$IsAvailable = 0;
							$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is used in warehouse (".$lstWarehouse."). "; 
						}  else {
							$SelectedSerialID      = $sub_row[0];
							$SelectedSerialQty     = $sub_row[3];
							$SelectedSerialQtySold = $sub_row[4];
							$SelectedItemCode      = $sub_row[5];
							$SelectedDeliveryDtID  = $sub_row[6];
							$IsAvailable = 1;
						}	
					
					} else {
						$SelectedSerialID      = $sub_row[0];
						$SelectedSerialQty     = $sub_row[3];
						$SelectedSerialQtySold = $sub_row[4];
						$SelectedItemCode      = $sub_row[5];
						$SelectedDeliveryDtID  = $sub_row[6];
						$IsAvailable = 1;
					}	

				}	
			}
			else {
				$IsAvailable = 0;
				$message  = "Insert not allowed, duplicate serial no. "; 
			}	
		}
		else {
			$IsAvailable = 0;
			$message  = "Insert not allowed, warehouse is empty. "; 
		}	
	}
	else {
		$IsAvailable = 0;
		$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available. "; 
	}
	
	
	if ($IsAvailable == 1)
	{
		
		$ErrorExists = 0;
		$SelectedDeliveryID = '';
		
		$sub_query = " Select Delivery_ID From DeliveryDt ".
		             " Where DeliveryDt.DeliveryDt_ID = '".$SelectedDeliveryDtID."' ".
					 " And DeliveryDt.Journal_Type = 'DI' ";
		$sub_result = selectData($connection, $sub_query);
		$SelectedDeliveryID = $sub_result[0];				   			 
				
		//Insert Master Table
		if ($RSaId == "" && $ErrorExists == 0){
		
			fbegin();	
			$vRSaId = get_nextsequence('delivery_id','',$connection);	
			fcommit();
			
			if ($Module_Delivery == 0) {	
				$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
						 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
						 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
						 " Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
						 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
						 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
						 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_SorderReferences, Detail_Code, Delivery_TaxableTTC, Delivery_DiscountTTC, Delivery_ReturnRef, Delivery_VatChkbx, User_Account, Logged_Code) ".
						 " SELECT $vRSaId, Null, Sorder_reference, now(), ADDDATE(now(), ifNull(Clients.Client_PaymentTerms,0)), Delivery_Remark, Deliveries.Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Deliveries.Salesman_Code, ".
						 " Deliveries.Currency_Code, Deliveries.Project_Code, Deliveries.Costcent_code, 0, 0, Delivery_Taxable, Delivery_TaxableBase1, Delivery_TaxableBase2, Delivery_NoneTaxable, Delivery_NoneTaxableBase1, Delivery_NoneTaxableBase2, ".
						 " Delivery_DiscountAmount, Delivery_DiscountBase1, Delivery_DiscountBase2, Delivery_DiscountPer, Delivery_VAT, Delivery_VATBase1, Delivery_VATBase2, Delivery_Total, Delivery_TotalBase1, Delivery_TotalBase2, ".
						 " 0, Delivery_Mode, 'DR', Null, Delivery_BelongsToGroup, Delivery_Tax1, Delivery_Tax2, Delivery_Tax3, Delivery_Tax4, Delivery_Tax5, Delivery_Tax1Base1, Delivery_Tax2Base1, ".
						 " Delivery_Tax3Base1, Delivery_Tax4Base1, Delivery_Tax5Base1, Delivery_Tax1Base2, Delivery_Tax2Base2, Delivery_Tax3Base2, Delivery_Tax4Base2, Delivery_Tax5Base2, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, ".
						 " Delivery_Acctax4, Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
						 " Delivery_CREDITACC, Delivery_TotalTax, Delivery_TotalTaxBase1, Delivery_TotalTaxBase2, Delivery_SorderReferences, Deliveries.Detail_Code, Delivery_TaxableTTC, Delivery_DiscountTTC, Delivery_Reference, Delivery_VatChkbx, Deliveries.User_Account, ".
						 " '".$HTTP_SESSION_VARS['useraccount']."' ".
						 " From Deliveries Inner Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
						 " Where Delivery_ID = '".$SelectedDeliveryID."' ".
						 " And Deliveries.Journal_Type = 'DI' ";
			} else {
				$query = " INSERT INTO temp_deliveries (Delivery_ID, Delivery_Reference, Sorder_reference, Delivery_Date, JournalDt_ValueDate, Delivery_Remark, Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Salesman_Code, ".
						 " Currency_Code, Project_Code, Costcent_code, Delivery_Posted, Delivery_Edit, Delivery_Confirmed, Delivery_Mode, Journal_Type, Journal_Id, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, ".
						 " Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
						 " Delivery_CREDITACC, Delivery_BelongsToGroup, Delivery_SorderReferences, Detail_Code, Delivery_ReturnRef, User_Account, Logged_Code) ".
						 " SELECT $vRSaId, Null, Sorder_reference, now(), ADDDATE(now(), ifNull(Clients.Client_PaymentTerms,0)), Delivery_Remark, Deliveries.Client_code, Delivery_ShippedTo, Delivery_Marks, Delivery_ShippedVia, Deliveries.Salesman_Code, ".
						 " Deliveries.Currency_Code, Deliveries.Project_Code, Deliveries.Costcent_code, 0, 0, 0, Delivery_Mode, 'DR', Null, Delivery_Acctax1, Delivery_Acctax2, Delivery_Acctax3, Delivery_Acctax4, ".
						 " Delivery_Acctax5, Delivery_CreditCur, Delivery_CreditAccount, Delivery_TipsAccount, Delivery_VatAccount, Delivery_CreditAccountVat, Delivery_PromotionAcc, Delivery_TransportAccount, Delivery_CREDITACCcur, ".
						 " Delivery_CREDITACC, Delivery_BelongsToGroup, Delivery_SorderReferences, Deliveries.Detail_Code, Delivery_Reference, Deliveries.User_Account, '".$HTTP_SESSION_VARS['useraccount']."' ".
						 " From Deliveries Inner Join Clients on Deliveries.Client_Code = Clients.Ledger_Number ".
						 " Where Delivery_ID = '".$SelectedDeliveryID."' ".
						 " And Deliveries.Journal_Type = 'DI' ";
			}
			
			$result=mysql_query($query,$connection);
			//echo $query."<br>";exit;	
			
			if ($result){
				$RSaId = $vRSaId;
				fcommit();
			}else{
				$vRSaId = "";
				$RSaId  = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}

		
		}
		
		if ($RSaId != ""  && $ErrorExists == 0)
		{
			
			$vRSaId = $RSaId;
			
			$sub_query = " SELECT Currency_Code, Delivery_Date, Client_Code, Project_Code, Costcent_code, ifNull(Delivery_DiscountPer,0), ".
						 " Date_Format(Delivery_Date,'%d/%m/%Y') As DeliveryDate, if(ifNull(Delivery_Total,0) > 0, if(ifNull(Delivery_VAT,0) > 0, 1, 0), 0) As Delivery_chkvat ".
						 " FROM Temp_Deliveries ".
						 " WHERE Delivery_ID = '".$vRSaId."' ";
			$return_result = selectData($connection, $sub_query);
			
			$vRSaDiscountPer = $return_result[5];				   
			if (empty($vRSaDiscountPer)) $vRSaDiscountPer = 0;
			
			$vRSaCurr     = $return_result[0];
			$vRSaDate     = $return_result[6];
			$vRSaVatChkbx = $return_result[7];

			$vRSaDtPrice         = 0;
			$vRSaDtPriceBase1    = 0;
			$vRSaDtPriceBase2    = 0;
			$vRSaDtPriceTTC      = 0;
			$vRSaDtPriceTTCBase1 = 0;
			$vRSaDtPriceTTCBase2 = 0;
			$vRSaDtDiscPer       = 0;
			$vRSaDtDiscAmt       = 0;
			$vRSaDtDiscAmtBase1  = 0;
			$vRSaDtDiscAmtBase2  = 0;
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vRSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vRSaCurr."' )";
			$result = selectData($connection, $query);
			$rate_dt = $result[0];
						
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
			$result = selectData($connection, $query);
			$rate_dt1 = $result[0];
						
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
			$result = selectData($connection, $query);
			$rate_dt2 = $result[0];
			
			$sub_query = " SELECT DeliveryDt_ID, ifNull(DeliveryDt_Quantity,0), ifNull(DeliveryDt_Price,0), ifNull(DeliveryDt_DiscountPer,0) ".
						 " FROM Temp_DeliveryDt ".
						 " WHERE Temp_DeliveryDt.RelatedDt_ID = '".$SelectedDeliveryDtID."' ".
						 " And Temp_DeliveryDt.Journal_Type = 'DR' ";
			$sub_result = selectData($connection, $sub_query);
			//echo $sub_query; exit;
			
			//If Item Not Exists Then Insert Into Temp_DeliveryDt Else Update
			if ($sub_result[0] == '') {
				
				$sub_query3 = " SELECT DeliveryDt.Delivery_ID, ifNull(DeliveryDt.Item_CodePacked, '') ".
							  " FROM DeliveryDt ".
							  " WHERE DeliveryDt.DeliveryDt_Id = '".$SelectedDeliveryDtID."' ".
							  " And DeliveryDt.Journal_Type = 'DI' ";
				$sub_result3 = selectData($connection, $sub_query3);
			
				$sub_query = " SELECT DeliveryDt.DeliveryDt_id, DeliveryDt.Currency_Code, now(), DeliveryDt.Client_Code, DeliveryDt.Project_Code, DeliveryDt.CostCent_Code, DeliveryDt.Warehouse_Code, DeliveryDt.Item_code, ".
							 " DeliveryDt.Item_CodePacked, DeliveryDt.Item_QtyPacked, ifNull(DeliveryDt.DeliveryDt_Quantity,0), ifNull(DeliveryDt.DeliveryDt_Price,0), ifNull(DeliveryDt.DeliveryDt_PriceBase1,0), ifNull(DeliveryDt.DeliveryDt_PriceBase2,0), ".
							 " ifNull(DeliveryDt.DeliveryDt_DiscountPer,0), ifNull(DeliveryDt.Item_Vat,0), ifNull(DeliveryDt.DeliveryDt_PriceTTC,0), ifNull(Deliverydt_priceTTCBase1,0), ifNull(Deliverydt_priceTTCBase2,0), ".
							 " ifNull(Deliverydt_costbase1,0), ifNull(Deliverydt_costbase2,0), DeliveryDt.Item_UnitCoef, DeliveryDt.Item_Unit2Qty, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
							 " Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, ifNull(DeliveryDt.Item_Tax1,0), ifNull(DeliveryDt.Item_Tax2,0), ifNull(DeliveryDt.Item_Tax3,0), ifNull(DeliveryDt.Item_Tax4,0), ifNull(DeliveryDt.Item_Tax5,0), ".
							 " ifNull(DeliveryDt_promotion,0), DeliveryDt.User_Account, Deliveries.Delivery_Reference, ifNull(Deliveries.Delivery_DiscountPer,0), Items.Item_WithSerialNo ".
							 " FROM DeliveryDt Inner Join Deliveries on DeliveryDt.Delivery_ID = Deliveries.Delivery_ID ".
							 " Inner Join Items on DeliveryDt.Item_Code = Items.Item_Code ";
				
				//If Not A Pack	Item
				if ($sub_result3[1] == '')	$sub_query = $sub_query." WHERE DeliveryDt.DeliveryDt_Id = '".$SelectedDeliveryDtID."' And DeliveryDt.Journal_Type = 'DI' ";
				else $sub_query = $sub_query." WHERE DeliveryDt.Delivery_Id = '".$sub_result3[0]."' And DeliveryDt.Item_CodePacked = '".$sub_result3[1]."'  And DeliveryDt.Journal_Type = 'DI' ";
				
				//echo $sub_query; exit;
				//$sub_row = selectData($connection, $sub_query);
				$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
				while($sub_row=mysql_fetch_array($sub_result)){
				
					$vRSaDtQty           = 1;	
					
					//If Case Pack Item And The Item Is Not The One Being Scanned And Item WithSerial True Then Set The Qty To Zero
					if ($sub_row[8] != '' && !(empty($sub_row[8])) && $sub_row[0] != $SelectedDeliveryDtID && $sub_row[39] == 1)
						$vRSaDtQty = 0;
					
					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					if ($Module_DoubleUnit == 1) {
						$vItemUnitCoef = $sub_row[21];
						$vItemUnit2Qty = $vItemUnitCoef * $vRSaDtQty;
					}
					
					if ($Module_Delivery == 0) {
						$vRSaDtPrice         = $sub_row[11];
						$vRSaDtPriceBase1    = $sub_row[12];
						$vRSaDtPriceBase2    = $sub_row[13];
						$vRSaDtPriceTTC      = $sub_row[16];
						$vRSaDtPriceTTCBase1 = $sub_row[17];
						$vRSaDtPriceTTCBase2 = $sub_row[18];
				
								
						if ($sub_row[1] != $vRSaCurr) {
							$vRSaDtPrice    = ConvertCurrency($sub_row[1], $vRSaCurr, insertMySQLDate($vRSaDate), $vRSaDtPrice, $connection);
							$vRSaDtPriceTTC = ConvertCurrency($sub_row[1], $vRSaCurr, insertMySQLDate($vRSaDate), $vRSaDtPriceTTC, $connection);
							$vRSaDtDiscAmt  = ConvertCurrency($sub_row[1], $vRSaCurr, insertMySQLDate($vRSaDate), $vRSaDtDiscAmt, $connection);
									
							$vRSaDtPriceBase1    = ($vRSaDtPrice*$rate_dt)/$rate_dt1;
							$vRSaDtPriceBase2    = ($vRSaDtPrice*$rate_dt)/$rate_dt2;
							$vRSaDtPriceTTCBase1 = ($vRSaDtPriceTTC*$rate_dt)/$rate_dt1;
							$vRSaDtPriceTTCBase2 = ($vRSaDtPriceTTC*$rate_dt)/$rate_dt2;
								
						}
							
						$vRSaDtDiscPer = $sub_row[14];
							
						//If Item Discount Is Zero And The Invoice Has Discount
						if ($vRSaDtDiscPer == 0 && $sub_row[38] > 0)
							$vRSaDtDiscPer = $sub_row[38];
						
					
						// Calculation For Detail Discount Amount
						$vRSaDtDiscAmt       = ((($vRSaDtPrice*$vRSaDtQty) - ($vRSaDtPrice*$vRSaDtQty*$vRSaDtDiscPer/100))*$vRSaDiscountPer)/100;
						$vRSaDtDiscAmtBase1  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt1;
						$vRSaDtDiscAmtBase2  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt2;
					
					}		
						
					fbegin();
					$vRSaDtId = get_nextsequence('deliverydt_id','',$connection);	
					fcommit();
						
					fbegin();
					
					if ($Module_Delivery == 0) {					
						$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, Item_QtyPacked, ". 
									  " DeliveryDt_Quantity, DeliveryDt_Price, DeliveryDt_PriceBase1, DeliveryDt_PriceBase2, DeliveryDt_DiscountPer, DeliveryDt_DiscountAmount, DeliveryDt_DiscountBase1, DeliveryDt_DiscountBase2, Item_Vat, ".
									  " DeliveryDt_PriceTTC, Deliverydt_priceTTCBase1, Deliverydt_priceTTCBase2, Deliverydt_costbase1, Deliverydt_costbase2, Item_UnitCoef, Item_Unit2Qty, DeliveryDt_Remark, Deliverydt_DirectStkDbt, ".
									  " Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Deliverydt_posted, ".
									  " Deliverydt_OldData, Deliverydt_promotion, Journal_Type, Related_Ref, User_Account, Logged_Code ) ".
									  " VALUES ( $vRSaDtId, $vRSaId, '".$sub_row[0]."', '".$return_result[0]."', '".$return_result[1]."', '".$return_result[2]."', '".$return_result[3]."', '".$return_result[4]."', '".$sub_row[6]."', '".$sub_row[7]."', ". 
									  " if('".$sub_row[8]."'='', Null, '".$sub_row[8]."'), '".$sub_row[9]."', $vRSaDtQty, $vRSaDtPrice, $vRSaDtPriceBase1, $vRSaDtPriceBase2, $vRSaDtDiscPer, $vRSaDtDiscAmt, $vRSaDtDiscAmtBase1, $vRSaDtDiscAmtBase2, '".$sub_row[15]."', ".
									  " $vRSaDtPriceTTC, $vRSaDtPriceTTCBase1, $vRSaDtPriceTTCBase2, '".$sub_row[19]."', '".$sub_row[20]."', '".$vItemUnitCoef."', '".$vItemUnit2Qty."', '".$sub_row[23]."', '".$sub_row[24]."', '".$sub_row[25]."', '".$sub_row[26]."', ".
									  " '".$sub_row[27]."', '".$sub_row[28]."', '".$sub_row[29]."', '".$sub_row[30]."', '".$sub_row[31]."', '".$sub_row[32]."', '".$sub_row[33]."', '".$sub_row[34]."', 0, 0, '".$sub_row[35]."', 'DR', '".$sub_row[37]."', ".
									  " '".$HTTP_SESSION_VARS['useraccount']."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
					} else {
						$sub_query1 = " INSERT INTO temp_deliverydt (DeliveryDt_id, Delivery_id, RelatedDt_Id, Currency_Code, Delivery_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, Item_QtyPacked, ". 
									  " DeliveryDt_Quantity, Item_Vat, Deliverydt_costbase1, Deliverydt_costbase2, Item_UnitCoef, Item_Unit2Qty, DeliveryDt_Remark, Deliverydt_DirectStkDbt, Deliverydt_DirectStkCrd, Deliverydt_DirectStkCur, ".
									  " Deliverydt_discountacc, Deliverydt_ItemAccount, DeliveryDt_PromoAcc, Deliverydt_posted, Deliverydt_OldData, Deliverydt_promotion, Journal_Type, Related_Ref, User_Account, Logged_Code ) ".
									  " VALUES ( $vRSaDtId, $vRSaId, '".$sub_row[0]."', '".$return_result[0]."', '".$return_result[1]."', '".$return_result[2]."', '".$return_result[3]."', '".$return_result[4]."', '".$sub_row[6]."', '".$sub_row[7]."', ". 
									  " if('".$sub_row[8]."'='', Null, '".$sub_row[8]."'), '".$sub_row[9]."', $vRSaDtQty, '".$sub_row[15]."', '".$sub_row[19]."', '".$sub_row[20]."', '".$vItemUnitCoef."', '".$vItemUnit2Qty."', '".$sub_row[23]."', '".$sub_row[24]."', '".$sub_row[25]."', ".
									  " '".$sub_row[26]."', '".$sub_row[27]."', '".$sub_row[28]."', '".$sub_row[29]."', 0, 0, '".$sub_row[35]."', 'DR', '".$sub_row[37]."', '".$HTTP_SESSION_VARS['useraccount']."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
					}
					
					//echo $sub_query1; exit;	
					$sub_result1=mysql_query($sub_query1,$connection);
				}
				
			} else {
			
				$vRSaDtId      = $sub_result[0];
				$vRSaDtQty     = $sub_result[1] + 1;
				$vRSaDtPrice   = $sub_result[2];
				$vRSaDtDiscPer = $sub_result[3];

				if ($Module_Delivery == 0) {
					// Calculation For Detail Discount Amount
					$vRSaDtDiscAmt       = ((($vRSaDtPrice*$vRSaDtQty) - ($vRSaDtPrice*$vRSaDtQty*$vRSaDtDiscPer/100))*$vRSaDiscountPer)/100;
					$vRSaDtDiscAmtBase1  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt1;
					$vRSaDtDiscAmtBase2  = ($vRSaDtDiscAmt*$rate_dt)/$rate_dt2;
					
					$sub_query1 = " UPDATE temp_deliverydt SET ".
								  " DeliveryDt_Quantity = (ifNull(DeliveryDt_Quantity,0) + 1), ";
								  
					if ($Module_DoubleUnit == 1) {
						$sub_query1 = $sub_query1." Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)), ";
					}			  
					$sub_query1 = $sub_query1." DeliveryDt_DiscountAmount = $vRSaDtDiscAmt, ".
											  " DeliveryDt_DiscountBase1  = $vRSaDtDiscAmtBase1, ".
											  " DeliveryDt_DiscountBase2  = $vRSaDtDiscAmtBase2  ".
											  " WHERE DeliveryDt_ID = '".$vRSaDtId."'";
				} else {
					$sub_query1 = " UPDATE temp_deliverydt SET ".
								  " DeliveryDt_Quantity = (ifNull(DeliveryDt_Quantity,0) + 1) ";
								  
					if ($Module_DoubleUnit == 1) {
						$sub_query1 = $sub_query1.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
					}			  
					$sub_query1 = $sub_query1." WHERE DeliveryDt_ID = '".$vRSaDtId."'";
				}
				
				//echo $sub_query1; exit;				  
				$sub_result1=mysql_query($sub_query1,$connection);
			}
			
			
			if ($sub_result1){

				fbegin();
				$vSerId = get_nextsequence('Serial_Id','',$connection);	
				fcommit();
						
				$sub_query2 = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
							  " VALUES ( ".$vSerId.", 'DR', $vRSaDtId, $vRSaDtId, '".$SelectedItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold, '".$lstWarehouse."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
								 
				//echo $sub_query2; exit;										 
				$sub_result2 = mysql_query($sub_query2,$connection);
					
				fcommit();
			}else{
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
			
		} //End if ($RSaId != "" )
		
		
	} //End Case IsAvailable = True
} //End Case Insert

else if ($Mode == 'delete' && $SerialId != '') {
	
	$ErrorExists = 0;
	$IsAvailable = 1;
	
	$query = " SELECT ifNull(SerialNo_Used, 0) As SerialNo_Used, ifNull(PurchaseDt_ID, DeliveryDt_ID)  from temp_purchasesserialno ".
	         " WHERE Serial_ID = ".$SerialId;
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	$result = selectData($connection, $query);
	$SerialNoUsed        = $result[0];
	$SerialDeliveryDt_Id = $result[1];
	
	if ($SerialNoUsed == 0) {
		fbegin();
		
		$query = " DELETE from temp_purchasesserialno ".
				 " WHERE Serial_ID = ".$SerialId.
				 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ".
				 " AND ifNull(SerialNo_Used, 0) = 0  ";
		
		$result=mysql_query($query,$connection);
			
		if ($result){
			$message = "Delete serial no (".$ItemSerialNo.") done successfully.";
			
			$query = " UPDATE temp_deliverydt SET ".
					 " DeliveryDt_Quantity =  (ifNull(DeliveryDt_Quantity,0) - 1) ";
					 
			if ($Module_DoubleUnit == 1) {
				$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
			}		 
			$query = $query." WHERE DeliveryDt_id = '".$SerialDeliveryDt_Id."' ";
			//echo $query."<br>";exit;				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 	
			
			
			fcommit();
		}else{
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}			
	} 
	else {	
		$ErrorExists = 1;
		$message  = "Delete not allowed, Serial No ".$ItemSerialNo." is used. "; 
	}	
}

// Update Amount Columns In Delivery Table
if ($Module_Delivery == 0 && $ErrorExists == 0 && $IsAvailable == 1 && $RSaId != '') {

	$vSaDtTotal = 0;
	$vItemVat   = 0;
	$vSaVatChk  = 0;
	
	$vSaTaxable        = 0;
	$vSaTaxableTTC     = 0;
	$vSaNoneTaxable    = 0;
	$vSaGrossTotal     = 0;
	$vSaDiscountAmt    = 0;
	$vSaDiscountPer    = 0;
	$vSaDiscountAmtTTC = 0;
	$vSaTransportAmt   = 0;
	$vSaTransportAmtB1 = 0;
	$vSaTransportAmtB2 = 0;
	$vSaVat      = 0;
	$vSaVatBase1 = 0;
	$vSaVatBase2 = 0;
		
	$vSaTax1 = 0;
	$vSaTax2 = 0;
	$vSaTax3 = 0;
	$vSaTax4 = 0;
	$vSaTax5 = 0;
	$vSaTax1B1 = 0;
	$vSaTax2B1 = 0;
	$vSaTax3B1 = 0;
	$vSaTax4B1 = 0;
	$vSaTax5B1 = 0;
	$vSaTax1B2 = 0;
	$vSaTax2B2 = 0;
	$vSaTax3B2 = 0;
	$vSaTax4B2 = 0;
	$vSaTax5B2 = 0;

	
	
	$sub_query = " Select Temp_Deliveries.Currency_code, ifNull(Delivery_DiscountPer,0), ".
	             " ifNull(Delivery_VatChkbx,0) As Delivery_VatChkbx  ".
				 " From Temp_Deliveries ".
				 " Left Join Clients on Temp_Deliveries.Client_code = Clients.Ledger_Number ".
				 " Where Delivery_ID = '".$RSaId."'";
	$sub_result = selectData($connection, $sub_query);
	
	$vSaCurr        = $sub_result[0];
	$vSaDiscountPer = $sub_result[1];
	$vSaVatChk      = $sub_result[2];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vSaCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vSaCurr."' )";
	$result = selectData($connection, $query);
	$vRate = $result[0];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base1."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base1."' )";
	$result = selectData($connection, $query);
	$vRate1 = $result[0];
			
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$base2."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$base2."' )";
	$result = selectData($connection, $query);
	$vRate2 = $result[0];
	
	
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0))-((ifNull(DeliveryDt_Quantity,0)*ifNull(DeliveryDt_Price,0)*ifNull(DeliveryDt_DiscountPer,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " DeliveryDt_Quantity, ifNull(DeliveryDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_DeliveryDt ".
				 " Where Delivery_ID = '".$RSaId."'";
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSaDtTotal = $sub_rows[1];
		$vItemVat   = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vSaTaxable     = $vSaTaxable     + ($vSaDtTotal*$tax_flag);
		$vSaNoneTaxable = $vSaNoneTaxable + ($vSaDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if ($vSaVatChk == 1 && $vSaDtTotal > 0)
			$vSaVat = $vSaVat + (($vSaDtTotal - $sub_rows[4])*$vItemVat/100);
		
		if ($Module_AdditionalTaxes == 1 && $vSaDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSaTax1 = $vSaTax1 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSaTax2 = $vSaTax2 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSaTax3 = $vSaTax3 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSaTax4 = $vSaTax4 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSaTax5 = $vSaTax5 + (($vSaDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vSaGrossTotal = $vSaTaxable + $vSaNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($vSaDiscountPer > 0)
		$vSaDiscountAmt = (($vSaGrossTotal * $vSaDiscountPer) / 100);
			
	if ($SalesTTC == 1)	$vSaDiscountAmtTTC = $vSaDiscountAmt;	

		
			
	$vSaTaxableTTC = $vSaTaxable + $vSaVat;
					
	$vSaNetTotal         = $vSaGrossTotal + $vSaVat - $vSaDiscountAmt;
	$vSaTaxableBase1     = ($vSaTaxable*$vRate)/$vRate1;
	$vSaTaxableBase2     = ($vSaTaxable*$vRate)/$vRate2;
	$vSaNoneTaxableBase1 = ($vSaNoneTaxable*$vRate)/$vRate1;
	$vSaNoneTaxableBase2 = ($vSaNoneTaxable*$vRate)/$vRate2;
	$vSaDiscountAmtBase1 = ($vSaDiscountAmt*$vRate)/$vRate1;
	$vSaDiscountAmtBase2 = ($vSaDiscountAmt*$vRate)/$vRate2;
	$vSaGrossTotalBase1  = ($vSaGrossTotal*$vRate)/$vRate1;
	$vSaGrossTotalBase2  = ($vSaGrossTotal*$vRate)/$vRate2;
	$vSaVatBase1 		 = ($vSaVat*$vRate)/$vRate1;
	$vSaVatBase2 		 = ($vSaVat*$vRate)/$vRate2;
					

	$vSaTax1B1  = ($vSaTax1*$vRate)/$vRate1;
	$vSaTax1B2  = ($vSaTax1*$vRate)/$vRate2;		
	$vSaTax2B1  = ($vSaTax2*$vRate)/$vRate1;
	$vSaTax2B2  = ($vSaTax2*$vRate)/$vRate2;		
	$vSaTax3B1  = ($vSaTax3*$vRate)/$vRate1;
	$vSaTax3B2  = ($vSaTax3*$vRate)/$vRate2;		
	$vSaTax4B1  = ($vSaTax4*$vRate)/$vRate1;
	$vSaTax4B2  = ($vSaTax4*$vRate)/$vRate2;		
	$vSaTax5B1  = ($vSaTax5*$vRate)/$vRate1;
	$vSaTax5B2  = ($vSaTax5*$vRate)/$vRate2;	
	
	fbegin();
	
	$sub_query1 = " UPDATE temp_deliveries SET ".
				  " Delivery_Taxable = $vSaTaxable, Delivery_TaxableBase1 = $vSaTaxableBase1, Delivery_TaxableBase2 = $vSaTaxableBase2, ".
				  " Delivery_NoneTaxable = $vSaNoneTaxable, Delivery_NoneTaxableBase1 = $vSaNoneTaxableBase1, Delivery_NoneTaxableBase2 = $vSaNoneTaxableBase2, ".
				  " Delivery_DiscountAmount = $vSaDiscountAmt, Delivery_DiscountBase1 = $vSaDiscountAmtBase1, Delivery_DiscountBase2 = $vSaDiscountAmtBase2, ".
				  " Delivery_VAT = $vSaVat, Delivery_VATBase1 = $vSaVatBase1, Delivery_VATBase2 = $vSaVatBase2, ".
				  " Delivery_Total = $vSaGrossTotal, Delivery_TotalBase1 = $vSaGrossTotalBase1, Delivery_TotalBase2 = $vSaGrossTotalBase2, ".
				  " Delivery_DiscountTTC = $vSaDiscountAmtTTC, Delivery_TaxableTTC = $vSaTaxableTTC,  ".
				  " Delivery_Tax1 = $vSaTax1, Delivery_Tax1Base1 = $vSaTax1B1, Delivery_Tax1Base2 = $vSaTax1B2,  ".
				  " Delivery_Tax2 = $vSaTax2, Delivery_Tax2Base1 = $vSaTax2B1, Delivery_Tax2Base2 = $vSaTax2B2,  ".
				  " Delivery_Tax3 = $vSaTax3, Delivery_Tax3Base1 = $vSaTax3B1, Delivery_Tax3Base2 = $vSaTax3B2,  ".
				  " Delivery_Tax4 = $vSaTax4, Delivery_Tax4Base1 = $vSaTax4B1, Delivery_Tax4Base2 = $vSaTax4B2,  ".
				  " Delivery_Tax5 = $vSaTax5, Delivery_Tax5Base1 = $vSaTax5B1, Delivery_Tax5Base2 = $vSaTax5B2  ".
				  " WHERE Delivery_ID = '".$RSaId."'";
		
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		frollback();
	}
				
}

$message          = ereg_replace(' ','%20',$message);
$PSaRemark        = ereg_replace(' ','%20',$PSaRemark);

$lstWarehouse     = ereg_replace('#','%23',$lstWarehouse);
$lstWarehouse     = ereg_replace('&','%26',$lstWarehouse);

header ( "Location: ./Form_ReturnDeliveryAddSerial.php?lstWarehouse=".$lstWarehouse."&PRSaId=".$RSaId."&perpage=".$PerPage."&message=".$message );

function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}

function ConvertCurrency($FromCurr, $ToCurr, $FromDate, $Amount, $connection)
{
	$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', 0, 0, '', '', ifNull($Amount,0)),0) From Dual ";
	$result = selectData($connection, $query);
	//echo $query;
	Return	$result[0];

}

print <<<HERE
</form>
</body>

HERE;

?>