<?php

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


include("config.inc.php");
include("Functions_Purchase.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_negativeQty,0) As Login_negativeQty, 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 ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, 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 ".
             " 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' />
<input type='hidden' name='SerialId' id='SerialId' value='$SerialId' />
<input type='hidden' name='AdjId' id='AdjId' value='$AdjId' />
<input type='hidden' name='PerPage' id='PerPage' value='$PerPage' />
<input type='hidden' name='Mode' id='Mode' value='$Mode' />		    
HERE;


if (!isset($PAdjCurr)) $PAdjCurr = $base1;

if ($AdjustType == 'O')      { $JourType = 'AR'; }
else if ($AdjustType == 'I') { $JourType = 'AI'; }
else if ($AdjustType == 'A') { $JourType = 'AI'; } 


$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PAdjCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PAdjCurr."' )";
$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];

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 SerialNo_Code =  '".$ItemSerialNo."' ".
			" And Journal_Type in ('PI','DR','TR','AI','PD')";
			  
	$result = selectData($connection, $query);
	$SerialNoExists = $result[0];
	
	$IsAvailable = 1;
	$ErrorExists = 0;
	$SelectedSerialID = 0;
	$SelectedSerialQty     = 0;
	$SelectedSerialQtySold = 0;
	$SelectedItemCode      = '';
	
	if ($SerialNoExists != '') {
		if ($lstWarehouse != '' && isset($lstWarehouse)) {
		
			$sub_query= " Select *  ".
						" From temp_purchasesserialno ".
						" where SerialNo_Code =  '".$ItemSerialNo."' ".
						" And Journal_Type in ('AR')";
			 //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 RelatedSerial_Id As Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) - 1 As SerialNo_QuantitySold, ".
							" purchasesserialno.Item_Code As Item_Code, 1 As OrderColumn ".
							" From purchasesserialno ".
							" Inner Join AdjustmentDt on Purchasesserialno.PurchaseDt_ID = AdjustmentDt.AdjustmentDt_ID ".
							" Where AdjustmentDt.Adjustment_ID = '".$AdjId."' ".
							" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Purchasesserialno.Warehouse_Code =  '".$lstWarehouse."' ".
							" And Purchasesserialno.Journal_Type = 'AR' ".
							" Union ".
							" Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, Item_Code, 2 As OrderColumn  ".
							" From purchasesserialno ".
							" where SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Warehouse_Code =  '".$lstWarehouse."' ".
							" And Journal_Type in ('PI','DR','TR','AI','PD') ".
							" Order by OrderColumn ";
							
							
				//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)
					{
						$sub_query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0), Item_Code  ".
									" From purchasesserialno ".
									" where SerialNo_Code =  '".$ItemSerialNo."' ".
									" And Warehouse_Code =  '".$lstWarehouse."' ".
									" And ifNull(SerialNo_Used,0) = 0 ".
									" And Journal_Type in ('PI','DR','TR','AI','PD')";
						$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];
							$IsAvailable = 1;
						}	
					
					} else {
						$SelectedSerialID      = $sub_row[0];
						$SelectedSerialQty     = $sub_row[3];
						$SelectedSerialQtySold = $sub_row[4];
						$SelectedItemCode      = $sub_row[5];
						$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)
	{
		$vAdjId   = '';
		$vAdjDtId = '';
		$vSerId   = '';
			
		$ErrorExists = 0;
		
		
		$vAdjDate         = $PAdjDate;
		$vAdjCurr         = $PAdjCurr;
		$vAdjProjectCode  = $PAdjProjectCode;
		$vAdjCostCentCode = $PAdjCostCentCode;
		$vAdjIsInvoice    = $PAdjIsInvoice;
		$vAdjInvDebit     = $PAdjInvDebit;
		$vAdjInvCredit    = $PAdjInvCredit;
		$vAdjRequestBy    = $PAdjRequestBy;
		$vAdjRemark       = $PAdjRemark;
		$vAdjEntryType    = $PAdjEntryType;
		

		if (!isset($vAdjCurr))
		   $vAdjCurr = $base1;
		if (empty($vAdjIsInvoice))
			$vAdjIsInvoice = 0;   
				   
		   
		if (empty($vAdjCostCentCode))	$CostCentCode = 'Null';
		else	$CostCentCode = "'".$vAdjCostCentCode."'";
				
		if (empty($vAdjProjectCode))	$ProjectCode = 'Null';
		else	$ProjectCode = "'".$vAdjProjectCode."'";  

		if (empty($vAdjInvDebit))	$AdjInvDebit = 'Null';
		else	$AdjInvDebit = "'".$vAdjInvDebit."'";   	
		if (empty($vAdjInvCredit))	$AdjInvCredit = 'Null';
		else	$AdjInvCredit = "'".$vAdjInvCredit."'";
	
		
	
		//Check For Project and Costcenter Codes Before Insert
		if ($vAdjCostCentCode != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent ".
						 " Where Costcent_code = '".$vAdjCostCentCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		if ($vAdjProjectCode != '') {
			$sub_query = " Select Count(Project_Code) From Project ".
						 " Where Project_Code = '".$vAdjProjectCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		if ($vAdjInvDebit != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger ".
						 " Where Ledger_Number = '".$vAdjInvDebit."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		if ($vAdjInvCredit != '') {
			$sub_query = " Select Count(Ledger_Number) From Ledger ".
						 " Where Ledger_Number = '".$vAdjInvCredit."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) $ErrorExists = 1;
		}
		
		if ($ErrorExists == 1)
			$message = 'Insert not allowed. Please check for Project/Costcenter/Debit Acc/Credit Acc.';
		
		
				
		//Insert Master Table
		if ($AdjId == "" && $ErrorExists == 0){
		
			fbegin();	
			$vAdjId = get_nextsequence('Adjustment_id','',$connection);
			fcommit();
				
			
			fbegin();
			$query = " INSERT INTO temp_adjustment (Adjustment_ID, Adjustment_Reference, Adjustment_Date, Adjustment_Remak, Currency_Code, Project_Code, Costcent_code, ".
					 " Adjustment_RequestBy, Adjustment_Type, Adjustment_EntryType, Adjustment_isInvoice, InvDebitAccount, InvCreditAccount, Adjustment_Amount, ".
					 " Adjustment_AmountBase1, Adjustment_AmountBase2, Journal_Id, Adjustment_BelongsToGroup, Adjustment_Posted, Entry_Type, User_Account, Logged_Code ) ".
					 " VALUES ( ".$vAdjId.", Null, '".insertMySQLDate($vAdjDate)."', '".ereg_replace("'", "\'", trim($vAdjRemark))."', '".$vAdjCurr."', ".
					 "          $ProjectCode, $CostCentCode, '".ereg_replace("'", "\'", trim($vAdjRequestBy))."', 'AD', '".$AdjustType."', $vAdjIsInvoice, ".
					 "          $AdjInvDebit, $AdjInvCredit, 0, 0, 0, Null, $FI_BelongsToGrp, 0, '".$vAdjEntryType."', '".$HTTP_SESSION_VARS['useraccount']."', ".
					 "          '".$HTTP_SESSION_VARS['useraccount']."' )";
							 
			
			$result=mysql_query($query,$connection);
			//echo $query."<br>";exit;	
			
			if ($result){
				$AdjId = $vAdjId;
				fcommit();
			}else{
				$AdjId  = "";
				$vAdjId = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
		
		
		}
		
		if ($AdjId != ""  && $ErrorExists == 0)
		{
			$QtyExistExceeded   = 0;
			
			$vAdjDtQty        = 0;
			$vAdjDtPrice      = 0;
			$vAdjDtPriceBase1 = 0;
			$vAdjDtPriceBase2 = 0;
				
			$vAdjDtDirectStkDbt = '';
			$vAdjDtDirectStkCrd = '';
			$vAdjDtDirectStkCur = '';
			
			$vAdjDtItemCode = $SelectedItemCode;
			$vAdjDtQty      = $SelectedSerialQty;
			
			$query = " UPDATE Temp_Adjustment SET ".
					 " Adjustment_Date = '".insertMySQLDate($vAdjDate)."' , ".
					 " Adjustment_Remak = '".ereg_replace("'", "\'", trim($vAdjRemark))."', ".
					 " Adjustment_isInvoice = $vAdjIsInvoice, InvDebitAccount = $AdjInvDebit, InvCreditAccount = $AdjInvCredit, ".
					 " Currency_Code = '".$vAdjCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode ".
					 " WHERE Adjustment_ID = $AdjId ";		 
			//echo $query."<br>";exit;				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 	
				
				
			$sub_query = " SELECT Item_Vat, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), Currency_Code, ".
						 " ifNull(Item_CostMethod,0), ifNull(Item_NonStock,0), ifNull(Item_Unit, 0) ".
						 " FROM Items WHERE Item_Code = '".$vAdjDtItemCode."'";
			$sub_result = selectData($connection, $sub_query);
			$ItemVat 	     = $sub_result[0];
			$ItemGroupCode   = $sub_result[1];
			$ItemProd        = $sub_result[2];
			$ItemTTCInc      = $sub_result[3];
			$ItemCurr		 = $sub_result[4];
			$ItemCostMethod  = $sub_result[5];
			$ItemNonStock    = $sub_result[6];
			$ItemUnit   	 = $sub_result[7];
			
			//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
			if ($ItemNonStock == 0 && $AdjustType == 'O') {
				$sub_query  = " Select QtyExistsWSorder('".$vAdjDtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($vAdjDate)."', 0, '".$JourType."', '', '') QtyExists From Dual ";
				$sub_result = selectData($connection, $sub_query);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result[0];
				
				$sub_query1 = " Select ifNull(Sum(ifNull(AdjustmentDt_Quantity,0)),0) FROM Temp_AdjustmentDt ".
							  " Where Item_code = '".$vAdjDtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $AdjId  ".
							  " And AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $AdjId) ";
				$sub_result1 = selectData($connection, $sub_query1);
				if (empty($sub_result1[0])) $sub_result1[0] = 0;
				
				$vItemQtyExists = $vItemQtyExists + $sub_result1[0];
				
					
				if (abs($vAdjDtQty) > $vItemQtyExists && abs($vAdjDtQty) > 0)
					$QtyExistExceeded = 1;
			}

			if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) 
			{						 
				$sub_query = " Select AdjustmentDt_ID, Item_Code, Abs(ifNull(AdjustmentDt_Quantity,0)) ".
							 " From Temp_AdjustmentDt ".
							 " Where Item_Code = '".$vAdjDtItemCode."' ".
							 " And Adjustment_ID = '".$AdjId."'";
				$sub_result = selectData($connection, $sub_query);
				
				$vAdjDtId = $sub_result[0];
				
				if ($vAdjDtId == "" )
				{
					
					
					
					$sub_query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur ".
								 " FROM transactionsetup ".
								 " WHERE Journal_type = 'AD' ".
								 " AND Group_code = '".$ItemGroupCode."'  ";
									 
					$sub_result = selectData($connection, $sub_query);
							
					$vTranStpDirectStkDbt = $sub_result[0];
					$vTranStpDirectStkCrd = $sub_result[1];
					$vTranStpDirectStkCur = $sub_result[2];
							
					$vAdjDtDirectStkDbt = $vTranStpDirectStkDbt;
					$vAdjDtDirectStkCrd = $vTranStpDirectStkCrd;
					$vAdjDtDirectStkCur = $vTranStpDirectStkCur;
					

					$vAdjDtQty        = $vAdjDtQty * (-1);
					$vAdjDtPrice      = Get_CostPrice($vAdjDtItemCode, $ItemCurr, $ItemCostMethod, $vAdjDate, $vAdjCurr, $base1, $base2, $connection);
					$vAdjDtPriceBase1 = ($vAdjDtPrice*$rate_dt)/$rate_dt1;
					$vAdjDtPriceBase2 = ($vAdjDtPrice*$rate_dt)/$rate_dt2;
					
					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					if ($Module_DoubleUnit == 1) {
						$vItemUnitCoef = $ItemUnit;
						$vItemUnit2Qty = $vItemUnitCoef * $vAdjDtQty;
					}
					
									
					fbegin();
					$vAdjDtId = get_nextsequence('AdjustmentDt_id','',$connection);
					fcommit();			
						 
					fbegin();	 
					$query = " INSERT INTO temp_adjustmentdt (AdjustmentDt_ID, Adjustment_ID, Currency_Code, Adjustment_Date, Project_Code, CostCent_Code, Warehouse_Code, ".
							 " Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentDt_Quantity, AdjustmentDt_Price, AdjustmentDt_PriceBase1, AdjustmentDt_PriceBase2, ".
							 " AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty, Journal_Type, AdjustmentDt_DirectStkDbt, AdjustmentDt_DirectStkCrd, AdjustmentDt_DirectStkCur, ".
							 " AdjustmentDt_Posted, Item_UnitCoef, Item_Unit2Qty, Logged_Code ) ".
							 " VALUES ( ".$vAdjDtId.", ".$AdjId.", '".$vAdjCurr."', '".insertMySQLDate($vAdjDate)."', $ProjectCode, $CostCentCode, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
							 "          '".$vAdjDtItemCode."', Null, 0, $vAdjDtQty, $vAdjDtPrice, $vAdjDtPriceBase1, $vAdjDtPriceBase2, 0, 0, '".$JourType."', '".$vAdjDtDirectStkDbt."', ".
							 "          '".$vAdjDtDirectStkCrd."', '".$vAdjDtDirectStkCur."', 0, $vItemUnitCoef, $vItemUnit2Qty, '".$HTTP_SESSION_VARS['useraccount']."' ) ";
					
					$result=mysql_query($query,$connection);
					
					if ($result){
						fbegin();
						$vSerId = get_nextsequence('Serial_Id','',$connection);	
						fcommit();
						
						$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, AdjustmentDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
								 " VALUES ( ".$vSerId.", 'AR', $vAdjDtId, $vAdjDtId, '".$vAdjDtItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$lstWarehouse."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
													 
						$result=mysql_query($query,$connection);
										
						if ($result){
							$message = "Serial no (".$ItemSerialNo.") inserted successfully.";
							fcommit();
						} else {
							$ErrorExists = 1;
							$message  = mysql_error(); 
							frollback();
						}
						
					} else {
						$ErrorExists = 1;
						$message  = mysql_error(); 
						frollback();
					}
					
					
				
				} 
				else {
					$vAdjDtItemCode = $sub_result[1];
					$vAdjDtQty      = $sub_result[2];
					$vAdjDtQty      = $vAdjDtQty + 1; 
					$vAdjDtQty      = $vAdjDtQty * (-1);
				
					fbegin();
					$vSerId = get_nextsequence('Serial_Id','',$connection);	
					fcommit();
					
					
					
					fbegin();
					$query = " UPDATE temp_adjustmentdt SET ".
							 " AdjustmentDt_Quantity =  (ifNull(AdjustmentDt_Quantity,0) - 1) ";
							 
					if ($Module_DoubleUnit == 1) {
						$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(AdjustmentDt_Quantity,0)) ";
					}		 
					$query = $query." WHERE AdjustmentDt_ID = '".$vAdjDtId."' ";
						 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
						
					if ($result){
						$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, AdjustmentDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
								 " VALUES ( ".$vSerId.", 'AR', $vAdjDtId, $vAdjDtId, '".$vAdjDtItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$lstWarehouse."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
														 
						$result=mysql_query($query,$connection);
											
						if ($result){
							$message = "Serial no (".$ItemSerialNo.") inserted successfully.";
							fcommit();
						} else {
							$ErrorExists = 1;
							$message  = mysql_error(); 
							frollback();
						}
							
					} else {
						$ErrorExists = 1;
						$message  = mysql_error(); 
						frollback();
					}
					
				}
			
			}
			else {
				$ErrorExists = 1;
				$message  = "Insert not allowed, Qty[".abs($vAdjDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vAdjDtItemCode.")"; 
			}

		
			
		} //End if ($AdjId != "" )
		
		
	} //End Case IsAvailable = True
} //End Case Insert

if ($Mode == 'delete' && $SerialId != '') {
	
	$ErrorExists = 0;
	$IsAvailable = 1;
	
	$query = " SELECT ifNull(SerialNo_Used, 0) As SerialNo_Used, ifNull(PurchaseDt_ID, AdjustmentDt_ID)  from temp_purchasesserialno ".
	         " WHERE Serial_ID = ".$SerialId;
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	$result = selectData($connection, $query);
	$SerialNoUsed   = $result[0];
	$SerialAdjDt_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_AdjustmentDt SET ".
					 " AdjustmentDt_Quantity =  (ifNull(AdjustmentDt_Quantity,-1) + 1) ";
					 
			if ($Module_DoubleUnit == 1) {
				$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(AdjustmentDt_Quantity,0)) ";
			}		 
			$query = $query." WHERE AdjustmentDt_ID = '".$SerialAdjDt_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. "; 
	}	
}

