<?php

session_start();
header("Content-type: text/html; charset=".$_SESSION['encodingmode']);
if($_SESSION['dbName']==""){
header("location:../index.php");
}

include("config.inc.php");
include("Functions_Purchase.php");

$txtItemCode = $_POST['txtItemCode']; if($txtItemCode == ""){ $txtItemCode = $_GET['txtItemCode']; }
$txtItemCode = trim(strtoupper($txtItemCode));

$lstWarehouse = $_POST['lstWarehouse']; if($lstWarehouse == "") { $lstWarehouse = $_GET['lstWarehouse']; }
$lstWarehouse = trim(strtoupper($lstWarehouse));

set_time_limit(0);

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


if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$querylog="select ifNull(Login_negativeQty,0) As Login_negativeQty, ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."') ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//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);
}

$querydflwh="select default_warehouse_code as defaultwarehouse from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_warehouse_code != '' ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
} 
//Read From Module Table
$querymodule=" Select ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ifNull(Module_rawmaterial,0) As Module_RawMaterial, ".
             " ifNull(Module_SerialNo,0) As Module_SerialNo, ifNull(Module_PostToJournal,0) As Module_PostToJournal, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_RestrictProjCost,0) As Module_RestrictProjCost, ifNull(Module_RestrictCost,0) As Module_RestrictCost, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_DivisionsDt,0) As Module_DivisionsDt, ifNull(Module_ExpireDate,0) As Module_ExpireDate, ".
			 " ifNull(Module_DirectStockAI,0) As Module_DirectStockAI, ifNull(module_outconfirm, 0) as module_outconfirm, ifNull(Module_IsInvoice,0) As Module_IsInvoice ".
             " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

if($module_outconfirm == 1 && $AdjustType == 'O') $checkConfirm = 1;
else $checkConfirm = 0;

$queryAdjustSetup="Select ifNull(ShowCostCentLayout,0) As ShowCostCentLayout, ifNull(CurrencyBase,1) As SetupCurrencyBase, Warehouse_code As SetupDftWareHouse,Barcode,ifnull(Adjustment_loadCharging,0) as Adjustment_loadCharging
				From AdjustmentSetup ";
$resultAdjustSetup=mysql_query($queryAdjustSetup,$connection) or die(mysql_error());
while($rowAdjustSetup=mysql_fetch_array($resultAdjustSetup)){
	extract($rowAdjustSetup);
}

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


</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='insertadjustment' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SAdjId' value='$SAdjId'>
<input type='text' name='SAdjDtId' value='$SAdjDtId'>
<input type='text' name='AdjustType' value='$AdjustType'>
<input type='text' name='SAdjDivId' value='$SAdjDivId'>
<input type='text' name='SAdjDtDivId' value='$SAdjDtDivId'>

HERE;
*/
$message='';

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

