<?php

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


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


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

//Read From Login Table
$querylog=" select ifNull(FI_ShowCostPrice,0) As FI_ShowCostPrice ".
          " from ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

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

//Read From Module Table
$querymodule=" Select ifNull(Module_Pack,0) As Module_Pack, ifNull(Module_SerialNo,0) As Module_SerialNo, ".
             " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_BatchNo,0) As Module_BatchNo, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt ".
			 " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}



//Group List
$querygroup= " select distinct group_code, group_name ".
			 " from grouping where group_code in (select group_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."') ".
			 " order by group_code";
$resultgroup = mysql_query($querygroup,$connection) or die(mysql_error());
$groupexist   = mysql_num_rows($resultgroup);
if ($groupexist == 0)
	$querygroup="select group_code, group_name from grouping order by group_code";
	
$resultgroup=mysql_query($querygroup,$connection) or die(mysql_error());


//Warehouse List
$querywarehouse=" select distinct warehouse.warehouse_code, warehouse_name ".
				" from warehouse where warehouse_code in (select warehouse_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."') ".
				" order by warehouse.warehouse_code";
$resultwh = mysql_query($querywarehouse,$connection) or die(mysql_error());
$whexist   = mysql_num_rows($resultwh);
if ($whexist == 0)
	$querywarehouse="select warehouse_code,warehouse_name from warehouse order by warehouse_code";
	
$resultwarehouse=mysql_query($querywarehouse,$connection) or die(mysql_error());


$querydflwh="select default_warehouse_code as defaultwarehouse from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk where user_account='".$HTTP_SESSION_VARS['useraccount']."' and default_warehouse_code != '' ";
$resultdflwh=mysql_query($querydflwh,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflwh)){
  extract($rows);
}


if ($AdjustType == 'O')      { $FormTitle = 'Stock Out';  $JourType = 'AR'; }
else if ($AdjustType == 'I') { $FormTitle = 'Stock In';   $JourType = 'AI'; }
else if ($AdjustType == 'A') { $FormTitle = 'Adjustment'; $JourType = 'AI'; } 

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">


function SubmitRecord(ItemExpire) {
	x = document.adjustmentdt;
	
	var vAdjustType = x.AdjustType.value;
	
	var result = CheckFields(vAdjustType,ItemExpire);
	var vAdjId      = x.PAdjId.value;
	var vAdjDtId    = x.txtAdjDtId.value;
	var vMainMode   = x.mainaction.value;
	var vMode	    = x.actionmode.value;
	var vAdjustType = x.AdjustType.value;
	
	if (vAdjDtId == '')
		vMode = 'submitrecord';	
	else
		vMode = 'editdt';	
	   
	if (result == 1) {
		x.action="Form_Adjustment_Actions.php?AdjustType="+vAdjustType+"&mode="+vMode+"&mainmode="+vMainMode+"&SAdjId="+vAdjId+"&SAdjDtId="+vAdjDtId;
		x.submit();
		
	}	
}

function ChangeLocation() {
	x = document.adjustmentdt;
	var vMode = x.actionmode.value;
	
	if (vMode == 'submitrecord') {
		
		opener.document.adjustment.actionmode.value = x.actionmode.value;
		opener.document.adjustment.mainaction.value = x.mainaction.value;
		//opener.document.adjustment.message.value = x.message.value;
		opener.document.adjustment.txtAdjId.value = x.PAdjId.value;
		opener.document.adjustment.submit();
		
	} 
	else if (vMode == 'submitrecord' || vMode == 'editdt') {
		opener.document.adjustment.actionmode.value = x.actionmode.value;
		opener.document.adjustment.mainaction.value = x.mainaction.value;
		opener.document.adjustment.txtAdjId.value = x.PAdjId.value;
		opener.document.adjustment.submit();
		
		if (x.message.value == '')
			self.close();
	
	}
	
	if (document.getElementById('txtItemCode').type == 'text')
		x.txtItemCode.focus();
}