if ($ErrorExists == 0 && $IsAvailable == 1) {
	//Calculating Master Amounts
	$CalculateResult = Calculate_MasterAmounts($AdjId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
	$message  = $message . $CalculateResult;
}



$message          = ereg_replace(' ','%20',$message);
$lstWarehouse     = ereg_replace(' ','%20',$lstWarehouse);
$PAdjRemark       = ereg_replace(' ','%20',$PAdjRemark);
$PAdjRequestBy    = ereg_replace(' ','%20',$PAdjRequestBy);

$lstWarehouse     = ereg_replace('#','%23',$lstWarehouse);
$PAdjRemark       = ereg_replace('#','%23',$PAdjRemark);
$PAdjRequestBy    = ereg_replace('#','%23',$PAdjRequestBy);

$lstWarehouse     = ereg_replace('&','%26',$lstWarehouse);
$PAdjRemark       = ereg_replace('&','%26',$PAdjRemark);
$PAdjRequestBy    = ereg_replace('&','%26',$PAdjRequestBy);


header ( "Location: ./Form_AdjustmentAddSerial.php?AdjustType=".$AdjustType."&mainaction=".$mainaction."&PAdjId=".$AdjId."&perpage=".$PerPage.	
		 "&PAdjDate=".$PAdjDate."&PAdjCurr=".$PAdjCurr."&PAdjProjectCode=".$PAdjProjectCode."&PAdjCostCentCode=".$PAdjCostCentCode.
		 "&PAdjIsInvoice=".$PAdjIsInvoice."&PAdjInvDebit=".$PAdjInvDebit."&PAdjInvCredit=".$PAdjInvCredit."&PAdjRequestBy=".$PAdjRequestBy.
		 "&lstWarehouse=".$lstWarehouse."&PAdjEntryType=".$PAdjEntryType."&PAdjRemark=".$PAdjRemark."&message=".$message );


function Calculate_MasterAmounts($PId, $PRate, $PRate1, $PRate2, $connection) {
		
	$vAdjTotalCost      = 0;
	$vAdjTotalCostBase1 = 0;
	$vAdjTotalCostBase2 = 0;
	
	//Calculating Master Amounts
	$sub_query = " Select ifNull(Sum(ifNull(AdjustmentDt_Quantity,0)*ifNull(AdjustmentDt_Price,0)),0) As TotalCost  ".
				 " From Temp_AdjustmentDt ".
				 " Where Adjustment_ID = ".$PId;
	$sub_result = selectData($connection, $sub_query);
										 
	//echo $sub_query;exit;
					
	$vAdjTotalCost       = $sub_result[0];
	$vAdjTotalCostBase1  = ($vAdjTotalCost*$PRate)/$PRate1;
	$vAdjTotalCostBase2  = ($vAdjTotalCost*$PRate)/$PRate2;
					

	fbegin();
	
	$sub_query1 = " UPDATE Temp_Adjustment SET ".
				  " Adjustment_Amount = $vAdjTotalCost, Adjustment_AmountBase1 = $vAdjTotalCostBase1, ".
				  " Adjustment_AmountBase2 = $vAdjTotalCostBase2 ".
				  " WHERE Adjustment_ID = ".$PId;
					 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}


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

HERE;

?>