//Submit Record Mode
if ($mode == "checkduplicate" ){

	$query = " select  count(item_code) from temp_adjustmentdt where item_code='".$PItem."' and adjustment_id = '".$SAdjId."'  ";
	$result=mysql_query($query, $connection) or die(mysql_error());
	$row=mysql_fetch_array($result);
	echo $row[0];
	exit;
}
if ($mode == "submitrecord" || $mode == "submitrecord-ajax" || $mode == "importexcel" || $mode == "submitbarcode"){

	$ErrorExists = 0;
	$InsertAllow = 1;


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

	$vAdjProjectCode  = "".$vAdjProjectCode;
	$vAdjCostCentCode = "".$vAdjCostCentCode;
	
	if ($vAdjCostCentCode == '')	$CostCentCode = 'Null';
	else	$CostCentCode = "'".$vAdjCostCentCode."'";

	if ($vAdjProjectCode == '')	$ProjectCode = 'Null';
	else	$ProjectCode = "'".$vAdjProjectCode."'";

	if (empty($vAdjInvDebit))	$AdjInvDebit = 'Null';
	else	$AdjInvDebit = "'".$vAdjInvDebit."'";
	if (empty($vAdjInvCredit))	$AdjInvCredit = 'Null';
	else	$AdjInvCredit = "'".$vAdjInvCredit."'";
	
	if (empty($txtManualNo))	$txtManualNo = 'Null';
	else	$txtManualNo = "'".$txtManualNo."'";

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

	//check for item code
	if($txtItemCode != ''){
		$check_query1 = "select  count(item_code) from temp_adjustmentdt where item_code='".$txtItemCode."' and adjustment_id = '".$SAdjId."' ";
		$result=selectData($connection, $check_query1);
			if ($result[0] >= 1) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Duplicate item code '.$txtItemCode.' ';
		}

	}

	//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;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	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;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	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;
			$message = 'Insert not allowed. Please check for Debit Ledger Number.';
		}
	}
	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;
			$message = 'Insert not allowed. Please check for Credit Ledger Number.';
		}
	}
	
	if ($mode != "importexcel"){
		if ($txtItemCode != '') {
			$sub_query = " Select Count(Item_Code) From Items ".
						 " Where Item_Code = '".$txtItemCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Item Code.';
			}
		}
		if ($lstWarehouse != '') {
			$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
						 " Where Warehouse_Code = '".$lstWarehouse."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Warehouse Code.';
			}
		}
		$txtProjectCodeDt = "".$txtProjectCodeDt;
		if ($txtProjectCodeDt != '') {
			$sub_query = " Select Count(Project_Code) From Project ".
						 " Where Project_Code = '".$txtProjectCodeDt."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Project Code.';
			}
		}
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($txtCostCentCodeDt != '') {
			$sub_query = " Select Count(Costcent_code) From Costcent ".
						 " Where Costcent_code = '".$txtCostCentCodeDt."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
			}
		}
	}	
	
	if ($txtClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$txtClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Code.';
		}
	}
	
	if($txtClientCode == '') $txtClientCode = "NULL";
	else $txtClientCode = "'".$txtClientCode."'";
	
	if($txtManualNo == '') $txtManualNo = "NULL";
	else $txtManualNo = "'".$txtManualNo."'";
	
	if($txtAdjDivision == '') $txtAdjDivision = 0;
	if($txtloadToChanging == '') $txtloadToChanging = 0;
	
	//Insert Master Table
	if ($SAdjId == "" && $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, client_code, adj_division, chk_loadToChanging, ".
				 " adjustment_manualNo, 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."',  ".$txtClientCode.",  ".$txtAdjDivision.", ".$txtloadToChanging.", ".
				 "          ".$txtManualNo.", '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' )";


		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;

		if ($result){
			$SAdjId = $vAdjId;
			$PAdjId = $vAdjId;
			fcommit();
			
			//Insert Divisions For Adjustment
			//InsertDivisions($SAdjId, $connection, $_SESSION['dbLabel'], $_SESSION['useraccount']);
		}else{
			$PAdjId = "";
			$SAdjId = "";
			$message  = mysql_error();
			frollback();
		} 

	}

	
	//Insert Detail Tables
	if ($SAdjId != "" && $SAdjDtId == "" && $ErrorExists == 0 && ($mode == "submitrecord" || $mode == "submitrecord-ajax" || $mode == "submitbarcode")){

		if (empty($txtAdjDtQty))	$txtAdjDtQty = 0;
		if (empty($txtAdjDtQty2))	$txtAdjDtQty2 = 0;
		if (empty($txtAdjDtPrice))  $txtAdjDtPrice = 0;

		if (empty($txtAdjDtExpireDate))		$vAdjDtExpireDate = "Null";
		else  $vAdjDtExpireDate = "'".insertMySQLDate($txtAdjDtExpireDate)."'";
		
		if (empty($PAdjdtInvDebit))		$PAdjdtInvDebit = "Null";
		else  $PAdjdtInvDebit = "'".$PAdjdtInvDebit."'";
		
		
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}	

		

		$vAdjDtQty        = 0;
		$vAdjDtQty2       = 0;
		$vAdjDtPrice      = 0;
		$vAdjDtPriceBase1 = 0;
		$vAdjDtPriceBase2 = 0;

		$vAdjDtDirectStkDbt = '';
		$vAdjDtDirectStkCrd = '';
		$vAdjDtDirectStkCur = '';

		$QtyExistExceeded   = 0;
		
		//Case Scanning Barcode
		if ($mode == "submitbarcode" && $txtItemBarcode != ''){
			$sub_query = " SELECT Item_Code, Currency_Code, ifNull(Item_CostMethod,0) FROM Items WHERE item_barcode = '".$txtItemBarcode."' or item_barcode2 = '".$txtItemBarcode."' or item_barcode3 = '".$txtItemBarcode."'";
			$sub_result = selectData($connection, $sub_query);
			$txtItemCode 	= $sub_result[0];
			$ItemCurr		= $sub_result[1];
			$ItemCostMethod = $sub_result[2];
			
			if ($txtItemCode == '' || empty($txtItemCode)) {
				$ErrorExists = 1;
				$message  = "Insert not allowed. Item not found."; 
			}
			
			if ($ErrorExists == 0){
				$txtAdjDtPrice = Get_CostPrice($txtItemCode, $ItemCurr, $ItemCostMethod, $vAdjDate, $vAdjCurr, $base1, $base2, $connection);
				if(empty($txtAdjDtPrice)) $txtAdjDtPrice = 0;
			}
			
		} else {

			$sub_query = " SELECT Count(*) FROM Items WHERE Item_Code = '".$txtItemCode."'";
			$sub_result = selectData($connection, $sub_query);

			//Item Code Not Exists Then Check For Barcode
			if ($sub_result[0] == 0) {
				$sub_query = " SELECT Item_Code FROM Items WHERE item_barcode = '".$txtItemCode."' or item_barcode2 = '".$txtItemCode."' or item_barcode3 = '".$txtItemCode."'";
				$sub_result = selectData($connection, $sub_query);
				$txtItemCode = $sub_result[0];

				if ($txtItemCode == '' || empty($txtItemCode)) {
					$ErrorExists = 1;
					$message  = "Insert not allowed. Item not found.";
				}
			}
		}	
		
		

		if ($ErrorExists == 0){
			$query = " SELECT ifNull(Item_Pack, 0) FROM Items WHERE Item_Code = '".$txtItemCode."'";
			$result   = selectData($connection, $query);
			$ItemPack = $result[0];
			
			// Case Not Pack Item
			//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
			if ($ItemPack != 1) {

				$vAdjDtQty        = $txtAdjDtQty;
				$vAdjDtQty2       = $txtAdjDtQty2;
				$vAdjDtPrice      = $txtAdjDtPrice;
				$vAdjDtPriceBase1 = ($vAdjDtPrice*$rate_dt)/$rate_dt1;
				$vAdjDtPriceBase2 = ($vAdjDtPrice*$rate_dt)/$rate_dt2;

				$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 = '".$txtItemCode."'";
				$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];

				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $ItemUnit;
					$vItemUnit2Qty = $vAdjDtQty2;
				}


				//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
				if ($ItemNonStock == 0 && ($AdjustType == 'O' || ($AdjustType == 'A' && $vAdjDtQty < 0))) {
					if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "") {
						$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtAdjDtBatchNo."', '".insertMySQLDate($vAdjDate)."', 0, '".$JourType."', '', '') QtyExists From Dual ";
					} else {
						$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$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 = '".trim(strtoupper($txtItemCode))."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $SAdjId And AdjustmentDt_ID != ifNull('".$SAdjDtId."',0) ";
								  
					if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "")
						$sub_query1 = $sub_query1." And	AdjustmentDt_BatchNo = '".$txtAdjDtBatchNo."' ";
					$sub_query1 = $sub_query1." And	AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $SAdjId) ";
					$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 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;

					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, AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo, Logged_Code, adjustmentdt_heatno, InvDEBITaccount ) ".
							 " VALUES ( ".$vAdjDtId.", ".$SAdjId.", '".$vAdjCurr."', '".insertMySQLDate($vAdjDate)."', $ProjectCodeDt, $CostCentCodeDt, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
							 "          '".trim(strtoupper($txtItemCode))."', Null, 0, $vAdjDtQty, $vAdjDtPrice, $vAdjDtPriceBase1, $vAdjDtPriceBase2, 0, 0, '".$JourType."', '".$vAdjDtDirectStkDbt."', ".
							 "          '".$vAdjDtDirectStkCrd."', '".$vAdjDtDirectStkCur."', 0, $vItemUnitCoef, $vItemUnit2Qty, $vAdjDtExpireDate, '".ereg_replace("'", "\'", trim($txtAdjDtBatchNo))."', ".
							 "          '".$_SESSION['useraccount']."', '".$adjustmentdt_heatno."', ".$PAdjdtInvDebit." ) ";

					$result=mysql_query($query,$connection);
					//echo $query."<br>";exit;

					if ($result){
						fcommit();
						
						//Insert Divisions For AdjustmentDt
						/*if ($Module_DivisionsDt == 1){
							InsertDivisionsDt($vAdjDtId, $txtItemCode, $connection);
						}	*/
					}else{
						$ErrorExists = 1;
						$message  = mysql_error();
						frollback();
					}
				} else {
					//$ErrorExists = 1;
					$message  = "Qty[".abs($vAdjDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")";
				}


			}	// End Case Not Pack Item
			else {

					$QtyExistExceeded   = 0;

					$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
									" FROM PackDt ".
									" WHERE Item_Code = '".$txtItemCode."'  ";

					$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
					while($packdt_rows=mysql_fetch_array($packdt_result)){

						$vItemCodePacked = $packdt_rows[0];
						$vItemCode 		 = $packdt_rows[1];
						$vPackDtQty 	 = $packdt_rows[2];
						$vPackDtCostPer  = $packdt_rows[3];

						$vAdjDtQty       = $txtAdjDtQty;

						$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) ".
									 " FROM Items WHERE Item_Code = '".$vItemCode."'";
						$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];



						//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
						if ($ItemNonStock == 0 && ($AdjustType == 'O' || ($AdjustType == 'A' && $vAdjDtQty < 0))){
							if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "") {
								$sub_query  = " Select QtyExistsByBatchNo('".$vItemCode."', '".$lstWarehouse."', '".$txtAdjDtBatchNo."', '".insertMySQLDate($vAdjDate)."', 0, '".$JourType."', '', '') QtyExists From Dual ";
							} else {
								$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$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 = '".$vItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $SAdjId And AdjustmentDt_ID != ifNull('".$SAdjDtId."',0) ";
										  
							if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "")
								$sub_query1 = $sub_query1." And	AdjustmentDt_BatchNo = '".$txtAdjDtBatchNo."' ";
							$sub_query1 = $sub_query1." And	AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $SAdjId) ";
							
							$sub_result1 = selectData($connection, $sub_query1);
							if (empty($sub_result1[0])) $sub_result1[0] = 0;

							$vItemQtyExists = $vItemQtyExists + $sub_result1[0];
							$vAdjDtQty      = $vAdjDtQty*$vPackDtQty;

							if (abs($vAdjDtQty) > $vItemQtyExists && abs($vAdjDtQty) > 0) {
								$QtyExistExceeded = 1;
								Break;
							}
						}
					}

					if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {

						fbegin();

						$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
										" FROM PackDt ".
										" WHERE Item_Code = '".$txtItemCode."'  ";

						$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
						while($packdt_rows=mysql_fetch_array($packdt_result)){

							$vItemCodePacked = $packdt_rows[0];
							$vItemCode 		 = $packdt_rows[1];
							$vPackDtQty 	 = $packdt_rows[2];
							$vPackDtCostPer  = $packdt_rows[3];



							$vAdjDtQty        = 0;
							$vAdjDtQty2       = 0;
							$vAdjDtPrice      = 0;
							$vAdjDtPriceBase1 = 0;
							$vAdjDtPriceBase2 = 0;

							$vAdjDtDirectStkDbt = '';
							$vAdjDtDirectStkCrd = '';
							$vAdjDtDirectStkCur = '';

							$QtyExistExceeded   = 0;


							$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 = '".$vItemCode."'";
							$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];
							$ItemCostMethod  = 0;
							$ItemNonStock    = $sub_result[6];
							$ItemUnit   	 = $sub_result[7];

							


							$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        = $txtAdjDtQty;
							$vAdjDtQty     	  = $vAdjDtQty*$vPackDtQty;

							$vAdjDtPrice      = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $vAdjDate, $vAdjCurr, $base1, $base2, $connection);
							$vAdjDtPriceBase1 = ($vAdjDtPrice*$rate_dt)/$rate_dt1;
							$vAdjDtPriceBase2 = ($vAdjDtPrice*$rate_dt)/$rate_dt2;

							$vItemUnitCoef = 0;
							$vItemUnit2Qty = 0;
							$vAdjDtQty2    = $txtAdjDtQty2;

							if ($Module_DoubleUnit == 1) {
								$vItemUnitCoef = $ItemUnit;
								
								if ($Module_Unit1Method == 1)
									$vItemUnit2Qty = $vAdjDtQty*$vItemUnitCoef;
								else	
									$vItemUnit2Qty = $vAdjDtQty/$vItemUnitCoef;
							}

							fbegin();
							$vAdjDtId = get_nextsequence('AdjustmentDt_id','',$connection);
							fcommit();


							$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, AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo, Logged_Code, InvDEBITaccount ) ".
									 " VALUES ( ".$vAdjDtId.", ".$SAdjId.", '".$vAdjCurr."', '".insertMySQLDate($vAdjDate)."', $ProjectCodeDt, $CostCentCodeDt, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
									 "          '".$vItemCode."',  '".trim(strtoupper($vItemCodePacked))."', $vPackDtQty, $vAdjDtQty, $vAdjDtPrice, $vAdjDtPriceBase1, $vAdjDtPriceBase2, 0, 0, '".$JourType."', ".
									 "          '".$vAdjDtDirectStkDbt."', '".$vAdjDtDirectStkCrd."', '".$vAdjDtDirectStkCur."', 0, $vItemUnitCoef, $vItemUnit2Qty, $vAdjDtExpireDate, ".
									 "          '".ereg_replace("'", "\'", trim($txtAdjDtBatchNo))."', '".$_SESSION['useraccount']."', ".$PAdjdtInvDebit." ) ";

							$result=mysql_query($query,$connection);
							//echo $query."<br>";


						} // End Loop Of Packdt

						//echo $ErrorExists; echo $message; exit;
						if ($result){
							fcommit();
							
							//Insert Divisions For AdjustmentDt
							/*if ($Module_DivisionsDt == 1){
								InsertDivisionsDt($vAdjDtId, $vItemCode, $connection);
							}*/
						}else{
							$message  = mysql_error();
							frollback();
						}

					} else {
						$ErrorExists = 1;
						$message  = "Qty[".abs($vAdjDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")";
					}


			} // End CasePack Item
		}

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

	} // End Case Insert In Detail Tables
	else if ($SAdjId != "" && $SAdjDtId == "" && $ErrorExists == 0 && $mode == "importexcel"){
	
		$file = $_FILES['excelfile']['tmp_name'];
		
		
		if (isset($_FILES['excelfile']) && $_FILES['excelfile']['size'] > 0) { 

			$file_name = addslashes($_FILES['excelfile']['name']);
			$file_type =trim($_FILES['excelfile']['type']);
			
			//echo $file_type; exit;
			if (($file_type != 'application/vnd.ms-excel') && ($file_type != 'application/excel') && 
			    ($file_type != 'application/vnd.msexcel') )
			{
				$message = "Invalid file type. Please use only .xls files.";
			}
			else {
				
				$uploaddir = './uploadsexcel/'; //assigns upload directory 
				if (!is_dir($uploaddir)) mkdir($uploaddir, 0700);
				
				$uploadfile = $uploaddir . basename($_FILES['excelfile']['name']); //assigns upload directory and file name 
				if (move_uploaded_file($_FILES['excelfile']['tmp_name'], $uploadfile)) { 
				
					require_once('Spreadsheet/Excel/Reader.php');
					
					// ExcelFile($filename, $encoding);
					$data = new Spreadsheet_Excel_Reader();

					// Set output Encoding.
					$data->setUTFEncoder('iconv');
					$data->setOutputEncoding('CP1251');
					$data->read($uploadfile);
					
					if ($_FILES["excelfile"]["error"] == 0){
					
						$vExistsSerials = '';
						for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
							
							$txtItemCode 	= $data->sheets[0]['cells'][$i][1];
							$lstWarehouse	= $data->sheets[0]['cells'][$i][2];
							$txtAdjDtQty	= $data->sheets[0]['cells'][$i][3];
							$txtAdjDtPrice	= $data->sheets[0]['cells'][$i][4];
							$txtCostCentCodeDt	= $data->sheets[0]['cells'][$i][5];
							$txtProjectCodeDt	= $data->sheets[0]['cells'][$i][6];
							
							
							if ($txtItemCode != '') {
								$sub_query = " Select Count(Item_Code) From Items ".
											 " Where Item_Code = '".$txtItemCode."'";
								$sub_result = selectData($connection, $sub_query);
								if ($sub_result[0] == 0) {
									$ErrorExists = 1;
									$message = 'Insert not allowed. Please check for Item Code.';
								}
							}
							if ($lstWarehouse != '') {
								$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
											 " Where Warehouse_Code = '".$lstWarehouse."'";
								$sub_result = selectData($connection, $sub_query);
								if ($sub_result[0] == 0) {
									$ErrorExists = 1;
									$message = 'Insert not allowed. Please check for Warehouse Code.';
								}
							}
							$txtProjectCodeDt = "".$txtProjectCodeDt;
							if ($txtProjectCodeDt != '') {
								$sub_query = " Select Count(Project_Code) From Project ".
											 " Where Project_Code = '".$txtProjectCodeDt."'";
								$sub_result = selectData($connection, $sub_query);
								if ($sub_result[0] == 0) {
									$ErrorExists = 1;
									$message = 'Insert not allowed. Please check for Detail Project Code.';
								}
							}
							$txtCostCentCodeDt = "".$txtCostCentCodeDt;
							if ($txtCostCentCodeDt != '') {
								$sub_query = " Select Count(Costcent_code) From Costcent ".
											 " Where Costcent_code = '".$txtCostCentCodeDt."'";
								$sub_result = selectData($connection, $sub_query);
								if ($sub_result[0] == 0) {
									$ErrorExists = 1;
									$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
								}
							}
					
							
							if ($ErrorExists == 0){
							
								if (empty($txtAdjDtQty))	$txtAdjDtQty = 0;
								if (empty($txtAdjDtQty2))	$txtAdjDtQty2 = 0;
								if (empty($txtAdjDtPrice))  $txtAdjDtPrice = 0;
								$txtAdjDtQty2 = 0;
								$txtAdjDtBatchNo = '';
								//if (empty($txtAdjDtExpireDate))		
								$vAdjDtExpireDate = 'Null';
								//else  $vAdjDtExpireDate = "'".insertMySQLDate($txtAdjDtExpireDate)."'";
								
								if ($Module_ProjectDt == 1){
									if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
									else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
								} else {
									$ProjectCodeDt = $ProjectCode;
								}
								if ($Module_CostCenterDt == 1) {
									if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
									else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
								} else {
									$CostCentCodeDt = $CostCentCode;
								}	



								$vAdjDtQty        = 0;
								$vAdjDtQty2       = 0;
								$vAdjDtPrice      = 0;
								$vAdjDtPriceBase1 = 0;
								$vAdjDtPriceBase2 = 0;

								$vAdjDtDirectStkDbt = '';
								$vAdjDtDirectStkCrd = '';
								$vAdjDtDirectStkCur = '';

								$QtyExistExceeded   = 0;
							
								$query = " SELECT ifNull(Item_Pack, 0) ".
										 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
								$result   = selectData($connection, $query);
								$ItemPack = $result[0];
								
								if ($ItemPack != 1) {

									$vAdjDtQty        = $txtAdjDtQty;
									$vAdjDtQty2       = $txtAdjDtQty2;
									$vAdjDtPrice      = $txtAdjDtPrice;
									$vAdjDtPriceBase1 = ($vAdjDtPrice*$rate_dt)/$rate_dt1;
									$vAdjDtPriceBase2 = ($vAdjDtPrice*$rate_dt)/$rate_dt2;

									$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 = '".$txtItemCode."'";
									$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];

									$vItemUnitCoef = 0;
									$vItemUnit2Qty = 0;
									if ($Module_DoubleUnit == 1) {
										$vItemUnitCoef = $ItemUnit;
										$vItemUnit2Qty = $ItemUnit*$vAdjDtQty;
									}
									

									//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
									if ($ItemNonStock == 0 && ($AdjustType == 'O' || ($AdjustType == 'A' && $vAdjDtQty < 0))) {
										if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "") {
											$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtAdjDtBatchNo."', '".insertMySQLDate($vAdjDate)."', 0, '".$JourType."', '', '') QtyExists From Dual ";
										} else {
											$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$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 = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $SAdjId And AdjustmentDt_ID != ifNull('".$SAdjDtId."',0) ";
													  
										if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "")
											$sub_query1 = $sub_query1." And	AdjustmentDt_BatchNo = '".$txtAdjDtBatchNo."' ";
										$sub_query1 = $sub_query1." And	AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $SAdjId) ";
										$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 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;

										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, AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo, Logged_Code ) ".
												 " VALUES ( ".$vAdjDtId.", ".$SAdjId.", '".$vAdjCurr."', '".insertMySQLDate($vAdjDate)."', $ProjectCodeDt, $CostCentCodeDt, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
												 "          '".trim(strtoupper($txtItemCode))."', Null, 0, $vAdjDtQty, $vAdjDtPrice, $vAdjDtPriceBase1, $vAdjDtPriceBase2, 0, 0, '".$JourType."', '".$vAdjDtDirectStkDbt."', ".
												 "          '".$vAdjDtDirectStkCrd."', '".$vAdjDtDirectStkCur."', 0, $vItemUnitCoef, $vItemUnit2Qty, $vAdjDtExpireDate, null, ".
												 "          '".$_SESSION['useraccount']."' ) ";
//echo $query;exit;
										$result=mysql_query($query,$connection);
										//echo $query."<br>";exit;

										if ($result){
											fcommit();
											
											//Insert Divisions For AdjustmentDt
											/*if ($Module_DivisionsDt == 1){
												InsertDivisionsDt($vAdjDtId, $txtItemCode, $connection);
											}	*/
										}else{
											$ErrorExists = 1;
											$message  = mysql_error();
											frollback();
										}
									} else {
										//$ErrorExists = 1;
										$message  = "Qty[".abs($vAdjDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")";
									}


								}	// End Case Not Pack Item
								else {

										$QtyExistExceeded   = 0;

										$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
														" FROM PackDt ".
														" WHERE Item_Code = '".$txtItemCode."'  ";

										$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
										while($packdt_rows=mysql_fetch_array($packdt_result)){

											$vItemCodePacked = $packdt_rows[0];
											$vItemCode 		 = $packdt_rows[1];
											$vPackDtQty 	 = $packdt_rows[2];
											$vPackDtCostPer  = $packdt_rows[3];

											$vAdjDtQty       = $txtAdjDtQty;

											$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) ".
														 " FROM Items WHERE Item_Code = '".$vItemCode."'";
											$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];



											//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
											if ($ItemNonStock == 0 && ($AdjustType == 'O' || ($AdjustType == 'A' && $vAdjDtQty < 0))){
												if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "") {
													$sub_query  = " Select QtyExistsByBatchNo('".$vItemCode."', '".$lstWarehouse."', '".$txtAdjDtBatchNo."', '".insertMySQLDate($vAdjDate)."', 0, '".$JourType."', '', '') QtyExists From Dual ";
												} else {
													$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$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 = '".$vItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $SAdjId And AdjustmentDt_ID != ifNull('".$SAdjDtId."',0) ";
															  
												if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "")
													$sub_query1 = $sub_query1." And	AdjustmentDt_BatchNo = '".$txtAdjDtBatchNo."' ";
												$sub_query1 = $sub_query1." And	AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $SAdjId) ";
												
												$sub_result1 = selectData($connection, $sub_query1);
												if (empty($sub_result1[0])) $sub_result1[0] = 0;

												$vItemQtyExists = $vItemQtyExists + $sub_result1[0];
												$vAdjDtQty      = $vAdjDtQty*$vPackDtQty;

												if (abs($vAdjDtQty) > $vItemQtyExists && abs($vAdjDtQty) > 0) {
													$QtyExistExceeded = 1;
													Break;
												}
											}
										}

										if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {

											fbegin();

											$packdt_query = " SELECT Item_Code, Item_CodePackDt, ifNull(PackDt_Quantity,1), PackDt_CostPercentage ".
															" FROM PackDt ".
															" WHERE Item_Code = '".$txtItemCode."'  ";

											$packdt_result=mysql_query($packdt_query, $connection) or die(mysql_error());
											while($packdt_rows=mysql_fetch_array($packdt_result)){

												$vItemCodePacked = $packdt_rows[0];
												$vItemCode 		 = $packdt_rows[1];
												$vPackDtQty 	 = $packdt_rows[2];
												$vPackDtCostPer  = $packdt_rows[3];



												$vAdjDtQty        = 0;
												$vAdjDtQty2       = 0;
												$vAdjDtPrice      = 0;
												$vAdjDtPriceBase1 = 0;
												$vAdjDtPriceBase2 = 0;

												$vAdjDtDirectStkDbt = '';
												$vAdjDtDirectStkCrd = '';
												$vAdjDtDirectStkCur = '';

												$QtyExistExceeded   = 0;


												$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 = '".$vItemCode."'";
												$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];
												$ItemCostMethod  = 0;
												$ItemNonStock    = $sub_result[6];
												$ItemUnit   	 = $sub_result[7];

												


												$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        = $txtAdjDtQty;
												$vAdjDtQty     	  = $vAdjDtQty*$vPackDtQty;

												$vAdjDtPrice      = Get_CostPrice($vItemCode, $ItemCurr, $ItemCostMethod, $vAdjDate, $vAdjCurr, $base1, $base2, $connection);
												$vAdjDtPriceBase1 = ($vAdjDtPrice*$rate_dt)/$rate_dt1;
												$vAdjDtPriceBase2 = ($vAdjDtPrice*$rate_dt)/$rate_dt2;

												$vItemUnitCoef = 0;
												$vItemUnit2Qty = 0;
												$vAdjDtQty2    = $txtAdjDtQty2;

												if ($Module_DoubleUnit == 1) {
													$vItemUnitCoef = $ItemUnit;
													
													if ($Module_Unit1Method == 1)
														$vItemUnit2Qty = $vAdjDtQty*$vItemUnitCoef;
													else	
														$vItemUnit2Qty = $vAdjDtQty/$vItemUnitCoef;
												}

												fbegin();
												$vAdjDtId = get_nextsequence('AdjustmentDt_id','',$connection);
												fcommit();


												$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, AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo, Logged_Code ) ".
														 " VALUES ( ".$vAdjDtId.", ".$SAdjId.", '".$vAdjCurr."', '".insertMySQLDate($vAdjDate)."', $ProjectCodeDt, $CostCentCodeDt, '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
														 "          '".trim(strtoupper($vItemCode))."',  '".$vItemCodePacked."', $vPackDtQty, $vAdjDtQty, $vAdjDtPrice, $vAdjDtPriceBase1, $vAdjDtPriceBase2, 0, 0, '".$JourType."', ".
														 "          '".$vAdjDtDirectStkDbt."', '".$vAdjDtDirectStkCrd."', '".$vAdjDtDirectStkCur."', 0, $vItemUnitCoef, $vItemUnit2Qty, $vAdjDtExpireDate, ".
														 "         NULL, '".$_SESSION['useraccount']."' ) ";

												$result=mysql_query($query,$connection);
												echo $query."<br>";


											} // End Loop Of Packdt

											//echo $ErrorExists; echo $message; exit;
											if ($result){
												fcommit();
												
												//Insert Divisions For AdjustmentDt
												/*if ($Module_DivisionsDt == 1){
													InsertDivisionsDt($vAdjDtId, $vItemCode, $connection);
												}*/
											}else{
												$message  = mysql_error();
												frollback();
											}

										} else {
											$ErrorExists = 1;
											$message  = "Qty[".abs($vAdjDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")";
										}


								}
								
								if ($ErrorExists == 0) {
									//Calculating Master Amounts
									$CalculateResult = Calculate_MasterAmounts($SAdjId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
									$message  = $message . $CalculateResult;
								}
							}
						
						}
						
					}
					else {
						$message = $_FILES["excelfile"]["error"];
					}
				
				} else 
				{ 
					$message = "File upload failed."; 
				}
				
			}
			
		} else {
			$message = "File not found.";
		}
	
	}
}