function CheckFields(AdjustType,ItemExpire){
  
    x = document.adjustmentdt;
	
	var AdjDtItem = x.txtItemCode.value;
	var AdjDtWarehouse = x.lstWarehouse.value;
	var AdjDtQty   = x.txtAdjDtQty.value;
	var AdjDtQty2  = x.txtAdjDtQty2.value;
	var AdjDtPrice = x.txtAdjDtPrice.value;
	
	var AdjDtExpireDate = x.txtAdjDtExpireDate.value;
	var AdjDtBatchNo    = x.txtAdjDtBatchNo.value;
	
	
	AdjDtQty   = parseFloat(AdjDtQty);
	AdjDtPrice = parseFloat(AdjDtPrice);
	
	
	var vmode = x.actionmode.value;
	
	
	if (AdjDtWarehouse=='')
	{
		alert("Warehouse Column is mandatory!");
		x.lstWarehouse.focus();
		return 0;
	}
	else if (AdjDtItem=='' )
	{
		alert("Item Column is mandatory!");
		x.txtItemCode.focus();
		return 0;
	}
	else if (AdjDtQty == '' || AdjDtQty*1 != AdjDtQty/1 ) {
		alert('Quantity should be a NUMERIC value ');
		x.txtAdjDtQty.focus();
		return 0;
	}
	else if (AdjDtQty < 0 && AdjustType == 'I') {
		alert('Quantity should be a POSITIVE value ');
		x.txtAdjDtQty.focus();
		return 0;
	}
	else if ((AdjDtPrice*1 != AdjDtPrice/1 || AdjDtPrice < 0) ) {
		alert('Cost Price should be a NUMERIC and POSITIVE value');
		x.txtAdjDtPrice.focus();
		return 0;
	}
	else if ((AdjDtQty2 != '' && AdjDtQty2*1 != AdjDtQty2/1) ) {
		alert('Item Qty2 should be a NUMERIC value.');
		x.txtAdjDtQty2.focus();
		return 0;
	}
	else if (ItemExpire == 1 && AdjDtExpireDate == '' ) {
		alert('Item Expire Date is mandatory.');
		x.txtAdjDtExpireDate.focus();
		return 0;
	}
	else if (ItemExpire == 1 && AdjDtBatchNo == '' ) {
		alert('Item Batch No is mandatory.');
		x.txtAdjDtBatchNo.focus();
		return 0;
	}
		
	
	else
	return 1 ;	
}






//All= All form; D= Detail Part
function ClearForm(Option){
    x = document.adjustmentdt;
	var vmode = x.actionmode.value;
	
	if (Option == 'D')
	{
		x.txtAdjDtId.value='';
		x.txtItemCode.value='';
		x.txtItemDesc.value='';
		x.lstWarehouse.value='';
		x.txtAdjDtQty.value='';
		x.txtAdjDtQty2.value='';
		x.txtAdjDtPrice.value='';
		x.txtAdjDtTotal.value='';
		x.txtAdjDtBatchNo.value='';
		x.txtAdjDtExpireDate.value='';
		
		//x.message.value='';
		x.actionmode.value = '';
	
	}

}


function CalcAdjDtTotal(TagID, dec) {
	x = document.adjustmentdt;
	var vmode = x.actionmode.value;
	var vAdjustType = x.AdjustType.value;
	var Qty = x.txtAdjDtQty.value;
	
	if (vAdjustType == 'O' && TagID == 'txtAdjDtQty' && Qty > 0) {
		x.txtAdjDtQty.value = Qty*(-1);
	}
	
	var Qty = x.txtAdjDtQty.value;
	var CostPrice = x.txtAdjDtPrice.value;
	if (Qty == '') Qty = 0;
	if (CostPrice == '') CostPrice = 0;
	
	Qty = parseInt(Qty);
	CostPrice = parseFloat(CostPrice);
	
	
	
	//if (Qty > 0 && CostPrice >= 0)
	   x.txtAdjDtTotal.value = Math.round((Qty*CostPrice)*Math.pow(10,dec))/Math.pow(10,dec);

}


function CalcQty2(ModuleUnit1Method,UnitCoef,Option) {
	x = document.adjustmentdt;
	var Qty  = x.txtAdjDtQty.value;
	var Qty2 = x.txtAdjDtQty2.value;
	
	if (Qty == '')  Qty = 0;
	if (Qty2 == '') Qty2 = 0;
	
	if(ModuleUnit1Method == 1) {
		if (Qty != 0 && Option == 1 && document.getElementById('txtAdjDtQty2').type == 'text') {
			x.txtAdjDtQty2.value = Qty*UnitCoef;
		}	
		else if (Qty == 0 && Option == 1 && document.getElementById('txtAdjDtQty2').type == 'text') {
			x.txtAdjDtQty2.value = '';
		}
	}
	//Case Modify Qty and Qty2 Should Be Empty
	else if(ModuleUnit1Method == 0 && Option == 1 && Qty2 == 0) {
		if (Qty != 0 && UnitCoef != 0 && document.getElementById('txtAdjDtQty2').type == 'text') {
			x.txtAdjDtQty2.value = Qty/UnitCoef;
		}	
		else if (Qty == 0 && document.getElementById('txtAdjDtQty2').type == 'text') {
			x.txtAdjDtQty2.value = '';
		}
	}
	//Case Modify Qty2 Get Qty
	else if(ModuleUnit1Method == 0 && Option == 2) {
		if (Qty2 != 0 && document.getElementById('txtAdjDtQty2').type == 'text') {
			x.txtAdjDtQty.value = Qty2*UnitCoef;
		}	
		else if (Qty2 == 0 && document.getElementById('txtAdjDtQty2').type == 'text') {
			x.txtAdjDtQty.value = '';
		}
	}
}