//Edit Detail Tables
else if (($mode == "editdt" || $mode == "editdt-ajax") && $SAdjId != "" && $SAdjDtId != ""){

	$ErrorExists == 0;
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	$txtProjectCodeDt = "".$txtProjectCodeDt;
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	if ($ErrorExists == 0) {

		if (empty($txtAdjDtQty))	$txtAdjDtQty = 0;
		if (empty($txtAdjDtQty2))	$txtAdjDtQty2 = 0;
		if (empty($txtAdjDtPrice))  $txtAdjDtPrice = 0;

		if (empty($txtAdjDtExpireDate))		$vAdjDtExpireDate = 'Null';
		else  $vAdjDtExpireDate = "'".insertMySQLDate($txtAdjDtExpireDate)."'";
		
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} 
		
		if (empty($PAdjdtInvDebit))		$PAdjdtInvDebit = "Null";
		else  $PAdjdtInvDebit = "'".$PAdjdtInvDebit."'";

		$vAdjDtQty        = 0;
		$vAdjDtQty2       = 0;
		$vAdjDtPrice      = 0;
		$vAdjDtPriceBase1 = 0;
		$vAdjDtPriceBase2 = 0;


		$QtyExistExceeded   = 0;

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

		$vAdjDtQty        = $txtAdjDtQty;
		$vAdjDtQty2       = $txtAdjDtQty2;
		$vAdjDtPrice      = $txtAdjDtPrice;
		$vAdjDtPriceBase1 = ($vAdjDtPrice*$rate_dt)/$rate_dt1;
		$vAdjDtPriceBase2 = ($vAdjDtPrice*$rate_dt)/$rate_dt2;

		$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) ".
					 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$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];



		//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
		if ($ItemNonStock == 0 && ($AdjustType == 'O' || ($AdjustType == 'A' && $vAdjDtQty < 0))){
			if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "") {
				$sub_query  = " Select QtyExistsByBatchNo('".$txtItemCode."', '".$lstWarehouse."', '".$txtAdjDtBatchNo."', '".insertMySQLDate($PAdjDate)."', $SAdjDtId, '".$JourType."', '', '') QtyExists From Dual ";
			} else {
				$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PAdjDate)."', $SAdjDtId, '".$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 = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $SAdjId And AdjustmentDt_ID != ifNull('".$SAdjDtId."',0) ";
						  
			if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "")
				$sub_query1 = $sub_query1." And	AdjustmentDt_BatchNo = '".$txtAdjDtBatchNo."' ";
			$sub_query1 = $sub_query1." And	AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $SAdjId) ";
			
			$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)) {

			fbegin();

			$query = " UPDATE Temp_AdjustmentDt SET  ".
					 " AdjustmentDt_Quantity = $vAdjDtQty, Item_Unit2Qty = $vAdjDtQty2, AdjustmentDt_Price = $vAdjDtPrice, ".
					 " AdjustmentDt_PriceBase1 = $vAdjDtPriceBase1, AdjustmentDt_PriceBase2 = $vAdjDtPriceBase2, ".
					 " AdjustmentDt_ExpireDate = $vAdjDtExpireDate, AdjustmentDt_BatchNo = '".ereg_replace("'", "\'", trim($txtAdjDtBatchNo))."', ".
					 " InvDEBITaccount = ".$PAdjdtInvDebit." ";
					 
			if ($Module_ProjectDt == 1)
				$query = $query.", Project_Code = $ProjectCodeDt ";
			if ($Module_CostCenterDt == 1)	
				$query = $query.", CostCent_Code = $CostCentCodeDt ";
			
			$query = $query.", journal_type ='".$JourType."', Warehouse_Code = '".$lstWarehouse."', Item_Code = '".str_replace('\\','\\\\',trim(strtoupper($txtItemCode)))."' ";
			
			$query = $query." Where AdjustmentDt_ID = ".$SAdjDtId;

			//echo $query; exit;
			$result=mysql_query($query,$connection);
			if ($result){
				fcommit();

				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SAdjId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
				$message  = $message . $CalculateResult;

			}else{
				$message  = mysql_error();
				frollback();
			}

		} else {
			//$ErrorExists = 1;
			$message  = "Qty[".abs($vAdjDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")";
		}
	} 	
}

//Edit ItemQuantity
else if($mode == "editqty1" && $SAdjId != "" && $SAdjDtId != ''){

	$QtyExistExceeded   = 0;

	if ($AdjustType == 'O') $QItemQty = $QItemQty * (-1);

	$sub_query = " Select AdjustmentDt.Currency_Code, AdjustmentDt.Item_Code, ifNull(Items.Item_NonStock,0) ".
                 " From Temp_AdjustmentDt As AdjustmentDt  ".
				 " Inner Join Items on Items.Item_Code = AdjustmentDt.Item_Code ".
				 " Where AdjustmentDt.Adjustment_ID = '".$SAdjId."' ".
				 " And AdjustmentDt.AdjustmentDt_ID = '".$SAdjDtId."' ";
	$sub_result = selectData($connection, $sub_query);
	$vCurrCode     = $sub_result[0];
	$vItemCode     = $sub_result[1];
	$vItemNonStock = $sub_result[2];

	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vCurrCode."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vCurrCode."' )";
	$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 Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
	if ($ItemNonStock == 0 && ($AdjustType == 'O' || ($AdjustType == 'A' && $QItemQty < 0))){
		if ($Module_ExpireDate == 1 && $txtAdjDtBatchNo != "") {
			$sub_query = " Select ifnull(QtyExistsByBatchNo(Item_Code, Warehouse_Code, AdjustmentDt_BatchNo, Adjustment_date, AdjustmentDt_ID, Journal_Type, '', ''),0) QtyExists  ".
						 " From Temp_AdjustmentDt As AdjustmentDt  ".
						 " Where AdjustmentDt.Adjustment_ID = '".$SAdjId."' ".
						 " And AdjustmentDt.AdjustmentDt_ID = '".$SAdjDtId."' ";
		} else {
			$sub_query = " Select ifnull(QtyExistsWSorder(Item_Code, Warehouse_Code, Adjustment_date, AdjustmentDt_ID, Journal_Type, '', ''),0) QtyExists  ".
						 " From Temp_AdjustmentDt As AdjustmentDt  ".
						 " Where AdjustmentDt.Adjustment_ID = '".$SAdjId."' ".
						 " And AdjustmentDt.AdjustmentDt_ID = '".$SAdjDtId."' ";
		}
		$sub_result = selectData($connection, $sub_query);
		$vItemQtyExists = 0;
		$vItemQtyExists = $sub_result[0];


		if (abs($QItemQty) > $vItemQtyExists && abs($QItemQty) > 0)
			$QtyExistExceeded = 1;
	}


	if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
		fbegin();

		$sub_query = " UPDATE Temp_AdjustmentDt SET  ".
					 " AdjustmentDt_Quantity = $QItemQty ";

		if ($Module_DoubleUnit == 1 && $Module_Unit1Method == 1) {
			$sub_query = $sub_query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(AdjustmentDt_Quantity,0)) ";
		}
		else if ($Module_DoubleUnit == 1 && $Module_Unit1Method == 0) {
			$sub_query = $sub_query.", Item_Unit2Qty = ifNull(AdjustmentDt_Quantity,0)/ifNull(Item_UnitCoef,1) ";
		}
		
		$sub_query = $sub_query." Where AdjustmentDt_ID = '".$SAdjDtId."' ".
								" And Adjustment_ID = '".$SAdjId."'";

		//echo $sub_query; exit;
		$sub_result=mysql_query($sub_query,$connection);
		if ($sub_result){
			fcommit();

			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SAdjId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
			$message  = $message . $CalculateResult;

		}else{
			$message  = mysql_error();
			frollback();
		}

	} else {
		//$ErrorExists = 1;
		$message  = "Qty[".abs($QItemQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")";
	}

}

//Delete Detail Mode
else if ($mode == "deletedt" && $SAdjDtId != ""){

	$AllowDelete = 1;
	$message  = '';


	//Check AdjustmentDt Items For Quantity Exists If Negative And Case Stock In
	if ($AllowDelete == 1 && ($AdjustType == 'I' || $AdjustType == 'A') && ($Module_NegativeQuantity == 0 || $Login_negativeQty == 0)) {

		$sub_query = " Select Count(Item_Code) ".
					 " From ( ".
					 " Select Item_Code, WareHouse_Code, AdjustmentDt_Quantity, ".
					 " QtyExistsWSorder(Item_Code, WareHouse_Code, Now(), AdjustmentDt_Id, 'AI', '', '') QtyExists ".
					 " From AdjustmentDt ".
					 " Where AdjustmentDt.AdjustmentDt_ID = '".$SAdjDtId."' ".
					 " And Journal_Type = 'AI' ".
					 " ) Q1 Where QtyExists < 0 ";

		$sub_result   = selectData($connection, $sub_query);
		$ItemQtyExists = $sub_result[0];

		if ($ItemQtyExists > 0 ){
			$message  = 'Delete not allowed, negative quantity exists.';
			$AllowDelete = 0;
		}

	}

	if ($AllowDelete == 1) {
		//Check Each AdjustmentDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_AdjustmentDt As AdjustmentDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.PurchaseDt_Id = AdjustmentDt.AdjustmentDt_Id ".
				 " Where AdjustmentDt.AdjustmentDt_ID = '".$SAdjDtId."' ".
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = AdjustmentDt.Journal_Type ";

		$result = selectData($connection, $query);
		$SerNoUsedExists = $result[0];

		if ($SerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial(s) no in use.';
			$AllowDelete = 0;
		}

	}


	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

		$ErrorExists    = 0;


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

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




		$querypack = " SELECT AdjustmentDt.Item_CodePacked, AdjustmentDt.Item_code ".
					 " FROM Temp_AdjustmentDt As AdjustmentDt ".
					 " Where AdjustmentDt.AdjustmentDt_ID = ".$SAdjDtId;


		$resultpack=mysql_query($querypack, $connection) or die(mysql_error());
		$rowspack=mysql_fetch_array($resultpack);
		$vItemCodePacked = $rowspack[0];

		fbegin();

		// Item Not Packed
		if ($vItemCodePacked == '') {

			// Delete From TempPucrhasesSerialNo For Selected Record
			$query = " DELETE FROM Temp_Purchasesserialno ".
					 " WHERE PurchaseDt_id  = ".$SAdjDtId.
					 " AND Journal_Type In ('AI','AR') ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";

			if (!updateData($connection, $query, true))
				$message  = mysql_error();
				
			$query = " DELETE FROM Temp_AdjustmentDtDivisions ".
					 " WHERE AdjustmentDt_id = ".$SAdjDtId;
			if (!updateData($connection, $query, true))
				$message  = mysql_error();   
				

			// Delete From TempAdjustmentDt For Selected Record
			$query = " DELETE FROM Temp_AdjustmentDt ".
					 " WHERE AdjustmentDt_ID = ".$SAdjDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";

			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}
			else {
				fcommit();
			}

		}
		// Item Packed Case
		else {

			$message = '';

			$querydt = " Select AdjustmentDt_ID, AdjustmentDt.Item_CodePacked, AdjustmentDt.Item_code  ".
					   " From Temp_AdjustmentDt As AdjustmentDt  ".
					   " Where AdjustmentDt.Adjustment_ID = ".$SAdjId.
					   " And AdjustmentDt.Item_CodePacked =  '".$vItemCodePacked."'  ";


			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){

				$vAdjDtId =	$rowsdt[0];

				// Delete From TempPucrhasesSerialNo For Selected Record
				$query = " DELETE FROM Temp_Purchasesserialno ".
						 " WHERE PurchaseDt_id  = ".$vAdjDtId.
						 " AND Journal_Type In ('AI','AR') ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";

				if (!updateData($connection, $query, true))
					$message  = mysql_error();
					
				$query = " DELETE FROM Temp_AdjustmentDtDivisions ".
						 " WHERE AdjustmentDt_id = ".$vAdjDtId;
				if (!updateData($connection, $query, true))
					$message  = mysql_error();   	

				// Delete From TempAdjustmentDt For Selected Record
				$query = " DELETE FROM Temp_AdjustmentDt ".
						 " WHERE AdjustmentDt_ID = ".$vAdjDtId;


				if (!updateData($connection, $query, true)) {
					$message  = mysql_error();
					$ErrorExists = 1;
					frollback();
				}

			}

			if ( $ErrorExists == 0 )
				fcommit();


		} // End Item Packed Case

		if ( $ErrorExists == 0 ){

			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SAdjId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
			$message  = $message . $CalculateResult;

		} // End If No Error Exists


	} // End If No Constraints Found On Delete


}

else if ($mode == "adddivision" && $SAdjId != "" && $SAdjDivId == ""){
	$message  = '';

	$ErrorExists = 0;
	$InsertAllow = 1;


	$vDivisionID      = $txtDivisionID;
	$vDivisionCode    = $txtDivisionCode;
	$vDivisionType    = $txtDivType;

	//Check For Division Code Before Insert
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = Upper('".$vDivisionCode."') ".
					 " And Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Division Code.';
		}
	}

	//Check For Division Type If Exists More Than Once For Adjustment
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
					 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ".
					 " And AdjustmentDivisions.Adjustment_Id = '".$SAdjId."'";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. You should add only one ('.$vDivisionType.')';
		}
	}

	//Insert Master Table
	if ($SAdjDivId == "" && $ErrorExists == 0){
		fbegin();
		$vAdjDivId = get_nextsequence('AdjustmentDivisions_Id','',$connection);
		fcommit();


		fbegin();
		$query = " INSERT INTO Temp_AdjustmentDivisions (AdjustmentDivisions_Id, Adjustment_Id, Divisions_Id ) ".
				 " VALUES ( ".$vAdjDivId.", ".$SAdjId.", ".$vDivisionID.")";


		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;

		if ($result){
			$SAdjDivId = $vAdjDivId;
			fcommit();

		}else{
			$SAdjDivId = "";
			$message  = mysql_error();
			frollback();
		}
	}
	/*else {
		if ($ErrorExists == 1)
			$message = 'Save not allowed. Please check for Division Code.';

	}*/

}

else if ($mode == "editdivision" && $SAdjId != "" && $SAdjDivId != ""){
	$message  = '';

	$ErrorExists = 0;

	$vDivisionID      = $txtDivisionID;
	$vDivisionCode    = $txtDivisionCode;
	$vDivisionType    = $txtDivType;

	//Check For Division Code Before Insert
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = Upper('".$vDivisionCode."') ".
					 " And Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Division Code.';
		}
	}

	//Check For Division Type If Exists More Than Once For Adjustment
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
					 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ".
					 " And AdjustmentDivisions.Adjustment_Id = '".$SAdjId."' ".
					 " And AdjustmentDivisions.AdjustmentDivisions_Id != '".$SAdjDivId."'";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. You should add only one ('.$vDivisionType.')';
		}
	}

	if ($SAdjDivId != "" && $ErrorExists == 0){
		fbegin();
		$query = " UPDATE Temp_AdjustmentDivisions Set Divisions_Id = '".$vDivisionID."' ".
				 " WHERE AdjustmentDivisions_Id = '".$SAdjDivId."'";


		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;

		if ($result){
			fcommit();

		}else{
			$message  = mysql_error();
			frollback();
		}

	}
	/*else {
		if ($ErrorExists == 1)
			$message = 'Save not allowed. Please check for Division Code.';

	}*/

}


else if ($mode == "deletedivision" && $SAdjId != "" && $SAdjDivId != ""){
	$message  = '';

	fbegin();

	$query = " DELETE FROM Temp_AdjustmentDivisions ".
			 " WHERE AdjustmentDivisions_Id = '".$SAdjDivId."'";

	if (!updateData($connection, $query, true)) {
		$message  = mysql_error();
		$ErrorExists = 1;
		frollback();
	}
	else {
		fcommit();
	}

}


else if ($mode == "adddivisiondt" && $SAdjId != "" && $SAdjDtId != "" && $SAdjDtDivId == ""){
	$message  = '';

	$ErrorExists = 0;
	$InsertAllow = 1;


	$vDivisionID      = $txtDivisionID;
	$vDivisionCode    = $txtDivisionCode;
	$vDivisionType    = $txtDivType;

	//Check For Division Code Before Insert
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = Upper('".$vDivisionCode."') ".
					 " And Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Division Code.';
		}
	}

	//Check For Division Type If Exists More Than Once For Adjustment
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_AdjustmentDtDivisions As AdjustmentDtDivisions ".
					 " Inner Join Divisions on AdjustmentDtDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ".
					 " And AdjustmentDtDivisions.AdjustmentDt_Id = '".$SAdjDtId."'";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. You should add only one ('.$vDivisionType.')';
		}
	}

	//Insert Master Table
	if ($SAdjDtDivId == "" && $ErrorExists == 0){
		fbegin();
		$vAdjDtDivId = get_nextsequence('AdjustmentDtDivisions_Id','',$connection);
		fcommit();


		fbegin();
		$query = " INSERT INTO Temp_AdjustmentDtDivisions (AdjustmentDtDivisions_Id, AdjustmentDt_Id, Divisions_Id ) ".
				 " VALUES ( ".$vAdjDtDivId.", ".$SAdjDtId.", ".$vDivisionID.")";


		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;

		if ($result){
			$SAdjDtDivId = $vAdjDtDivId;
			fcommit();

		}else{
			$SAdjDtDivId = "";
			$message  = mysql_error();
			frollback();
		}
	}
	/*else {
		if ($ErrorExists == 1)
			$message = 'Save not allowed. Please check for Division Code.';

	}*/

}

else if ($mode == "editdivisiondt" && $SAdjId != "" && $SAdjDtId != "" && $SAdjDtDivId != ""){
	$message  = '';

	$ErrorExists = 0;

	$vDivisionID      = $txtDivisionID;
	$vDivisionCode    = $txtDivisionCode;
	$vDivisionType    = $txtDivType;

	//Check For Division Code Before Insert
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = Upper('".$vDivisionCode."') ".
					 " And Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Division Code.';
		}
	}

	//Check For Division Type If Exists More Than Once For Adjustment
	if ($vDivisionCode != '') {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_AdjustmentDtDivisions As AdjustmentDtDivisions ".
					 " Inner Join Divisions on AdjustmentDtDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(DivisionTypes_Name) = Upper('".$vDivisionType."') ".
					 " And AdjustmentDtDivisions.AdjustmentDt_Id = '".$SAdjDtId."' ".
					 " And AdjustmentDtDivisions.AdjustmentDtDivisions_Id != '".$SAdjDtDivId."'";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. You should add only one ('.$vDivisionType.')';
		}
	}

	if ($SAdjDtDivId != "" && $ErrorExists == 0){
		fbegin();
		$query = " UPDATE Temp_AdjustmentDtDivisions Set Divisions_Id = '".$vDivisionID."' ".
				 " WHERE AdjustmentDtDivisions_Id = '".$SAdjDtDivId."'";


		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;

		if ($result){
			fcommit();

		}else{
			$message  = mysql_error();
			frollback();
		}

	}
	/*else {
		if ($ErrorExists == 1)
			$message = 'Save not allowed. Please check for Division Code.';

	}*/

}


else if ($mode == "deletedivisiondt" && $SAdjId != "" && $SAdjDtId != "" && $SAdjDtDivId != ""){
	$message  = '';

	fbegin();

	$query = " DELETE FROM Temp_AdjustmentDtDivisions ".
			 " WHERE AdjustmentDtDivisions_Id = '".$SAdjDtDivId."'";

	if (!updateData($connection, $query, true)) {
		$message  = mysql_error();
		$ErrorExists = 1;
		frollback();
	}
	else {
		fcommit();
	}

}