function showlistItems(str){
  var vdate, vid;
  x = document.adjustmentdt;
  
  vAdjustType = x.AdjustType.value;
  vdate = x.PAdjDate.value;
  vid   = x.PAdjId.value;
  vItemType  = x.lstItemType.value;
  vItemGroup = x.lstGroup.value;
  vItemSort  = 'ItemCode';
  vItemWh    = x.lstWarehouse.value;
  vItemCode  = x.txtItemCode.value;
  
  //if (vAdjustType == 'I') vItemWh = '';
  
  vItemGroup = vItemGroup.replace('&','%26');
  vItemWh = vItemWh.replace('&','%26');
  
  
  window.open('List_SorItems.php?frm=5&PItem_Code='+vItemCode+'&ItemType='+vItemType+'&ItemSort='+vItemSort+'&ItemGroup='+vItemGroup+'&ItemWh='+vItemWh+'&TransDate='+vdate,'mywindow','width=850,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistBatchNo(str) {
	x = document.adjustmentdt;
	vItemCode  = x.txtItemCode.value;
	
	window.open('List_BatchNo.php?frm=3&PItem_Code='+vItemCode,'List_BatchNo','width=580,height=400,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistProject(str){

  window.open('List_SorProject.php?frm=16&item='+str,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistCostcenter(str){

  window.open('List_SorCostcenter.php?frm=16&item='+str,'mywindow','width=850,height=550,,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function kd(e)
{
	x=document.adjustmentdt;
    var intKey = (window.Event) ? e.which : e.keyCode;
    if (intKey == 13) { //enter key
        x.btnSubmitRecord.click();
		return false;
    }
    return true;
}

</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>$FormTitle Detail - Add Items</title>


<script type="text/javascript" src="dropdown.js"></script>
<link rel="stylesheet" href="default.css" type="text/css" />
<link rel="stylesheet" href="short.css" type="text/css" />
<link rel="stylesheet" href="dropdown.css" type="text/css" />
<style type="text/css">

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 2px;
	margin-left: 1px;
}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}
.style11 {color: #999999; font-weight: bold; }
.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}
.style15 {color: #5151FF; font-size: 10px;}
.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #FFFFFF ;font-size: 10px;}

</style>

<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>

</head>
<body onLoad='ChangeLocation();'>
<form name='adjustmentdt' method='post'>
<input type='hidden' name='message' value='$message'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='actionmode' value='$actionmode'>
<input type='hidden' name='AdjustType' value='$AdjustType'>
<input type='hidden' name='PAdjEntryType' value='$PAdjEntryType'>
<input type='hidden' name='PAdjDate' value='$PAdjDate'>
<input type='hidden' name='PAdjId' value='$PAdjId'>
<input type='hidden' name='PAdjDtId' value='$PAdjDtId'>

<input type='hidden' name='PAdjCurr' value='$PAdjCurr'>
<input type='hidden' name='PAdjProjectCode' value='$PAdjProjectCode'>
<input type='hidden' name='PAdjCostCentCode' value='$PAdjCostCentCode'>
<input type='hidden' name='PAdjIsInvoice' value='$PAdjIsInvoice'>
<input type='hidden' name='PAdjInvDebit' value='$PAdjInvDebit'>
<input type='hidden' name='PAdjInvCredit' value='$PAdjInvCredit'>

HERE;
						 
echo "<input type='hidden' name='PAdjRequestBy' value='".htmlspecialchars($PAdjRequestBy, ENT_QUOTES)."'>";
echo "<input type='hidden' name='PAdjRemark' value='".htmlspecialchars($PAdjRemark, ENT_QUOTES)."'>";
	
		                  
						  
//Pack Item Module
$ModePackItem = '';
if ($Module_Pack == 0)	$ModePackItem = ' disabled ';


$lstWarehouse = $_POST["lstWarehouse"]; if ($lstWarehouse == ""){$lstWarehouse = $_GET["lstWarehouse"];}   
$lstItemType = $_POST['lstItemType']; if ($lstItemType == ""){$lstItemType = $_GET["lstItemType"];} if ($lstItemType == ""){$lstItemType = "All";}

if (empty($lstWarehouse)) {
	if(!empty($defaultwarehouse))
		$lstWarehouse = $defaultwarehouse;
	else	
		$lstWarehouse = $SetupDftWareHouse;
}	

if ($Module_ProjectDt == 1 && empty($txtProjectCodeDt))     $txtProjectCodeDt  = $PAdjProjectCode; 
if ($Module_CostCenterDt == 1 && empty($txtCostCentCodeDt)) $txtCostCentCodeDt = $PAdjCostCentCode; 

//Edit Production Detail Mode
if($PAdjDtId != ''){
	$querydt = " Select AdjustmentDt_ID, AdjustmentDt.Item_CodePacked, AdjustmentDt.Item_code, Item_Description, AdjustmentDt.Warehouse_Code, ".
	           " AdjustmentDt_Quantity, Round(AdjustmentDt_Price, ".$DecimalBase."), AdjustmentDt_PriceBase1, AdjustmentDt_PriceBase2, ".
			   " Round((ifNull(AdjustmentDt_Quantity,0)*ifNull(AdjustmentDt_Price,0)), ".$DecimalBase.") As TotalAmount, AdjustmentDt.Journal_Type, ".
			   " AdjustmentDt.Item_Unit2Qty, Date_Format(AdjustmentDt_ExpireDate,'%d/%m/%Y') As AdjustmentDt_ExpireDate, AdjustmentDt_BatchNo, ".
			   " AdjustmentDt.Project_code, AdjustmentDt.Costcent_Code ".
			   " From Temp_AdjustmentDt As AdjustmentDt Left Join Items on AdjustmentDt.Item_code = Items.Item_code ".
	           " Where AdjustmentDt.AdjustmentDt_ID = ".$PAdjDtId;
			   //" And Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";			   
	//echo $querydt;
	$resultdt=mysql_query($querydt,$connection) or die(mysql_error());
    $rowsdt=mysql_fetch_array($resultdt);
 	
	$txtAdjDtId      = $rowsdt[0];
	$txtItemCode     = $rowsdt[2];
	$txtItemDesc     = $rowsdt[3];
	$lstWarehouse    = $rowsdt[4];
	$txtAdjDtQty     = $rowsdt[5];
	$txtAdjDtQty2    = $rowsdt[11];
	$txtAdjDtPrice   = $rowsdt[6];
	$txtAdjDtTotal   = $rowsdt[9];
	$JourType        = $rowsdt[10];
	
	$txtAdjDtExpireDate = $rowsdt[12];
	$txtAdjDtBatchNo    = $rowsdt[13]; 
	
	$txtProjectCodeDt	= $rowsdt[14]; 
	$txtCostCentCodeDt	= $rowsdt[15]; 
	
}
$i_unitcoef = 1;
$i_expire   = 0;

if($txtItemCode != ''){

	$min_sorder_qty = 0;
	$min_available_qty = 9999999999;
	$min_exists_qty = 9999999999;
	$available_qty = 0;
	$exist_qty = 0;
	$temp_qty = 0;
	
	$vItemCode    = '';
	$vItemPackQty = 0;
	
	if (empty($PAdjId))   $PAdjId = 0;
	if (empty($PAdjDtId)) $PAdjDtId = 0;
	
	if($lstItemType == 'Packed' || $lstItemType == 'PromoPacked'){
		$query = "SELECT Item_CodePackDt, Sum(PackDt_Quantity) FROM packdt WHERE Item_Code = '".$txtItemCode."' Group By Item_CodePackDt ";
		$result = mysql_query($query, $connection);			
		//echo $query;
		while($cur = mysql_fetch_row($result)){

			$Qry_QtyExists = " SELECT ifnull(QtyExists('".$cur[0]."', '".$lstWarehouse."', '".insertMySQLDate($PAdjDate)."', $PAdjDtId, '".$JourType."', '', ''),0) As QtyExists ";
			//echo "<br><br>".$Qry_QtyExists;
			$sub_result3 = selectData($connection, $Qry_QtyExists);
			if (empty($sub_result3[0])) $sub_result3[0] = 0;
			
			$Qry_QtyInTemp = " Select ifNull(Sum(ifNull(AdjustmentDt_Quantity,0)),0) FROM Temp_AdjustmentDt ".
							 " WHERE Item_code = '".$cur[0]."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $PAdjId And AdjustmentDt_ID != ifNull('".$PAdjDtId."',0) ".
							 " And 	AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $PAdjId) ";
			$sub_result = selectData($connection, $Qry_QtyInTemp);
			
			$exist_qty = (($sub_result3[0] + $sub_result[0]) / $cur[1]); 
			if ($exist_qty < $min_exists_qty ){
				$min_exists_qty = $exist_qty;
					
				$vItemCode    = $cur[0];
				$vItemPackQty = $cur[1];
				$temp_qty     = $sub_result[0];
			}
			
		}
		

		$Qry_QtyBookTemp  = " SELECT ifnull(QtyBooking('".$vItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PAdjDate)."'),0)";
		$Qry_QtyAvailable = " SELECT ifnull(QtyExistsWSorder('".$vItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PAdjDate)."', $PAdjDtId, '".$JourType."', '', ''),0) QtyExists ";
		
		//echo "<br><br>".$Qry_QtyBookTemp;
		//echo "<br><br>".$Qry_QtyAvailable;
					
		$sub_result  = selectData($connection, $Qry_QtyBookTemp);
		$sub_result1 = selectData($connection, $Qry_QtyAvailable);
			
		if ($sub_result[0] < 0) {$sub_result[0] = 0;}
		
		$min_available_qty = abs(($sub_result1[0] + $temp_qty) / $vItemPackQty);
		$min_sorder_qty    = ($sub_result[0] / $vItemPackQty);
		
			
			
		$min_sorder_qty = ceil($min_sorder_qty);
		//$min_available_qty = floor($min_available_qty);
		$min_available_qty = floor($min_exists_qty) - ceil($min_sorder_qty);
		$min_exists_qty = floor($min_exists_qty);
 
	}else{
		$Qry_QtyBookTemp = "SELECT ifnull(QtyBooking('".$txtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PAdjDate)."'),0) ";
		$result = selectData($connection, $Qry_QtyBookTemp);
		if ($result[0] < 0){$result[0] = 0;}
		$min_sorder_qty = $result[0];
		
		$Qry_QtyExists = " SELECT ifnull(QtyExists('".$txtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PAdjDate)."', $PAdjDtId, '".$JourType."', '', ''),0) As QtyExists ";				 
		$result = selectData($connection, $Qry_QtyExists);
		$min_exists_qty = $result[0];
		//echo $Qry_QtyExists;
		
		$Qry_QtyAvailable = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PAdjDate)."', $PAdjDtId, '".$JourType."', '', '') QtyExists From Dual ";
		$result = selectData($connection, $Qry_QtyAvailable);
		$min_available_qty = $result[0];

		$Qry_QtyInTemp = " Select ifNull(Sum(ifNull(AdjustmentDt_Quantity,0)),0) FROM Temp_AdjustmentDt ".
		                 " WHERE Item_code = '".$txtItemCode."'  And  Warehouse_code = '".$lstWarehouse."' And Adjustment_ID = $PAdjId And AdjustmentDt_ID != ifNull('".$PAdjDtId."',0) ".
						 " And 	AdjustmentDt_ID Not In (Select AdjustmentDt_ID From AdjustmentDt Where Adjustment_ID  = $PAdjId) ";
		$result = selectData($connection, $Qry_QtyInTemp);
		$temp_qty = $result[0];
		
		$min_available_qty = $min_available_qty + $temp_qty;
		$min_exists_qty    = $min_exists_qty    + $temp_qty;
		$min_sorder_qty    = $min_sorder_qty;

	}
	//echo $query;
	$txtBookingQty   = $min_sorder_qty;
	$txtAvailableQty = $min_available_qty;
	$txtExistingQty  = $min_exists_qty;
	
	
	
	$sub_query = " SELECT Item_Vat, Currency_Code, ifNull(Item_CostMethod,0), ifNull(Item_NonStock,0), ".
				 " Item_UnitSalesDesc, Item_UnitPurchaseDesc, ifNull(Item_Unit,1), ifNull(Item_Expire,1) ".	
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
	$sub_result = selectData($connection, $sub_query);
	$ItemVat 	     = $sub_result[0];
	$ItemCurr		 = $sub_result[1];
	//$ItemCostMethod  = $sub_result[2];
	$ItemCostMethod  = 0;
	$ItemNonStock    = $sub_result[3];
	$i_unit1  	  	 = $sub_result[4];
	$i_unit2 	  	 = $sub_result[5]; 
	$i_unitcoef	     = $sub_result[6];
	$i_expire	  	 = $sub_result[7];
		
	$txtItemUnit1  = $i_unit1;
	$txtItemUnit2  = $i_unit2;
	
	if($PAdjDtId == '' || $PAdjDtId == 0){
		$txtAdjDtQty = 1;
		if ($AdjustType == 'O') $txtAdjDtQty = -1;
		
		if ($Module_DoubleUnit == 1){
			if ($Module_Unit1Method == 1)
				$txtAdjDtQty2 = ($txtAdjDtQty*$i_unitcoef);
			else	
				$txtAdjDtQty2 = ($txtAdjDtQty/$i_unitcoef);
		}		
		
		$txtAdjDtPrice = Round(Get_CostPrice($txtItemCode, $ItemCurr, $ItemCostMethod, $PAdjDate, $PAdjCurr, $base1, $base2, $connection), $DecimalBase);		
		$txtAdjDtTotal = Round(($txtAdjDtQty*$txtAdjDtPrice), $DecimalBase);
	}	

	
	
}