//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SAdjId != ''){

	$AllowDelete = 1;
	$message  = '';

	//Check If Adjustment Is Posted
	$sub_query = "SELECT ifNull(Adjustment_Posted,0) As AdjustmentPosted FROM Adjustment WHERE Adjustment_Id = ".$SAdjId;
	$sub_result = selectData($connection, $sub_query);
	$AdJPosted = $sub_result[0];

	if ($AdJPosted == 1 ){
		$message  = 'Delete not allowed, transaction posted.';
		$AllowDelete = 0;
	}

	if($Adjustment_loadCharging == 1 && $AdjustType == 'O' && $Module_IsInvoice == 1 && $AllowDelete == 1){
		$querydel = "delete from PrepaymentD where PrePaymentM_Id = (select PrePM_id from adjustment where Adjustment_Id = $SAdjId);";
		$resdel = mysql_query($querydel, $connection);
		
		$querydel = "delete from PrePaymentM where PrePaymentM_Id = (select PrePM_id from adjustment where Adjustment_Id = $SAdjId);";
		$resdel = mysql_query($querydel, $connection);
		
		
	}
	//Check AdjustmentDt Items For Quantity Exists If Negative And Case Stock In
	if ($AllowDelete == 1 && ($AdjustType == 'I' || $AdjustType == 'A') && ($Module_NegativeQuantity == 0 || $Login_negativeQty == 0)) {

		$sub_query = " Select Count(Item_Code) ".
					 " From ( ".
					 " Select Item_Code, WareHouse_Code, AdjustmentDt_Quantity, ".
					 " QtyExistsWSorder(Item_Code, WareHouse_Code, Now(), AdjustmentDt_Id, 'AI', '', '') QtyExists ".
					 " From AdjustmentDt ".
					 " Where AdjustmentDt.Adjustment_ID = '".$SAdjId."' ".
					 " And Journal_Type = 'AI' ".
					 " ) Q1 Where QtyExists < 0 ";

		$sub_result   = selectData($connection, $sub_query);
		$ItemQtyExists = $sub_result[0];

		if ($ItemQtyExists > 0 ){
			$message  = 'Delete not allowed, negative quantity exists.';
			$AllowDelete = 0;
		}

	}

	if ($AllowDelete == 1) {
		//Check Each AdjustmentDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_AdjustmentDt As AdjustmentDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.PurchaseDt_Id = AdjustmentDt.AdjustmentDt_Id ".
				 " Where AdjustmentDt.Adjustment_ID = '".$SAdjId."' ".
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = AdjustmentDt.Journal_Type ";

		$result = selectData($connection, $query);
		$SerNoUsedExists = $result[0];

		if ($SerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial(s) no in use.';
			$AllowDelete = 0;
		}

	}


	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {

	    $sub_query = " Select Journal_Id From Adjustment Where Adjustment_id = ".$SAdjId;
		$sub_result = selectData($connection, $sub_query);
		$vAdjJournalID = $sub_result[0];
		if(empty($vAdjJournalID)) $vAdjJournalID = -1;


		//Update Used Serials Set USed=0 For Related Delivery Serials
		if ($AdjustType == 'O' || $AdjustType == 'A') {
			$sub_query = " SELECT RelatedSerial_Id FROM Purchasesserialno ".
						 " WHERE PurchaseDt_id In (Select AdjustmentDt_Id From AdjustmentDt Where Adjustment_ID = ".$SAdjId." And Journal_Type = 'AR' ) ".
						 " AND Journal_Type = 'AR' ";
			$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
			while($sub_rows=mysql_fetch_array($sub_result)){

				$sub_query1 = " UPDATE purchasesserialno ".
							  " Set SerialNo_Used = 0 ".
							  "	WHERE Serial_ID = '".$sub_rows[0]."'";

				if (!updateData($connection, $sub_query1, true))
					$message  = mysql_error();
			}
		}


		// Delete From PurchasesSerialNo For Selected Record
		$query = " DELETE FROM Purchasesserialno ".
				 " WHERE PurchaseDt_id In (Select AdjustmentDt_Id From AdjustmentDt Where Adjustment_ID = ".$SAdjId." ) ".
				 " AND Journal_Type In ('AI','AR') ";

		if (!updateData($connection, $query, true))
			$message  = mysql_error();

		$query = " DELETE FROM AdjustmentDtDivisions ".
				 " WHERE AdjustmentDt_id In (Select AdjustmentDt_id From AdjustmentDt Where Adjustment_id = ".$SAdjId." ) ";
		if (!updateData($connection, $query, true))
			$message  = mysql_error();   
		
		if($config['log_file'] == 1){
			$company = explode("_", $_SESSION['dbName']);
			$currCompany = strtoupper($company[0]);
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SAdjId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'adjustment', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		
		// Delete From AdjustmentDt For Selected Record
		$query = " DELETE FROM AdjustmentDt ".
				 " WHERE Adjustment_Id = ".$SAdjId;

		if (updateData($connection, $query, true)) {
			$query = " DELETE FROM AdjustmentDivisions ".
					 " WHERE Adjustment_Id = '".$SAdjId."'";
			if (!updateData($connection, $query, true))
				$message  = mysql_error();

			// Delete From Adjustment For Selected Record
			$query = " DELETE FROM Adjustment ".
					 " WHERE Adjustment_Id = ".$SAdjId;

			if (!updateData($connection, $query, true))
				$message  = mysql_error();


			if ($vAdjJournalID != -1) {

				$query = " DELETE FROM Journal ".
						 " WHERE Journal_Id = ".$vAdjJournalID;

				if (!updateData($connection, $query, true))
					$message  = mysql_error();

			}
		}
		else
			$message  = mysql_error();

	}


}

else if ($mode == "" && $mainmode == "ConfirmStockOut" && $SAdjId != '' && $AdjustType == 'O'){
	$errorExists = 0;
	$queryup = "update adjustment set Adjustment_confirm= 1, Confirmed_user = '".$_SESSION['useraccount']."' where Adjustment_Id = $SAdjId;"; 
	if (!updateData($connection, $queryup, true)){
		$message  = mysql_error();  
		$errorExists = 1;
	}
	if($errorExists == 0){
		$message = Create_AdjustmentJv($SAdjId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']);
		if($message == '') $message = "Stock Out Confirmed!";
	}
	
}
else if ($mode == "" && $mainmode == "ConfirmAll" && $AdjustType == 'O'){
	$errorExists = 0;
	$allAdjIds = explode(',', $adjIds);
	if (count($allAdjIds) == 0) $message = "No Stock Out were Selected!";
	
	foreach ($allAdjIds as $SAdjId){
		if ($SAdjId != '*' && $SAdjId != ''){
			$queryup = "update adjustment set Adjustment_confirm= 1, Confirmed_user = '".$_SESSION['useraccount']."' where Adjustment_Id = $SAdjId;"; 
			if (!updateData($connection, $queryup, true)){
				$message  = mysql_error();  
				$errorExists = 1;
			}
			if($errorExists == 0){
				$message = Create_AdjustmentJv($SAdjId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']);
			}
		}
	}
	
	if($message == '') $message = "Stock Out Confirmed!";
	
} 
//Delete Record Mode From Temp Tables
else if (($mode == "cancel" || $mainmode == "deletepending") && $SAdjId != ''){

	$query = " DELETE FROM Temp_Purchasesserialno ".
			 " WHERE PurchaseDt_id In (Select AdjustmentDt_id From Temp_AdjustmentDt Where Adjustment_id = ".$SAdjId." ) ".
			 " AND Journal_Type In ('AI','AR') ";
			 //" AND Logged_Code = '".$_SESSION['useraccount']."' ";
	if (!updateData($connection, $query, true))
		$message  = mysql_error();

	$query = " DELETE FROM Temp_AdjustmentDtDivisions ".
			 " WHERE AdjustmentDt_id In (Select AdjustmentDt_id From Temp_AdjustmentDt Where Adjustment_id = ".$SAdjId." ) ";
	if (!updateData($connection, $query, true))
		$message  = mysql_error();   
			
	// Delete From TempAdjustmentDt For Selected Record
	$query = " DELETE FROM Temp_AdjustmentDt ".
			 " WHERE Adjustment_Id = ".$SAdjId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";

	if (updateData($connection, $query, true)) {
		$query = " DELETE FROM Temp_AdjustmentDivisions ".
				 " WHERE Adjustment_Id = '".$SAdjId."'";
		if (!updateData($connection, $query, true))
			$message  = mysql_error();

		// Delete From TempAdjustment For Selected Record
		$query = " DELETE FROM Temp_Adjustment ".
				 " WHERE Adjustment_Id = ".$SAdjId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";

		if (!updateData($connection, $query, true))
			$message  = mysql_error();
	}
	else
		$message  = mysql_error();


}


//Search Mode
else if($mainmode == "search" && $SAdjId != ''){

	$ErrorExists = 0;
	$message  = '';


	//Copy Data From Main Tables To Temp Tables
	$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, Adjustment_confirm, Confirmed_user, ".
			 " client_code, adj_division, chk_loadToChanging, PrePM_id, adjustment_manualNo, User_Account, Logged_Code ) ".
			 " SELECT 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, Adjustment_confirm, Confirmed_user, client_code, adj_division, chk_loadToChanging, PrePM_id, ".
			 " adjustment_manualNo, User_Account, '".$_SESSION['useraccount']."' ".
			 " FROM Adjustment ".
			 " WHERE Adjustment_id = ".$SAdjId;

	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error();
	}

	//echo $message.$query; exit;

	if ($ErrorExists == 0) {
		$query = " INSERT INTO Temp_AdjustmentDivisions (AdjustmentDivisions_Id, Adjustment_Id, Divisions_Id ) ".
				 " SELECT AdjustmentDivisions_Id, Adjustment_Id, Divisions_Id ".
				 " FROM AdjustmentDivisions ".
				 " WHERE Adjustment_Id = ".$SAdjId;

		if (!updateData($connection, $query, true))
			$message  = mysql_error();

		$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, AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo, Logged_Code , adjustmentdt_heatno, InvDEBITaccount) ".
				 " SELECT 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, AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo, '".$_SESSION['useraccount']."', adjustmentdt_heatno, InvDEBITaccount  ".
				 " FROM AdjustmentDt ".
				 " WHERE Adjustment_id = ".$SAdjId;

		if (!updateData($connection, $query, true))
			$message  = mysql_error();
			
		$query = " INSERT INTO Temp_AdjustmentDtDivisions (AdjustmentDtDivisions_Id, AdjustmentDt_Id, Divisions_Id ) ".
				 " SELECT AdjustmentDtDivisions_Id, AdjustmentDtDivisions.AdjustmentDt_Id, Divisions_Id ".
				 " FROM AdjustmentDtDivisions ".
				 " Inner Join AdjustmentDt on AdjustmentDtDivisions.AdjustmentDt_ID = AdjustmentDt.AdjustmentDt_ID ".
				 " WHERE AdjustmentDt.Adjustment_id = ".$SAdjId;

		if (!updateData($connection, $query, true))
			$message  = mysql_error();	

		$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, PurchaseDt_ID, AdjustmentDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Item_ExpireDate, Item_BatchNo, Logged_Code ) ".
				 " SELECT Serial_ID, Purchasesserialno.Journal_Type, Purchasesserialno.PurchaseDt_ID, Purchasesserialno.AdjustmentDt_ID, Purchasesserialno.Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, ".
				 " SerialNo_QuantitySold, Purchasesserialno.Warehouse_code, Item_ExpireDate, Item_BatchNo, '".$_SESSION['useraccount']."' ".
				 " FROM Purchasesserialno ".
				 " Inner Join Temp_AdjustmentDt on Purchasesserialno.PurchaseDt_ID = Temp_AdjustmentDt.AdjustmentDt_ID ".
				 " WHERE Temp_AdjustmentDt.Adjustment_id = ".$SAdjId.
				 " AND Purchasesserialno.Journal_Type = Temp_AdjustmentDt.Journal_Type ";

		if (!updateData($connection, $query, true))
			$message  = mysql_error();


	}

}




//Post Mode
else if($mode == "post" && $SAdjId != ''){

	$vAdjDate         = $txtDate;
	$vAdjCurr         = $txtCurr;
	$vAdjProjectCode  = $txtProjectCode;
	$vAdjCostCentCode = $txtCostCentCode;
	$vAdjIsInvoice    = $txtAdjIsInvoice;
	$vAdjInvDebit     = $txtInvDebit;
	$vAdjInvCredit    = $txtInvCredit;
	$vAdjRequestBy    = $txtRequestBy;
	$vAdjRemark       = $txtRemark;
	$vAdjEntryType    = $txtEntryType;
	
	$txtClientCode	  = $client_code;
	$txtAdjDivision	  = $txtdivision;
	$txtloadToChanging = $chkloadchanging;

	if (!isset($vAdjCurr))
	   $vAdjCurr = $base1;
	if (empty($vAdjIsInvoice))
		$vAdjIsInvoice = 0;

	$vAdjProjectCode  = "".$vAdjProjectCode;
	$vAdjCostCentCode = "".$vAdjCostCentCode;
	
	if ($vAdjCostCentCode == '')	$CostCentCode = 'Null';
	else	$CostCentCode = "'".$vAdjCostCentCode."'";

	if ($vAdjProjectCode == '')	$ProjectCode = 'Null';
	else	$ProjectCode = "'".$vAdjProjectCode."'";   

	if (empty($vAdjInvDebit))	$AdjInvDebit = 'Null';
	else	$AdjInvDebit = "'".$vAdjInvDebit."'";
	if (empty($vAdjInvCredit))	$AdjInvCredit = 'Null';
	else	$AdjInvCredit = "'".$vAdjInvCredit."'";
	
	if (empty($txtManualNo))	$AdjInvCredit = 'Null';
	else	$txtManualNo = "'".$txtManualNo."'";




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





    $SaveAllow   = 1;
	$ErrorExists = 0;

	$sub_query = " Select Distinct Item_CodePacked ".
				 " From Temp_AdjustmentDt ".
				 " Where Adjustment_ID = '".$SAdjId."' ".
				 " And (Item_CodePacked Is Not Null and Item_CodePacked != '') ";
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$sub_rowcount = mysql_num_rows ($sub_result);

	if ($sub_rowcount > 0) {
		while($sub_row=mysql_fetch_array($sub_result)){
			$ItemQty = 0;
			$ItemPackQty = 0;

			$CheckQty = 0;
			$PackDtCode = '';
			$PackDtQty  = 0;

			$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
						  " From PackDt ".
						  " Where Item_Code = '".$sub_row[0]."' ";
			$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());
			while($sub_row1=mysql_fetch_array($sub_result1)){
				// PackDt Items Should Be Different And Have Same Qty
				if ($PackDtCode != '' && $PackDtCode != $sub_row1[1] && $PackDtQty  == $sub_row1[2])
					$CheckQty = 1;

				$PackDtCode = $sub_row1[1];
				$PackDtQty  = $sub_row1[2];
			}

			// If PackDt Items Are Different And Have Same Qty Then Check For Qty Differences
			if ($CheckQty == 1) {
				$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
							  " From PackDt ".
							  " Where Item_Code = '".$sub_row[0]."' ";
				$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());
				while($sub_row1=mysql_fetch_array($sub_result1)){
					$sub_query2 = " Select Item_CodePacked, Item_Code, Sum(ifNull(Abs(AdjustmentDt_Quantity),0)) As AdjustmentDtQuantity ".
								  " From Temp_AdjustmentDt ".
								  " Where Adjustment_ID = '".$SAdjId."' ".
								  " And Item_CodePacked = '".$sub_row1[0]."' ".
								  " And Item_Code = '".$sub_row1[1]."' ".
								  " Group by Item_CodePacked, Item_Code ";

					$sub_result2 = selectData($connection, $sub_query2);
					$ItemPackQty = $sub_result2[2] / $sub_row1[2];
					if (empty($sub_result2[2])) $ItemPackQty = -1;

					if ($ItemQty == 0) $ItemQty = $ItemPackQty;
					if ($ItemQty != $ItemPackQty) $SaveAllow = 0;


				}
			}

		}
	}




	//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;
			$message = 'Save not allowed. Please check for Costcenter Code.';
		}
	}
	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;
			$message = 'Save not allowed. Please check for Project Code.';
		}
	}
	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;
			$message = 'Save not allowed. Please check for Debit Acc/Credit Acc.';
		}
	}
	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;
			$message = 'Save not allowed. Please check for Debit Acc/Credit Acc.';
		}
	}

	if ($txtClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$txtClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Code.';
		}
	}
	
	if($txtClientCode == '') $txtClientCode = "NULL";
	else $txtClientCode = "'".$txtClientCode."'";
	
	if($txtAdjDivision == '') $txtAdjDivision = 0;
	if($txtloadToChanging == '') $txtloadToChanging = 0;
	
	if ($ErrorExists == 0 && $Module_SerialNo == 1) {
		//Checking For Difference Btw Qty and Count SerialNo
		$sub_query = " Select Count(*) From ( ".
					 " 	Select AdjustmentDt.AdjustmentDt_ID, AdjustmentDt.Item_code, Abs(ifNull(AdjustmentDt_Quantity,0)) as AdjustmentDt_Quantity, Count(SerialNo_Code) As CountSerialNo ".
					 " 	From Temp_AdjustmentDt As AdjustmentDt Left Join Items on AdjustmentDt.Item_code = Items.Item_code ".
					 " 	Left Join Temp_Purchasesserialno on AdjustmentDt.AdjustmentDt_ID = Temp_Purchasesserialno.PurchaseDt_ID ".
					 " 	And Temp_Purchasesserialno.Journal_Type = AdjustmentDt.Journal_Type ".
					 " 	And Temp_Purchasesserialno.AdjustmentDt_ID Is Not Null ".
					 " 	Where AdjustmentDt.Adjustment_ID = ".$SAdjId.
					 " 	And ifNull(Items.item_withserialno,0) = 1 ".
					 " 	Group By AdjustmentDt.AdjustmentDt_ID ".
					 " 	Having Abs(ifNull(AdjustmentDt_Quantity,0)) != CountSerialNo ".
					 " ) Q1 ";
		// echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item Serials.';
		}		 
	}
	
	if ($ErrorExists == 0) {
		//Checking For Qty Not To Be Zero
		$sub_query = " Select Count(*) From ( ".
					 " 	Select AdjustmentDt.AdjustmentDt_ID, AdjustmentDt.Item_code, ifNull(AdjustmentDt_Quantity,0) as AdjustmentDt_Quantity ".
					 " 	From Temp_AdjustmentDt As AdjustmentDt ".
					 " 	Where AdjustmentDt.Adjustment_ID = ".$SAdjId.
					 " 	And ifNull(AdjustmentDt_Quantity,0) = 0 ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item(s) Quantity [Qty cannot be zero].';
		}		 
	}
	