$style= "style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'";

	  
echo"   <tr><td valign='top'>
        <table border='0' style='table-layout:fixed' align='center' valign='top'>
          <col width=90>
		  <col width=170>
		  <col width=80>
		  <col width=170>
		  <col width=80>
		  <col width=80>";
		  
echo"	   <tr bgcolor='#F7F7F7' height='25'>
		     <th colspan='6'><span class='style3'>Add Items </span></th></tr>
		   <tr bgcolor='#F7F7F7' height='25'>	
			 <td colspan='6' align='center'><font size='1' color='#FF0000' face='Verdana'><b>".$message."</b></font></td></tr>			 
			 
		   <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Warehouse&nbsp;<span class='style26'>*</span></span></td>";
		     
		if ($PAdjDtId == '') {	 	 
			echo" <td colspan='3'><select name='lstWarehouse' id='lstWarehouse' style='font-size:11px; width:200px; height:20px;' >";
			echo"<option></option>";
			while($wrhf=mysql_fetch_row($resultwarehouse)){
			echo"<option ";
				if (($lstWarehouse==$wrhf[0]) || ($DftWareHouse==$wrhf[0]))
					echo " selected ";
			echo" value='$wrhf[0]'>$wrhf[0] / $wrhf[1]</option>";
			}
			echo"</select></td>";
			
		} else 	{
			echo"<td colspan='3'><b>$lstWarehouse</b><input type='hidden' name='lstWarehouse' id='lstWarehouse' value='$lstWarehouse'></td>";
		
		}
			
	echo" 	 <td align='left'><span class='style12'>Existing Qty</span></td>
			 <td align='right'><b>".number_format($txtExistingQty,2)."</b> <input type='hidden' name='txtExistingQty' value='$txtExistingQty' ></td>
		  </tr>	 
		  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Item Type</span></td>
		     <td colspan='3'>
			 <input type='hidden' name='txtAdjDtId' value='$txtAdjDtId' >
			 <select name='lstItemType' style='font-size:11px; width:200px; height:20px;'>";
			
			if ($lstItemType == "All"){
				echo "<option selected value='All'>All Items</option>";
			}else {
				echo "<option value='All'>All Items</option>";
			}
			if ($lstItemType == "Packed" && $Module_Pack == 1){
				echo "<option selected value='Packed'>Packed</option>";
			}else if ($Module_Pack == 1){
				echo "<option value='Packed'>Packed</option>";
			}
			if ($lstItemType == "PromoPacked" && $Module_Pack == 1){
				echo "<option selected value='PromoPacked'>Promo Packed</option>";
			}else{
				echo "<option value='PromoPacked'>Promo Packed</option>";
			}
			if ($lstItemType == "Trading"){
				echo "<option selected value='Trading'>Trading</option>";
			}else{
				echo "<option value='Trading'>Trading</option>";
			}
			if ($lstItemType == "PromoTrading"){
				echo "<option selected value='PromoTrading'>Promo Trading</option>";
			}else{
				echo "<option value='PromoTrading'>Promo Trading</option>";
			}
			if ($lstItemType == "Production"){
				echo "<option selected value='Production'>Production</option>";
			}else{
				echo "<option value='Production'>Production</option>";
			}
			if ($lstItemType == "NonStock"){
				echo "<option selected value='NonStock'>Non-Stock</option>";
			}else{
				echo "<option value='NonStock'>Non-Stock</option>";
			}
			echo "</select></td>";
			 
			