/*
	//Check For Mandatory Project, Costcenter
	if ($Module_Project == 1 && $Module_RestrictProjCost == 1) {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
					 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Adjustment_Id = '".$SAdjId."' ".
					 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Project is mandatory.';
		}
	}
	if ($Module_CostCenter == 1 && $Module_RestrictCost == 1) {
		$sub_query = " Select Count(Divisions_Code) ".
					 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
					 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Adjustment_Id = '".$SAdjId."' ".
					 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
		$sub_result = selectData($connection, $sub_query);

		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. CostCenter is mandatory.';
		}
	}
*/
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);
	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";


	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}

	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($vAdjDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($vAdjDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	//echo $sub_query;exit;


	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {

		$vAdjDtPrice      = 0;
		$vAdjDtPriceBase1 = 0;
		$vAdjDtPriceBase2 = 0;

		//Update Detail Amount Columns In Case Currency Is Modified
		$sub_query = " Select AdjustmentDt_Id, Currency_Code, ifNull(AdjustmentDt_Price,0), ifNull(AdjustmentDt_PriceBase1,0), ifNull(AdjustmentDt_PriceBase2,0) ".
					 " From Temp_AdjustmentDt ".
					 " Where Adjustment_ID = ".$SAdjId; 
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){

			$vAdjDtPrice         = $sub_row[2];
			$vAdjDtPriceBase1    = $sub_row[3];
			$vAdjDtPriceBase2    = $sub_row[4];


			
			if ($sub_row[1] != $vAdjCurr) { 
				$vAdjDtPrice    = ConvertCurrency($sub_row[1], $vAdjCurr, insertMySQLDate($vAdjDate), $vAdjDtPrice, $connection);

				$vAdjDtPriceBase1    = ($vAdjDtPrice*$rate_dt)/$rate_dt1;
				$vAdjDtPriceBase2    = ($vAdjDtPrice*$rate_dt)/$rate_dt2;

				$sub_query1 = " UPDATE Temp_AdjustmentDt SET  ".
							  " Currency_Code = '".$vAdjCurr."', ".
							  " AdjustmentDt_Price = $vAdjDtPrice, AdjustmentDt_PriceBase1 = $vAdjDtPriceBase1, AdjustmentDt_PriceBase2 = $vAdjDtPriceBase2 ".
							  " Where AdjustmentDt_Id = ".$sub_row[0];

				//echo $sub_query1; exit;
				if (!updateData($connection, $sub_query1, true))
					$message  = mysql_error();

			}

			/*if ($Module_DivisionsDt == 1) {
				//Get Project/Costcenter And Update Detail Table For Old Columns
				$CostCentCode = 'Null';
				$ProjectCode  = 'Null';

				$sub_query1 = " Select Divisions_Code ".
							  " From Temp_AdjustmentDtDivisions As AdjustmentDtDivisions ".
							  " Inner Join Divisions on AdjustmentDtDivisions.Divisions_Id = Divisions.Divisions_Id ".
							  " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
							  " Where AdjustmentDt_Id = '".$sub_row[0]."' ".
							  " And Upper(DivisionTypes_Name) = 'PROJECT' ";
				$sub_result1 = selectData($connection, $sub_query1);
				if ($sub_result1[0] != '') $ProjectCode = "'".$sub_result1[0]."'";


				$sub_query2 = " Select Divisions_Code ".
							  " From Temp_AdjustmentDtDivisions As AdjustmentDtDivisions ".
							  " Inner Join Divisions on AdjustmentDtDivisions.Divisions_Id = Divisions.Divisions_Id ".
							  " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
							  " Where AdjustmentDt_Id = '".$sub_row[0]."' ".
							  " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
				$sub_result2 = selectData($connection, $sub_query2);
				if ($sub_result2[0] != '') $CostCentCode = "'".$sub_result2[0]."'";


				$sub_query3 = " UPDATE Temp_AdjustmentDt SET ".
							  " Project_Code = $ProjectCode, CostCent_Code = $CostCentCode ".
							  " Where AdjustmentDt_Id = ".$sub_row[0];
				//echo $sub_query2."<br>";exit;
				if (!updateData($connection, $sub_query3, true))
					$message  = mysql_error();
			
			}*/


		}  //End Loop of AdjustmentDt Query


		
		//Update Serials ExpireDate and BatchNo From Detail Table
		if ($Module_ExpireDate == 1 && $Module_SerialNo == 1) { 
			$sub_query5 = " Select AdjustmentDt_Id, AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo ".
						  " From Temp_AdjustmentDt As AdjustmentDt  ".
						  " Where AdjustmentDt.Adjustment_ID = ".$SAdjId;
						  
			//echo $sub_query5; 
			$sub_result5=mysql_query($sub_query5,$connection) or die(mysql_error());
			while($sub_rows5=mysql_fetch_array($sub_result5)){
				if (empty($sub_rows5[1]))		$vAdjDtExpireDate = 'Null';
				else  $vAdjDtExpireDate = "'".$sub_rows5[1]."'";		
		
				$query = " UPDATE temp_purchasesserialno SET ".
						 " Item_ExpireDate = $vAdjDtExpireDate, Item_BatchNo = '".$sub_rows5[2]."' ".
					     " WHERE PurchaseDt_Id  = '".$sub_rows5[0]."' ".
						 " AND Journal_Type In ('AI','AR') ";
				//echo $query."<br>";exit;		   
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
			
			}
		}

		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SAdjId, $rate_dt, $rate_dt1, $rate_dt2, $connection);
		$message  = $message . $CalculateResult;


		//Get Project/Costcenter And Update Header And Detail Tables For Old Columns
		/*$CostCentCode = 'Null';
		$ProjectCode  = 'Null';

		$sub_query = " Select Divisions_Code ".
					 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
					 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Adjustment_Id = '".$SAdjId."' ".
					 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] != '') $ProjectCode = "'".$sub_result[0]."'";


		$sub_query = " Select Divisions_Code ".
					 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
					 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
					 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Adjustment_Id = '".$SAdjId."' ".
					 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] != '') $CostCentCode = "'".$sub_result[0]."'";*/


		$sub_query2 = " UPDATE Temp_AdjustmentDt SET ".
					  " Currency_Code = '".$vAdjCurr."', Adjustment_Date = '".insertMySQLDate($vAdjDate)."' ";
					  
		if ($Module_ProjectDt != 1)
			$sub_query2 = $sub_query2.", Project_Code = $ProjectCode ";
		if ($Module_CostCenterDt != 1)	
			$sub_query2 = $sub_query2.", CostCent_Code = $CostCentCode ";
			
		$sub_query2 = $sub_query2." WHERE Adjustment_ID = $SAdjId ";
		//echo $sub_query2."<br>";exit;
		if (!updateData($connection, $sub_query2, true))
			$message  = mysql_error();
		

		$query = " UPDATE Temp_Adjustment SET ".
				 " Adjustment_Date = '".insertMySQLDate($vAdjDate)."', Entry_Type = '".$vAdjEntryType."', ".
				 " Adjustment_Remak = '".ereg_replace("'", "\'", trim($vAdjRemark))."', ".
				 " Adjustment_isInvoice = $vAdjIsInvoice, InvDebitAccount = $AdjInvDebit, InvCreditAccount = $AdjInvCredit, ".
				 " Currency_Code = '".$vAdjCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode, client_code = $txtClientCode, adj_division = $txtAdjDivision, 
				 chk_loadToChanging = $txtloadToChanging, Adjustment_RequestBy = '".ereg_replace("'", "\'", trim($vAdjRequestBy))."', adjustment_manualNo = ".$txtManualNo." ".
				 " WHERE Adjustment_ID = $SAdjId ";

		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;

		if ($result){


			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit')   $SMode = 'U';
			//echo $SMode;exit;

			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcent_code  FROM Adjustment WHERE Adjustment_id = $SAdjId ";
			$result  = selectData($connection, $query);
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];

			/*$sub_query = " Select Divisions_Code ".
						 " From AdjustmentDivisions ".
						 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
						 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
						 " Where Adjustment_Id = '".$SAdjId."' ".
						 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
			$sub_result = selectData($connection, $sub_query);
			$vOldProjCode     = $sub_result[0];

			$sub_query = " Select Divisions_Code ".
						 " From AdjustmentDivisions ".
						 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
						 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
						 " Where Adjustment_Id = '".$SAdjId."' ".
						 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
			$sub_result = selectData($connection, $sub_query);
			$vOldCostCentCode = $sub_result[0];*/

			$query = "Select Count(*) From Temp_Adjustment where Adjustment_ID = '".$SAdjId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];
			
			$query_checkDelivery  = "select count(*) as AdjustmentExist from adjustment where adjustment_id = '$SAdjId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($AdjustmentExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);

			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();
				$query = "SELECT CopyData_TempAdjustment('".$SMode."', ".$SAdjId.", '".$_SESSION['useraccount']."') FROM Dual ";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$result = $result[0];

				if ($result != 0){
					fcommit();

					$query   = " SELECT Adjustment_Reference, Adjustment_EntryType, Costcent_code, Project_Code FROM Adjustment WHERE Adjustment_id = $SAdjId ";
					$result  = selectData($connection, $query);
					$vAdjRef  = $result[0];
					$vAdjType = $result[1];
					$vCostCentCode = $result[2];
					$vProjectCode  = $result[3];
				
					$existCode = 0;
					if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vAdjRef != ''){
						$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vAdjRef != ''){
						$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					
					/*$sub_query = " Select Divisions_Code ".
								 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
								 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
								 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
								 " Where Adjustment_Id = '".$SAdjId."' ".
								 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
					$sub_result = selectData($connection, $sub_query);
					$vProjectCode     = $sub_result[0];

					$sub_query = " Select Divisions_Code ".
								 " From Temp_AdjustmentDivisions As AdjustmentDivisions ".
								 " Inner Join Divisions on AdjustmentDivisions.Divisions_Id = Divisions.Divisions_Id ".
								 " Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
								 " Where Adjustment_Id = '".$SAdjId."' ".
								 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
					$sub_result = selectData($connection, $sub_query);
					$vCostCentCode = $sub_result[0];*/


					if ($vAdjRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
						($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {

						if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						else $vProjCostCent = '';

						fbegin();

						if ($vAdjType == 'O')
							$vAdjRef = get_nextsequence('OUT_Reference',$vProjCostCent,$connection);
						else if ($vAdjType == 'I')
							$vAdjRef = get_nextsequence('IN_Reference',$vProjCostCent,$connection);
						else
							$vAdjRef = get_nextsequence('Adjustment_Reference',$vProjCostCent,$connection);

						fcommit();

						$query = " UPDATE Adjustment SET ".
								 " Adjustment_Reference = $vAdjRef ".
								 " WHERE Adjustment_id = $SAdjId ";

						if (!updateData($connection, $query, true))
							$message  = mysql_error();

					}
					
					if ($Module_PostToJournal == 1 && $Module_DirectStockAI == 1 && $checkConfirm == 0)
						$message = Create_AdjustmentJv($SAdjId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']);
					
					if($Adjustment_loadCharging == 1 && $AdjustType == 'O' && $Module_IsInvoice == 1){
							$message = Create_PrePayment($SAdjId, $connection);
					}
					
					// JP check Max last purchase Price and Update items
					if ($vAdjType != 'O'){
						$queryPurdetails = "select   item_code, adjustment_date   from adjustmentdt  WHERE Adjustment_id = $SAdjId ";
						$resPurDetails = mysql_query($queryPurdetails , $connection);
						while($rowPurDet = mysql_fetch_array($resPurDetails)){
							$querydays = "select ifnull(itemcostdays,30)  from purchasesetup";
							$resultDays  = selectData($connection, $querydays);
							$vCurdays = $resultDays[0];
 
								$query ="call highestItemPurPricebyItem('".$rowPurDet[0]."','".$rowPurDet[1]."',$vCurdays)";
								if (!updateData($connection, $query, true)) {
										$message  = mysql_error();
										frollback();
									}
							}
					}

				} else{
					//$message  = mysql_error();
					$message  = 'Error In CopyData_TempAdjustment Function';
					frollback();
				}

			}
			if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SAdjId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'adjustment', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}

		} else{
			$message  = mysql_error();
			frollback();
		}
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllow == 0)
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
		else if ($SaveAllow == -1)
			$message = 'Save not allowed. Please check for Item(s) Quantity.';
		//else if ($ErrorExists == 1)
			//$message = 'Save not allowed. Please check for Project/Costcenter/Debit Acc/Credit Acc.';
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';

		frollback();
	}
	//exit;
}
else if($mainmode == "copyrequest" && $TrReqId != ''){


	fbegin();	
	$vSaId = get_nextsequence('adjustment_id','',$connection);	
	fcommit();
	$PGeneratedId = $vSaId;
	
	$query = " select adjustmentrequest_reference from adjustmentrequest where adjustmentrequest_id = ".$TrReqId;
	$result = mysql_query($query,$connection) or die(mysql_error());
	$row=mysql_fetch_array($result);
	$ref = $row[0];
	 
$query = " INSERT INTO Temp_Adjustment(Adjustment_Id, Adjustment_Reference, Adjustment_Date, Adjustment_Remak, Adjustment_posted, Currency_Code
			, Adjustment_Amount, Adjustment_AmountBase1, Adjustment_AmountBase2, Costcent_Code, Project_Code, Journal_id, Invdebitaccount, Invcreditaccount
			, Adjustment_isInvoice, Adjustment_BelongsToGroup, Mach_code, Item_code, Adjustment_hours, Adjustment_Type, Sendreceive_reference, Adjustment_RateBase1
			, Adjustment_RateBase2, Adjustment_Rate, Synchronized, adjustment_isinv_dstk, Tag_Reference, Adjustment_RequestBy
			, Adjustment_asset, Logged_Code, Entry_Type, adjustmentrequest_id, User_account, Adjustment_EntryType)
				Select ".$vSaId.", null,  AdjustmentRequest_Date, AdjustmentRequest_Remak, AdjustmentRequest_posted, Currency_Code, AdjustmentRequest_Amount, AdjustmentRequest_AmountBase1
				, AdjustmentRequest_AmountBase2, Costcent_Code, Project_Code, Journal_id, Invdebitaccount, Invcreditaccount, AdjustmentRequest_isInvoice
				, AdjustmentRequest_BelongsToGroup, Mach_code, Item_code, AdjustmentRequest_hours, AdjustmentRequest_Type, Sendreceive_reference, AdjustmentRequest_RateBase1
				, AdjustmentRequest_RateBase2, AdjustmentRequest_Rate, Synchronized, adjustmentRequest_isinv_dstk,  Tag_Reference, AdjustmentRequest_RequestBy
				 , AdjustmentRequest_asset, '".$_SESSION['useraccount']."', Entry_Type, adjustmentrequest_id
				, '".$_SESSION['useraccount']."','O' FROM Adjustmentrequest ".
				" WHERE Adjustmentrequest_id = ".$TrReqId;

	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 	
			 

			
		$query = "Select AdjustmentRequestDt_Id, AdjustmentRequest_Id, AdjustmentRequest_Date, Warehouse_Code, Item_Code, AdjustmentRequestDt_Quantity, AdjustmentRequestDt_Posted, Color_Code, Costcent_Code, Project_code, Size_measure, AdjustmentRequestDt_Price, AdjustmentRequestDt_PriceBase1, AdjustmentRequestDt_PriceBase2, AdjustmentRequestDt_ExistingQty, AdjustmentRequestDt_PhysicalQty, Item_Barcode, Journal_Type, AdjustmentRequestDt_DirectStkDbt, AdjustmentRequestDt_DirectStkCrd, AdjustmentRequestDt_DirectStkCur, Deliverydt_id, Item_codepacked, Synchronized, Item_qtyPacked, Currency_Code, Tag_Reference, AdjustmentDt_PricePerUnit, AdjustmentDt_QtyUnit, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, AdjustmentRequestdt_AssetPrice, AdjustmentRequestDt_ExpireDate, AdjustmentRequestDt_BatchNo, AdjustmentRequestDt_status
					FROM adjustmentrequestdt  WHERE adjustmentrequest_id = ".$TrReqId." and ifnull(upper(adjustmentrequestDt_status),'r') = 'A' ";
		//	echo $query; exit;
		$result = mysql_query($query,$connection) or die(mysql_error());	
		while($row=mysql_fetch_array($result)){
			
			fbegin();
			$vSaDtId = get_nextsequence('adjustmentdt_id','',$connection);	
			fcommit();
		
		
			$query = " INSERT INTO temp_adjustmentdt (AdjustmentDt_Id, Adjustment_Id, Adjustment_Date, Warehouse_Code, Item_Code, AdjustmentDt_Quantity, AdjustmentDt_Posted, Color_Code, Costcent_Code, Project_code, Size_measure, AdjustmentDt_Price, AdjustmentDt_PriceBase1, AdjustmentDt_PriceBase2, AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty, Item_Barcode, Journal_Type, AdjustmentDt_DirectStkDbt, AdjustmentDt_DirectStkCrd, AdjustmentDt_DirectStkCur, Deliverydt_id, Item_codepacked, Synchronized, Item_qtyPacked, Currency_Code, Tag_Reference, AdjustmentDt_PricePerUnit, AdjustmentDt_QtyUnit, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, Adjustmentdt_AssetPrice, AdjustmentDt_ExpireDate
				, AdjustmentDt_BatchNo, adjustmentrequest_Reference, adjustmentrequestdt_Id, Logged_Code)
				select ".$vSaDtId.",  ".$vSaId.", AdjustmentRequest_Date, Warehouse_Code, Item_Code, AdjustmentRequestDt_Quantity, AdjustmentRequestDt_Posted
				, Color_Code, Costcent_Code, Project_code, Size_measure, AdjustmentRequestDt_Price, AdjustmentRequestDt_PriceBase1, AdjustmentRequestDt_PriceBase2
				, AdjustmentRequestDt_ExistingQty, AdjustmentRequestDt_PhysicalQty, Item_Barcode, 'AR', AdjustmentRequestDt_DirectStkDbt
				, AdjustmentRequestDt_DirectStkCrd, AdjustmentRequestDt_DirectStkCur, Deliverydt_id, Item_codepacked, Synchronized, Item_qtyPacked
				, Currency_Code, Tag_Reference, AdjustmentDt_PricePerUnit, AdjustmentDt_QtyUnit, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty
				, AdjustmentRequestdt_AssetPrice, AdjustmentRequestDt_ExpireDate, AdjustmentRequestDt_BatchNo
				,'".$ref."', adjustmentrequestdt_Id, '".$_SESSION['useraccount']."'
				FROM adjustmentrequestdt  WHERE adjustmentrequestdt_id = ".$row[0]." and ifnull(upper(adjustmentrequestDt_status),'r') = 'A' ";
				//echo $query."<bR>"; exit;
				if (!updateData($connection, $query, true))
						$message1  = mysql_error(); 
		
		
		}
		
		//echo $message." ".$message1;
		if ($message!='' or $message1!='')
		frollback();
		else
		fcommit();
	
	header ("Location: ./Form_AdjustmentLoadRequest.php?PMode=1&GeneratedId=".$PGeneratedId."&message=".$message);		
	exit;
}