echo"    	  <td align='left'><span class='style12'>Booking Qty</span></td>
			  <td align='right'><b>".number_format($txtBookingQty,2)."</b><input type='hidden' name='txtBookingQty' value='$txtBookingQty' ></td>
		  </tr>	 
		  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Group</span></td>
		     <td colspan='3'><select name='lstGroup' id='lstGroup' style='font-size:11px; width:383px; height:20px;' >";
			echo"<option></option>";
			while($groupf=mysql_fetch_row($resultgroup)){
			echo"<option ";
				if ($lstGroup==$groupf[0] )
					echo " selected ";
			echo" value='$groupf[0]'>$groupf[0] - $groupf[1]</option>";
			}
			
echo"        </select></td>	
			 <td align='left'><span class='style12'>Real Qty</span></td>
			 <td align='right'><b>".number_format($txtAvailableQty,2)."</b> <input type='hidden' name='txtAvailableQty' value='$txtAvailableQty' ></td>	
		  </tr>	 
		  <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Item&nbsp;<span class='style26'>*</span></span></td>";
			 
			 if ($PAdjDtId == '') {
				echo " <td colspan='5'><input type='text' name='txtItemCode' id='txtItemCode' value='$txtItemCode'  maxlength='20' style='font-size:12px; width:110px; height:20px;' onkeydown='return kd(event)'>
					   <input type='text' name='txtItemDesc' id='txtItemDesc' value='$txtItemDesc' style='font-size:12px; width:270px; height:20px;' />
					   <label><span class='style12'><img src='img/btnopen.jpg' title=' Select Item '  width='15' height='17' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistItems(1); ' /></span></label></td>";
			 } else {
				echo " <td colspan='5'><input type='hidden' name='txtItemCode' id='txtItemCode' value='$txtItemCode' /><input type='hidden' name='txtItemDesc' id='txtItemDesc' value='$txtItemDesc' />
					   <b>$txtItemCode &nbsp;&nbsp; $txtItemDesc</b></td>";
			 }	
			 
echo"     </tr>";


if ($Module_ProjectDt == 1 || $Module_CostCenterDt == 1) {
	echo"   <tr bgcolor='#F7F7F7'>";

	if ($Module_ProjectDt == 1) {
		echo" <td align='left'><span class='style12'>Project&nbsp;<span class='style12'>*</span></span></td>
			  <td align='left'> <span class='style12'>
				<input type='text' name='txtProjectCodeDt' id='txtProjectCodeDt' value='$txtProjectCodeDt' style='width:120px;' maxlength='15' readonly /></span>
				<label><span class='style12'><img src='img/btnopen.jpg' title=' Select Project ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
	} else {
		echo" <td align='left'>&nbsp;</td>
			  <td align='left'><input type='hidden' name='txtProjectCodeDt' id='txtProjectCodeDt' value='' /></td>";
	}

	if ($Module_CostCenterDt == 1) {		  
		echo" <td align='left'><span class='style12'>Costcenter&nbsp;<span class='style12'>*</span></span></td>
			  <td align='left'><span class='style12'>
				<input type='text' name='txtCostCentCodeDt' id='txtCostCentCodeDt' value='$txtCostCentCodeDt' style='width:130px;' maxlength='15' readonly /></span>
				<label><span class='style12'><img src='img/btnopen.jpg' title=' Select Costcenter ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick='showlistCostcenter(1); ' /></span></label></td>";
	} else {
		echo" <td align='left'>&nbsp;</td>
			  <td align='left'><input type='hidden' name='txtCostCentCodeDt' id='txtCostCentCodeDt' value='' /></td>";

	}
	echo"    </td><td colspan='2'>&nbsp;</td>";			
	echo"   </tr>";
}