else if($mainmode == "loadserial"){

	$ErrorExists = 0;
	$message  = '';

if ($SetupCurrencyBase == 1) $vAdjCurr = $base1;
	else $vAdjCurr = $base2;	
$serialnbs = explode(",", $txtserialnbr);	
	//Copy Data From Main Tables To Temp Tables
	fbegin();
		$vAdjId = get_nextsequence('Adjustment_id','',$connection);
		fcommit();

		$AdjustType = 'A';
		$jourType = 'AI';
		fbegin();
		$query = " INSERT INTO temp_adjustment (Adjustment_ID, Adjustment_Reference, Adjustment_Date, Currency_Code,  ".
				 " Adjustment_Type, Adjustment_EntryType,  ".
				 " Adjustment_AmountBase1, Adjustment_AmountBase2,  Adjustment_BelongsToGroup, Adjustment_Posted, User_Account, Logged_Code ) ".
				 " VALUES ( ".$vAdjId.", Null, now(), '".$vAdjCurr."', ".
				 "   'AI',  '".$AdjustType."', '$base1', '$base2', $FI_BelongsToGrp, 0, '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' )";
	

	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error();
	}

	//echo $message.$query; exit;

	if ($ErrorExists == 0) {
		fbegin();
		$vAdjDtId = get_nextsequence('AdjustmentDt_ID','',$connection);
		fcommit();
		
		if($default_warehouse_code == '')
				 $lstWarehouse = $SetupDftWareHouse; 
		
		fbegin();
		$query = " INSERT INTO temp_adjustmentdt (AdjustmentDt_ID, Adjustment_ID, Currency_Code, Adjustment_Date,  Warehouse_Code, ".
							 " Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentDt_Quantity, AdjustmentDt_Price, AdjustmentDt_PriceBase1, AdjustmentDt_PriceBase2, ".
							 " AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty,Journal_Type, Logged_Code ) ".
							 " VALUES ( ".$vAdjDtId.", ".$vAdjId.", '".$vAdjCurr."', now(),  '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
							 "          '".trim(strtoupper($fromitem))."', Null, 0, - $txtqty, '$txtcost', '$base1','$base2', 0, 0, '$jourType', '".$_SESSION['useraccount']."' ) ";


		if (!updateData($connection, $query, true)){
			$message  = mysql_error();
			$ErrorExists =1;
		}

		if($ErrorExists == 0){
		fcommit();
		
		
		foreach($serialnbs as $serialnb){	
		fbegin(); 
		$srlId = get_nextsequence('Serial_ID','',$connection);
		fcommit();	
		$query = " INSERT INTO temp_purchasesserialno ( Serial_ID,Journal_Type, PurchaseDt_ID, AdjustmentDt_ID, Item_Code, SerialNo_Code, SerialNo_Used,
					Warehouse_code, Logged_Code ) ".
				"values ($srlId,'AI', $vAdjDtId, $vAdjDtId,'$fromitem', '$serialnb',1, '$lstWarehouse', '".$_SESSION['useraccount']."' )";
		if (!updateData($connection, $query, true))
			$message  = mysql_error();
		}
		}
		
		fbegin();
		$vAdjDtId = get_nextsequence('AdjustmentDt_ID','',$connection);
		fcommit();
		
		if($default_warehouse_code == '')
				 $lstWarehouse = $SetupDftWareHouse; 
		
		fbegin();
		$query = " INSERT INTO temp_adjustmentdt (AdjustmentDt_ID, Adjustment_ID, Currency_Code, Adjustment_Date,  Warehouse_Code, ".
							 " Item_code, Item_CodePacked, Item_qtyPacked, AdjustmentDt_Quantity, AdjustmentDt_Price, AdjustmentDt_PriceBase1, AdjustmentDt_PriceBase2, ".
							 " AdjustmentDt_ExistingQty, AdjustmentDt_PhysicalQty,Journal_Type, Logged_Code ) ".
							 " VALUES ( ".$vAdjDtId.", ".$vAdjId.", '".$vAdjCurr."', now(),  '".ereg_replace("'", "\'", trim($lstWarehouse))."', ".
							 "          '".trim(strtoupper($toitem))."', Null, 0, '$txtqty', '$txtcost', '$base1', '$base2', 0, 0, '$jourType', '".$_SESSION['useraccount']."' ) ";


		if (!updateData($connection, $query, true)){
			$message  = mysql_error();
			$ErrorExists =1;
		}
		if($ErrorExists == 0){
			fcommit();
			
		foreach($serialnbs as $serialnb){
			fbegin();
			$srlId = get_nextsequence('Serial_ID','',$connection);
			fcommit();				
		$query = " INSERT INTO temp_purchasesserialno ( Serial_ID, Journal_Type, PurchaseDt_ID, AdjustmentDt_ID, Item_Code, SerialNo_Code, SerialNo_Used,
					Warehouse_code, Logged_Code ) ".
				"values ($srlId, 'AI', $vAdjDtId,$vAdjDtId, '$toitem', '$serialnb',0, '$lstWarehouse', '".$_SESSION['useraccount']."' )";

		if (!updateData($connection, $query, true))
			$message  = mysql_error();
		}
		}

	}
	echo $vAdjId; exit;
	

}



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

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


//if($mode == "post")
	//header ("Location: ./Form_Adjustment.php?AdjustType=".$AdjustType."&actionmode=post&mainaction=&PrAdjId=".$SAdjId."&PrAdjRef=".$vAdjRef."&message=".$message);