if ($Module_ExpireDate == 1) {
	echo" <tr bgcolor='#F7F7F7' height='25'>
             <td valign='center' align='left' ><span class='style12'>Batch No</span></td>
			 <td>";
			 
	if ($AdjustType == 'I') {		 
		echo"	<input type='text' name='txtAdjDtBatchNo' value='".htmlspecialchars($txtAdjDtBatchNo, ENT_QUOTES)."'  maxlength='40' style='font-size:12px; width:120px; height:20px;' ></td>";
	} else {
		echo"	<input type='text' name='txtAdjDtBatchNo' value='".htmlspecialchars($txtAdjDtBatchNo, ENT_QUOTES)."'  maxlength='40' style='font-size:12px; width:120px; height:20px;' readonly >
				<label><span class='style12'><img src='img/btnopen.jpg' title='Select Batch No'  width='15' height='17' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistBatchNo(1); ' /></span></label></td>";
	}
	
	echo"		<td valign='center' align='left' ><span class='style12'>Expire Date</span></td>
				<td><input type='text' name='txtAdjDtExpireDate' value='$txtAdjDtExpireDate' maxlength='10' style='font-size:12px; width:90px; height:20px;'>
					<a HREF='#' onClick=\"displayCalendar(document.adjustmentdt.txtAdjDtExpireDate,'dd/mm/yyyy',this); return false;\" NAME='anchor1' ID='anchor1'><img src='./img/cal.gif' border=0 align=center></a></td>"; 	 
	echo"    </td><td colspan='2'>&nbsp;</td>";			
	echo"   </tr>";
} else {
	echo" <input type='hidden' name='txtAdjDtExpireDate' value='$txtAdjDtExpireDate'>";
	echo" <input type='hidden' name='txtAdjDtBatchNo' value='$txtAdjDtBatchNo'>";
}



echo"	  <tr bgcolor='#F7F7F7' height='25'>		  
			 <td valign='center' align='left' ><span class='style12'>Quantity&nbsp;<span class='style26'>*</span></span></td>
			 <td align='left'>
				<input type='text' name='txtAdjDtQty' id='txtAdjDtQty' value='$txtAdjDtQty' maxlength='20' onBlur='CalcAdjDtTotal(this.id,$DecimalBase);' onchange='CalcQty2($Module_Unit1Method,$i_unitcoef,1);' style='text-align:right; font-size:12px; width:90px; height:20px;' >";
echo"			<b>&nbsp;$txtItemUnit1</b></td>";

if ($Module_DoubleUnit == 1){
	echo"<td valign='center' align='left' ><span class='style12'>Unit2 Qty</span></td>
		 <td><input type='text' name='txtAdjDtQty2' id='txtAdjDtQty2' value='$txtAdjDtQty2' maxlength='20' onchange='CalcQty2($Module_Unit1Method,$i_unitcoef,2);' style='text-align:right; font-size:12px; width:90px; height:20px;' >
			 <b>&nbsp;$txtItemUnit2</b></td>";
} else {
	echo "<td colspan='2'><input type='hidden' name='txtAdjDtQty2' id='txtAdjDtQty2' value='$txtAdjDtQty2'></td>";
}

echo"    <td colspan='2'>&nbsp;</td>";
echo"	</tr>";
		  
if ($FI_ShowCostPrice == 1) {		  
	echo" <tr bgcolor='#F7F7F7' height='25'>
			 <td valign='center' align='left' ><span class='style12'>Cost Price&nbsp;<span class='style26'>*</span></span></td>
		     <td align='left' colspan='3'><input type='text' name='txtAdjDtPrice' id='txtAdjDtPrice' value='$txtAdjDtPrice' maxlength='20' onBlur='CalcAdjDtTotal(this.id,$DecimalBase);'  style='text-align:right; font-size:12px; width:90px; height:20px;' ></td>
			 <td colspan='2'>&nbsp;</td>
		  </tr>
		  <tr bgcolor='#F7F7F7' height='25'>
			 <td valign='center' align='left' ><span class='style12'>Total</span></td>	 
			 <td align='left' colspan='3'><input type='text' name='txtAdjDtTotal' value='$txtAdjDtTotal' maxlength='20' style='text-align:right; font-size:12px; width:90px; height:20px;' readonly></td>
			 <td colspan='2'>&nbsp;</td>
		  </tr>";
} else {
	echo" <input type='hidden' name='txtAdjDtPrice' value='$txtAdjDtPrice' >
		  <input type='hidden' name='txtAdjDtTotal' value='$txtAdjDtTotal' >";

}
		  	 
echo"	  <tr bgcolor='#F7F7F7' height='35'>
		     <td colspan='6' align='center' bgcolor=#D8D8D8>
			    <input type='button' id='btnSubmitRecord' name='btnSubmitRecord'  value='Submit Record'  onclick='SubmitRecord($i_expire)' $style title='Submit Record'></td>
			 
		  </tr>
        </table>";

	

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

HERE;

?>