if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_Adjustment.php?AdjustType=".$AdjustType."&HideMenu=".$HideMenu."&actionmode=".$mode."&mainaction=".$mainmode."&PrAdjId=".$SAdjId."&PrAdjRef=".$vAdjRef."&message=".$message);
	else
		header ("Location: ./Form_Adjustment.php?AdjustType=".$AdjustType."&HideMenu=".$HideMenu."&actionmode=submitrecord&mainaction=".$mainmode."&txtAdjId=".$SAdjId."&message=".$message);
}
else if ($mode == "" && $mainmode == "delete" )
	header ("Location: ./Form_AdjustmentSearch.php?AdjustType=".$AdjustType."&message=".$message);
else if ($mode == "" && $mainmode == "deletepending")
	header ("Location: ./Form_AdjustmentSearchPending.php?AdjustType=".$AdjustType);
else if ($mode == "cancel" )		
	header ("Location: ./Form_Adjustment.php?AdjustType=".$AdjustType."&HideMenu=".$HideMenu."&message=".$message);	
//else if ($mode == "deletedt" )
	//header ("Location: ./Form_Adjustment.php?AdjustType=".$AdjustType."&actionmode=".$mode."&mainaction=".$mainmode."&txtAdjId=".$SAdjId."&message=".$message);
else if ($mode == "editdt")
	header ("Location: ./Form_AdjustmentDetail.php?AdjustType=".$AdjustType."&actionmode=".$mode."&mainaction=".$mainmode."&PAdjId=".$PAdjId."&PAdjDate=".$PAdjDate."&PAdjDtId=".$SAdjDtId."&message=".$message);
else if ($mode == "editqty1" && $mainmode == "" )
	header ("Location: ./Form_AdjustmentSerialNo.php?AdjustType=".$AdjustType."&SRAdjDtId=".$SAdjDtId."&SRAdjId=".$SAdjId."&PMode=1&message=".$message);
else if ($mode == "" && $mainmode == "search" )
	header ("Location: ./Form_AdjustmentSearch.php?AdjustType=".$AdjustType."&PMode=1");
else if ($mainmode == "copyrequest")
	header ("Location: ./Form_AdjustmentLoadRequest.php?AdjustType=O&PMode=1");
else if ($mode == "importexcel")	
	header ("Location: ./Form_Adjustment.php?AdjustType=".$AdjustType."&HideMenu=".$HideMenu."&actionmode=submitrecord&mainaction=".$mainmode."&txtAdjId=".$SAdjId."&message=".$message);		
else if ($mode == "adddivision" || $mode == "editdivision" || $mode == "deletedivision")
	header ("Location: ./Form_Adjustment.php?AdjustType=".$AdjustType."&HideMenu=".$HideMenu."&actionmode=".$mode."&mainaction=".$mainmode."&txtAdjId=".$SAdjId."&message=".$message);
else if ($mode == "adddivisiondt" || $mode == "editdivisiondt" || $mode == "deletedivisiondt")
	header ("Location: ./Form_AdjustmentDtDivisions.php?AdjustType=".$AdjustType."&actionmode=".$mode."&mainaction=".$mainmode."&PAdjId=".$SAdjId."&PAdjDtId=".$SAdjDtId."&message=".$message);	
else if($mode == "submitrecord") {
    header ("Location: ./Form_AdjustmentDetail.php?AdjustType=".$AdjustType."&actionmode=".$mode."&mainaction=".$mainmode."&PAdjId=".$PAdjId."&PAdjDate=".$PAdjDate.
			"&PAdjCurr=".$PAdjCurr."&PAdjProjectCode=".$PAdjProjectCode."&PAdjCostCentCode=".$PAdjCostCentCode."&PAdjIsInvoice=".$PAdjIsInvoice."&PAdjInvDebit=".$PAdjInvDebit.
			"&PAdjInvCredit=".$PAdjInvCredit."&PAdjEntryType=".$PAdjEntryType."&PAdjRequestBy=".$PAdjRequestBy."&lstWarehouse=".$lstWarehouse."&PAdjRemark=".$PAdjRemark."&message=".$message);
} else if( $mode == "" && ($mainmode == 'ConfirmStockOut' || $mainmode == 'ConfirmAll' ))
	header ("Location: ./Form_StockOutConfirm.php?AdjustType=".$AdjustType."&message=".$message);


$return_arr = array();

$row_array['message'] = $message;
$row_array['transid'] = $SAdjId;
		
array_push($return_arr,$row_array);
echo json_encode($return_arr);



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;

}

function InsertDivisions($PId, $connection, $PDbLabel, $PUserAccount) {

	//Insert Project
	$sub_query = " Select Project_Code From ".$PDbLabel.".loginstk ".
				 " Where User_Account='".$PUserAccount."' ".
				 " And ifNull(Default_Project, 0) = 1 ";
	$sub_result  = selectData($connection, $sub_query);
	//echo $sub_query."<br>";
	$ProjectCode = $sub_result[0];
	$ProjectCode = "".$ProjectCode;
	if ($ProjectCode != "") {
		$sub_query = " Select Divisions_ID ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = '".$ProjectCode."' ".
					 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
		$sub_result  = selectData($connection, $sub_query);
		$DivisionsID = $sub_result[0];

		fbegin();
		$vAdjDivId = get_nextsequence('AdjustmentDivisions_Id','',$connection);
		fcommit();

		$query = " INSERT INTO Temp_AdjustmentDivisions (AdjustmentDivisions_Id, Adjustment_Id, Divisions_Id ) ".
				 " VALUES (".$vAdjDivId.", ".$PId.", ".$DivisionsID." )";
		$result=mysql_query($query,$connection);
	}

	//Insert CostCenter
	$sub_query = " Select CostCent_Code From ".$PDbLabel.".loginstk ".
				 " Where User_Account='".$PUserAccount."' ".
				 " And ifNull(Default_CostCenter, 0) = 1 ";
	$sub_result  = selectData($connection, $sub_query);
	//echo $sub_query."<br>";
	$CostCenterCode = $sub_result[0];
	$CostCenterCode = "".$CostCenterCode;
	if ($CostCenterCode != "") {
		$sub_query = " Select Divisions_ID ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = '".$CostCenterCode."' ".
					 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
		$sub_result  = selectData($connection, $sub_query);
		$DivisionsID = $sub_result[0];

		fbegin();
		$vAdjDivId = get_nextsequence('AdjustmentDivisions_Id','',$connection);
		fcommit();

		$query = " INSERT INTO Temp_AdjustmentDivisions (AdjustmentDivisions_Id, Adjustment_Id, Divisions_Id ) ".
				 " VALUES (".$vAdjDivId.", ".$PId.", ".$DivisionsID." )";
		$result=mysql_query($query,$connection);
	}



	//exit;
}


function InsertDivisionsDt($PDtId, $PItemCode, $connection) {

	//Insert Project
	$sub_query = " Select Project_Code, CostCent_Code From Items ".
				 " Where Item_Code = '".$PItemCode."' ";
	$sub_result  = selectData($connection, $sub_query);
	//echo $sub_query."<br>";
	$ProjectCode    = $sub_result[0];
	$CostCenterCode = $sub_result[1];
	
	if ($ProjectCode != "") {
		$sub_query = " Select Divisions_ID ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = '".$ProjectCode."' ".
					 " And Upper(DivisionTypes_Name) = 'PROJECT' ";
		$sub_result  = selectData($connection, $sub_query);
		$DivisionsID = $sub_result[0];

		fbegin();
		$vAdjDtDivId = get_nextsequence('AdjustmentDtDivisions_Id','',$connection);
		fcommit();

		$query = " INSERT INTO Temp_AdjustmentDtDivisions (AdjustmentDtDivisions_Id, AdjustmentDt_Id, Divisions_Id ) ".
				 " VALUES (".$vAdjDtDivId.", ".$PDtId.", ".$DivisionsID." )";
		$result=mysql_query($query,$connection);
	}

	if ($CostCenterCode != "") {
		$sub_query = " Select Divisions_ID ".
					 " From Divisions Inner Join DivisionTypes on Divisions.DivisionTypes_Id = DivisionTypes.DivisionTypes_Id ".
					 " Where Upper(Divisions_Code) = '".$CostCenterCode."' ".
					 " And Upper(DivisionTypes_Name) = 'COSTCENTER' ";
		$sub_result  = selectData($connection, $sub_query);
		$DivisionsID = $sub_result[0];

		fbegin();
		$vAdjDtDivId = get_nextsequence('AdjustmentDtDivisions_Id','',$connection);
		fcommit();

		$query = " INSERT INTO Temp_AdjustmentDtDivisions (AdjustmentDtDivisions_Id, AdjustmentDt_Id, Divisions_Id ) ".
				 " VALUES (".$vAdjDtDivId.", ".$PDtId.", ".$DivisionsID." )";
		$result=mysql_query($query,$connection);
	}



	//exit;
}

function Create_PrePayment($SAdjId, $connection) {
	
	$querychk = "select PrePM_id from adjustment where Adjustment_Id = $SAdjId;"; 
	$reschk = mysql_query($querychk,$connection);
	$rwchk = mysql_fetch_row($reschk);
	$PrePM_Id = $rwchk[0]; 
	
	if($PrePM_Id == ''){
		fbegin();
		$PrePM_Id = get_nextsequence('PrePaymentM_Id','',$connection);
		fcommit();
		
		fbegin();
		$query = " insert into PrepaymentM (PrePaymentM_Id, Ledger_number, PrePayment_Edit, Prepayment_dbcd, PrePayment_TotalB1, PrePayment_TotalB2, PrePayment_RemainB1, PrePayment_RemainB2) ".
				 " select $PrePM_Id, Invdebitaccount, 0, 'D', abs(Adjustment_AmountBase1), abs(Adjustment_AmountBase2), abs(Adjustment_AmountBase1), abs(Adjustment_AmountBase2) ".
				 " from adjustment where Adjustment_Id = $SAdjId;";
	} else {
		fbegin();
		$query = " update PrepaymentM, adjustment ".
				 " set Ledger_number = Invdebitaccount, PrePayment_TotalB1 = abs(Adjustment_AmountBase1), PrePayment_TotalB2 = abs(Adjustment_AmountBase2), ".
				 " PrePayment_RemainB1 = abs(Adjustment_AmountBase1), PrePayment_RemainB2 = abs(Adjustment_AmountBase2) ".
				 " where Adjustment_Id = $SAdjId and PrePaymentM_Id = PrePM_id and PrePaymentM_Id = $PrePM_Id;";
		
	} //echo $query;echo "<br>";	exit;
	$result=mysql_query($query,$connection);
	if ($result){
		fcommit();
	} else {
		$PrePM_Id = '';
		$message  = mysql_error();
		$ErrorExists = 1;
		frollback();
	}
	if($PrePM_Id != '' && $ErrorExists == 0){
		$del = " delete from PrepaymentD where PrePaymentM_Id = $PrePM_Id;";
		$res = mysql_query($del,$connection);
		
		$querysel = " select adjustment.Invcreditaccount as Invcreditaccount, adjustmentdt.Costcent_code, adjustmentdt.Project_code, adjustment.Invdebitaccount,adjustment.Currency_code, ".
					 " adjustment.Project_Code, adjustment.Costcent_code, Adjustment_Remak, Adjustment_Amount, adj_division, adjustmentdt.Adjustment_Date, 1, Adjustment_AmountBase1, Adjustment_AmountBase2, ".
					 " 0, 0, 0, 0, client_code, adjustmentdt.Item_Code, SerialNo_Code, adjustmentdt.Warehouse_Code ".
					 " from adjustmentdt ".
					 " inner join adjustment on adjustment.adjustment_id = adjustmentdt.adjustment_id ".
					 " left join purchasesserialno on purchasesserialno.AdjustmentDt_ID = adjustmentdt.adjustmentdt_id ".
					 " where adjustment.adjustment_id = $SAdjId;";
		$ressel = mysql_query($querysel, $connection);			 
		while($rwsel = mysql_fetch_array($ressel)){
			fbegin();
			$PrePD_Id = get_nextsequence('PrePaymentD_Id','',$connection);
			fcommit();
			
			extract($rwsel);
			
			fbegin();
			$query = " insert into PrepaymentD (PrePaymentD_Id, PrePaymentM_Id, Ledger_number, Costcent_CodeD, Project_CodeD, Ledger_NumberM, Currency_code, Project_Code, Costcent_code, Description, amount, division, ".
					 " Date1, generate, amountbase1, amountbase2, amountgenerate, AmountGenerate1, AmountGenerate2, divisiongenerate, client_code, item_code, serial_no, warehouse_code) ".
					 " values ($PrePD_Id, $PrePM_Id, ".strformat($Invcreditaccount).", ".strformat($Costcent_code).", ".strformat($Project_code).", ".strformat($Invdebitaccount).",'".$Currency_code."', ".
					 " ".strformat($Project_Code).", ".strformat($Costcent_code).", ".strformat($Adjustment_Remak).", abs($Adjustment_Amount), $adj_division, ".strformat($Adjustment_Date).", 1, abs($Adjustment_AmountBase1), ".
					 " abs($Adjustment_AmountBase2), 0, 0, 0, 0, ".strformat($client_code).", ".strformat($Item_Code).", ".strformat($SerialNo_Code).", ".strformat($Warehouse_Code)." ) ";
					 
				//echo $query;echo "<br>";	
			$result=mysql_query($query,$connection);
			if ($result){
				fcommit();
			} else {
				$PrePD_Id = '';
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}	
		}	
	}//exit;
	
	 if($ErrorExists == 0 && $PrePM_Id != ''){
		$update = "update adjustment set PrePM_id = $PrePM_Id where Adjustment_Id = $SAdjId; ";//echo $update;exit;
		$res = mysql_query($update,$connection);
	} 
	return $message;
}


function strformat($str){
	if($str == '') $str = "NULL";
	else $str = "'".ereg_replace("'", "\'", trim($str))."'";
	return $str;
}
/*
print <<<HERE
</form>
</body>

HERE;
*/

?>