<?php

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


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

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");
$querysetup="select base1, base2, grid_color1, grid_color2, serialNb_quantity_setup 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_DeliveryWithSorder,0) As Module_DeliveryWithSorder, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ".
			 " ifNull(Module_SerialNoOut,0) As Module_SerialNoOut ".
			 " From Module ";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
} 
$ItemQty    	= $_POST['ItemQty']; if ($ItemQty == ""){$ItemQty = $_GET["ItemQty"];}
$serialtodelete = $_POST['txttodelete'];					
print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

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


if($Mode == 'insertgenerate' ){ 
$t=0; $invoicedserialnbr='';
	for($i=$txtfromserialnb;$i<=$txttoserialnb;$i++){
		$query= " Select Count(SerialNo_Code) ".
			" From Temp_Purchasesserialno ".
			" where Temp_Purchasesserialno.PurchaseDt_ID = '".$SaDtId."' ".
			" And Journal_Type = 'DI' ";
	
	$result = selectData($connection, $query);
	$SerialCount = $result[0];		
	if ($SerialCount == '') $SerialCount = 0;
	
			
	if ($Module_DeliveryWithSorder == 0 || ($Module_DeliveryWithSorder == 1 && $SerialCount < $ItemQty )) {
	
		$query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
				" From purchasesserialno ".
				" where Item_Code = '".$ItemCode."' ".
				" And SerialNo_Code =  '".$txtprefixserialnb."".$i."' ".
				" And Journal_Type in ('PI','DR','TR','AI','PD')";
				  
		$result = selectData($connection, $query);
		$SerialNoExists = $result[0];
		//secho $query; exit;
		$IsAvailable = 0;
		$SelectedSerialID = 0;
		$SelectedSerialQty     = 0;
		$SelectedSerialQtySold = 0;
		
		if ($SerialNoExists != '' || $Module_SerialNoOut == 1) {
			if ($ItemWhCode != '' && isset($ItemWhCode)) {
			
				$sub_query= " Select SerialNo_Code  ".
							" From temp_purchasesserialno ".
							" where Item_Code = '".$ItemCode."' ".
							" And SerialNo_Code =  '".$txtprefixserialnb."".$i."' ".
							" And Journal_Type in ('DI') ".
							" Union ".
							" Select SerialNo_Code  ".
							" From purchasesserialno ".
							" where Item_Code = '".$ItemCode."' ".
							" And SerialNo_Code =  '".$txtprefixserialnb."".$i."' ".
							" And Warehouse_Code =  '".$ItemWhCode."' ".
							" And Journal_Type in ('DI')";
				//echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
				$RecCount=mysql_num_rows($sub_result);
			
				if ($RecCount == 0 || $RecCount == '') {
					$sub_query= " Select RelatedSerial_Id As Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) - 1 As SerialNo_QuantitySold, 1 As OrderColumn ".
								" From purchasesserialno ".
								" Inner Join DeliveryDt on Purchasesserialno.PurchaseDt_id = DeliveryDt.DeliveryDt_ID ".
								" Where Delivery_id = ".$SaId.
								" And Purchasesserialno.Item_Code = '".$ItemCode."' ".
								" And Purchasesserialno.SerialNo_Code =  '".$txtprefixserialnb."".$i."' ".
								" And Purchasesserialno.Warehouse_Code =  '".$ItemWhCode."' ".
								" And Purchasesserialno.Journal_Type = 'DI' ".
								" Union ".
								" Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, 2 As OrderColumn  ".
								" From purchasesserialno ".
								" where Item_Code = '".$ItemCode."' ".
								" And SerialNo_Code =  '".$txtprefixserialnb."".$i."' ".
								" And Warehouse_Code =  '".$ItemWhCode."' ".
								" And Journal_Type in ('PI','DR','TR','AI','PD') ".
								" Order by OrderColumn ";
								
								
					//echo $sub_query; exit;			
					$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
					$sub_row=mysql_fetch_array($sub_result);
					$RecCount=mysql_num_rows($sub_result);
					
					if ($RecCount == 0 && $Module_SerialNoOut != 1) {
						$IsAvailable = 1;
						$notaddserialnbr = $txtprefixserialnb."".$i.",".$notaddserialnbr;
						if($t == 10) $notaddserialnbr = $notaddserialnbr."<br>";
						$messagerr  = "Insert not allowed, Serial No (".$notaddserialnbr.") is not available in the warehouse (".$ItemWhCode.") . "; 
						$t++;
					}
					else if ($RecCount == 0 && $Module_SerialNoOut == 1) {
						$SelectedSerialID      = 'null';
						$SelectedSerialQty     = 1;
						$SelectedSerialQtySold = 0;
						$IsAvailable = 0;
					}		
					else {
						
						if ($sub_row[1] == 1)
						{
							$sub_query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
										" From purchasesserialno ".
										" where Item_Code = '".$ItemCode."' ".
										" And SerialNo_Code =  '".$txtprefixserialnb."".$i."' ".
										" And Warehouse_Code =  '".$ItemWhCode."' ".
										" And ifNull(SerialNo_Used,0) = 0 ".
										" And Journal_Type in ('PI','DR','TR','AI','PD')";
							$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
							$sub_row=mysql_fetch_array($sub_result);
							$RecCount=mysql_num_rows($sub_result);
							
							if ($RecCount == 0) {
								$IsAvailable = 1;
								$notaddserialnbr = $txtprefixserialnb."".$i.",".$notaddserialnbr;
								if($t == 10) $notaddserialnbr = $notaddserialnbr."<br>";
								$messagerr  = "Insert not allowed, Serial No (".$notaddserialnbr.") is used in warehouse (".$ItemWhCode."). "; 
								$t++;
							}  else {
								$SelectedSerialID      = $sub_row[0];
								$SelectedSerialQty     = $sub_row[3];
								$SelectedSerialQtySold = $sub_row[4];
								$IsAvailable = 0;
							}	
						
						} else {
							$SelectedSerialID      = $sub_row[0];
							$SelectedSerialQty     = $sub_row[3];
							$SelectedSerialQtySold = $sub_row[4];
							$IsAvailable = 0;
						}	

					}	
				}
				else {
					$IsAvailable = 1;
					$invoicedserialnbr = $txtprefixserialnb."".$i.",".$invoicedserialnbr;
					$messagerr  = "Insert not allowed, serial no (".$invoicedserialnbr.") already invoiced.<br> "; 
				}	
			}
			else {
				$IsAvailable = 1;
				$messagerr  = "Insert not allowed, warehouse is empty.<br> "; 
			}	
		}
		else {
			$IsAvailable = 1;
			$notaddserialnbr = $txtprefixserialnb."".$i.",".$notaddserialnbr;
			if($t == 10) $notaddserialnbr = $notaddserialnbr."<br>";
			$messagerr  = "Insert not allowed, Serial No (".$notaddserialnbr.") is not available. "; 
			$t++;
		}
	}	
	else {
			$IsAvailable = 1;
			$message  = "Insert not allowed, Ordered Qty[$ItemQty] Exceeded.<br> "; 
	}
	
	if ($IsAvailable == 0)
	{
		//fbegin();
		$SerId = get_nextsequence('Serial_Id','',$connection);	
		//fcommit();
					
		//fbegin();
		$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
				 " VALUES ( ".$SerId.", 'DI', $SaDtId, $SaDtId, '".$ItemCode."', '".$txtprefixserialnb."".$i."', 0, ".$SelectedSerialID.", '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$ItemWhCode."', '".$_SESSION['useraccount']."' ) ";
		
		$result=mysql_query($query,$connection);
					
		if ($result){
			//if ($Module_DeliveryWithSorder == 0) {
				$query = " UPDATE temp_deliverydt SET ".
						 " DeliveryDt_Quantity =  (ifNull(DeliveryDt_Quantity,0) + 1) ";
				
				if ($Module_DoubleUnit == 1) {
					$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
				}
				$query = $query." WHERE DeliveryDt_id = '".$SaDtId."' ";
				//echo $query."<br>";exit;				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	
			//}
			
			$message = "Serial no inserted successfully.";
		//	fcommit();
		} else {
			$message  = mysql_error(); 
			//frollback();
		}
	
	}
	} 

	if($serialNb_quantity_setup == 1){
		$queryserial = "select * from temp_purchasesserialno where PurchaseDt_ID = $SaDtId "; 
		$resserial = mysql_query($queryserial, $connection);
		$rwserial = mysql_num_rows($resserial);
		$query = " UPDATE temp_deliverydt SET ".
						 " DeliveryDt_Quantity =  $rwserial ";
				
				if ($Module_DoubleUnit == 1) {
					$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
				}
				$query = $query." WHERE DeliveryDt_id = '".$SaDtId."' ";
				//echo $query."<br>";exit;				
				$res = mysql_query($query, $connection); 	
	}
} 

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

	$query= " Select Count(SerialNo_Code) ".
			" From Temp_Purchasesserialno ".
			" where Temp_Purchasesserialno.PurchaseDt_ID = '".$SaDtId."' ".
			" And Journal_Type = 'DI' ";
	
	$result = selectData($connection, $query);
	$SerialCount = $result[0];		
	if ($SerialCount == '') $SerialCount = 0;
	
			
	if ($Module_DeliveryWithSorder == 0 || ($Module_DeliveryWithSorder == 1 && $SerialCount < $ItemQty )) {
	
		$query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
				" From purchasesserialno ".
				" where Item_Code = '".$ItemCode."' ".
				" And SerialNo_Code =  '".$ItemSerialNo."' ".
				" And Journal_Type in ('PI','DR','TR','AI','PD')";
				  
		$result = selectData($connection, $query);
		$SerialNoExists = $result[0];
		//echo $query; exit;
		$IsAvailable = 0;
		$SelectedSerialID = 0;
		$SelectedSerialQty     = 0;
		$SelectedSerialQtySold = 0;
		
		if ($SerialNoExists != '' || $Module_SerialNoOut == 1) {
			if ($ItemWhCode != '' && isset($ItemWhCode)) {
			
				$sub_query= " Select SerialNo_Code  ".
							" From temp_purchasesserialno ".
							" where Item_Code = '".$ItemCode."' ".
							" And SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Journal_Type in ('DI') ".
							" Union ".
							" Select SerialNo_Code  ".
							" From purchasesserialno ".
							" where Item_Code = '".$ItemCode."' ".
							" And SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Warehouse_Code =  '".$ItemWhCode."' ".
							" And Journal_Type in ('DI')";
				 //echo $sub_query; exit;	 
				$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
				$RecCount=mysql_num_rows($sub_result);
			
				if ($RecCount == 0 || $RecCount == '') {
					$sub_query= " Select RelatedSerial_Id As Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) - 1 As SerialNo_QuantitySold, 1 As OrderColumn ".
								" From purchasesserialno ".
								" Inner Join DeliveryDt on Purchasesserialno.PurchaseDt_id = DeliveryDt.DeliveryDt_ID ".
								" Where Delivery_id = ".$SaId.
								" And Purchasesserialno.Item_Code = '".$ItemCode."' ".
								" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
								" And Purchasesserialno.Warehouse_Code =  '".$ItemWhCode."' ".
								" And Purchasesserialno.Journal_Type = 'DI' ".
								" Union ".
								" Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, 2 As OrderColumn  ".
								" From purchasesserialno ".
								" where Item_Code = '".$ItemCode."' ".
								" And SerialNo_Code =  '".$ItemSerialNo."' ".
								" And Warehouse_Code =  '".$ItemWhCode."' ".
								" And Journal_Type in ('PI','DR','TR','AI','PD') ".
								" Order by OrderColumn ";
								
								
					//echo $sub_query; exit;			
					$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
					$sub_row=mysql_fetch_array($sub_result);
					$RecCount=mysql_num_rows($sub_result);
					
					if ($RecCount == 0 && $Module_SerialNoOut != 1) {
						$IsAvailable = 1;
						$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available in the warehouse (".$ItemWhCode.") . "; 
					}
					else if ($RecCount == 0 && $Module_SerialNoOut == 1) {
						$SelectedSerialID      = 'null';
						$SelectedSerialQty     = 1;
						$SelectedSerialQtySold = 0;
						$IsAvailable = 0;
					}		
					else {
						
						if ($sub_row[1] == 1)
						{
							$sub_query= " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
										" From purchasesserialno ".
										" where Item_Code = '".$ItemCode."' ".
										" And SerialNo_Code =  '".$ItemSerialNo."' ".
										" And Warehouse_Code =  '".$ItemWhCode."' ".
										" And ifNull(SerialNo_Used,0) = 0 ".
										" And Journal_Type in ('PI','DR','TR','AI','PD')";
							$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
							$sub_row=mysql_fetch_array($sub_result);
							$RecCount=mysql_num_rows($sub_result);
							
							if ($RecCount == 0) {
								$IsAvailable = 1;
								$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is used in warehouse (".$ItemWhCode."). "; 
							}  else {
								$SelectedSerialID      = $sub_row[0];
								$SelectedSerialQty     = $sub_row[3];
								$SelectedSerialQtySold = $sub_row[4];
								$IsAvailable = 0;
							}	
						
						} else {
							$SelectedSerialID      = $sub_row[0];
							$SelectedSerialQty     = $sub_row[3];
							$SelectedSerialQtySold = $sub_row[4];
							$IsAvailable = 0;
						}	

					}	
				}
				else {
					$IsAvailable = 1;
					$message  = "Insert not allowed, serial no already invoiced. "; 
				}	
			}
			else {
				$IsAvailable = 1;
				$message  = "Insert not allowed, warehouse is empty. "; 
			}	
		}
		else {
			$IsAvailable = 1;
			$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available. "; 
		}
	}	
	else {
			$IsAvailable = 1;
			$message  = "Insert not allowed, Ordered Qty[$ItemQty] Exceeded. "; 
	}
	
	if ($IsAvailable == 0)
	{
		fbegin();
		$SerId = get_nextsequence('Serial_Id','',$connection);	
		fcommit();
					
		fbegin();
		$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
				 " VALUES ( ".$SerId.", 'DI', $SaDtId, $SaDtId, '".$ItemCode."', '".$ItemSerialNo."', 0, ".$SelectedSerialID.", '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$ItemWhCode."', '".$_SESSION['useraccount']."' ) ";
									 
		$result=mysql_query($query,$connection);
						
		if ($result){
			//if ($Module_DeliveryWithSorder == 0) {
			/*	$query = " UPDATE temp_deliverydt SET ".
						 " DeliveryDt_Quantity =  (ifNull(DeliveryDt_Quantity,0) + 1) ";
				
				if ($Module_DoubleUnit == 1) {
					$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
				}
				$query = $query." WHERE DeliveryDt_id = '".$SaDtId."' ";
				//echo $query."<br>";exit;				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	*/
			//}
			
			$message = "Serial no (".$ItemSerialNo.") inserted successfully.";
			fcommit();
		} else {
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	if($serialNb_quantity_setup == 1){
		$queryserial = "select * from temp_purchasesserialno where PurchaseDt_ID = $SaDtId "; 
		$resserial = mysql_query($queryserial, $connection);
		$rwserial = mysql_num_rows($resserial);
		$query = " UPDATE temp_deliverydt SET ".
						 " DeliveryDt_Quantity =  $rwserial ";
				
				if ($Module_DoubleUnit == 1) {
					$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
				}
				$query = $query." WHERE DeliveryDt_id = '".$SaDtId."' ";
				//echo $query."<br>";exit;				
				$res = mysql_query($query, $connection); 	
	}
}

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

else if ($Mode == 'load' && $SaDtId != '' && $SaId != '') {

	$vString  = $SRString;
	$vSeqFrom = $SRSeqFrom;
	$vSeqTo   = $SRSeqTo;
	
	$vLenSeqFrom = StrLen($vSeqFrom);
	$vLenSeqTo	 = StrLen($vSeqTo);
	$vRange      = $vSeqTo - $vSeqFrom;
	
	$sub_query = " Select Item_code, Warehouse_Code, DeliveryDt_Quantity ".
				 " From Temp_DeliveryDt As DeliveryDt ".
				 " Where Delivery_ID = '".$SaId."' ".
				 " And DeliveryDt_ID = '".$SaDtId."' ";
	$sub_result = selectData($connection, $sub_query);	    

	$ItemCode	 = $sub_result[0];
	$ItemWhCode  = $sub_result[1];
	//$ItemQty	 = $sub_result[2];
	
	if ($ItemCode != '' && $ItemWhCode != '') {
		
		$vExistsSerials		 = '';
		$vUnavailableSerials = '';
		$vUsedSerials		 = '';
		
		for ($i = $vSeqFrom; $i <= $vSeqTo; $i++) {
		
			$ItemSerialNo = $vString. str_pad($i, $vLenSeqTo, '0', STR_PAD_LEFT);
			//echo $ItemSerialNo."<br>";
			
			$sub_query1 = " SELECT Count(*) As SerialNoCount From ".
						  " ( SELECT SerialNo_Code from temp_purchasesserialno ".
						  "   WHERE SerialNo_Code = '".$ItemSerialNo."' ".
						  "   AND Item_Code = '".$ItemCode."' ".
						  "   AND Journal_Type = 'DI' ".
						  "   UNION ".
						  "   SELECT SerialNo_Code from purchasesserialno ".
						  "   WHERE SerialNo_Code = '".$ItemSerialNo."' ".
						  "   AND Item_Code = '".$ItemCode."' ".
						  "   AND ifNull(SerialNo_Used,0) = 0 ".
						  "   AND Journal_Type = 'DI' ".
						  "   AND PurchaseDt_ID != ".$PurDtId.
						  " ) Q1 ";
			$sub_result1 = selectData($connection, $sub_query1);
			$SerialNoExists = $sub_result1[0];
			
			if ($SerialNoExists == 0) {
			
				$sub_query2 = " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
							  " From purchasesserialno ".
							  " where Item_Code = '".$ItemCode."' ".
							  " And SerialNo_Code =  '".$ItemSerialNo."' ".
							  " And Warehouse_Code =  '".$ItemWhCode."' ".
							  " And Journal_Type in ('PI','DR','TR','AI','PD')";
						  
				$sub_result2 = selectData($connection, $sub_query2);
				$SerialNoAvailable = $sub_result2[0];
				//echo $query; exit;
				$IsAvailable = 1;
				$SelectedSerialID 	   = 0;
				$SelectedSerialQty     = 0;
				$SelectedSerialQtySold = 0;
				
				if ($SerialNoAvailable != '') {

					$sub_query3 = " Select RelatedSerial_Id As Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) - 1 As SerialNo_QuantitySold, 1 As OrderColumn ".
								  " From purchasesserialno ".
								  " Inner Join DeliveryDt on Purchasesserialno.PurchaseDt_id = DeliveryDt.DeliveryDt_ID ".
								  " Where Delivery_id = ".$SaId.
								  " And Purchasesserialno.Item_Code = '".$ItemCode."' ".
								  " And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
								  " And Purchasesserialno.Warehouse_Code =  '".$ItemWhCode."' ".
								  " And Purchasesserialno.Journal_Type = 'DI' ".
								  " Union ".
								  " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, 2 As OrderColumn  ".
								  " From purchasesserialno ".
								  " where Item_Code = '".$ItemCode."' ".
								  " And SerialNo_Code =  '".$ItemSerialNo."' ".
								  " And Warehouse_Code =  '".$ItemWhCode."' ".
								  " And Journal_Type in ('PI','DR','TR','AI','PD') ".
								  " Order by OrderColumn ";
										
										
					//echo $sub_query3; exit;			
					$sub_result3=mysql_query($sub_query3,$connection)  or die(mysql_error());
					$sub_row3=mysql_fetch_array($sub_result3);
					
					if ($sub_row3[1] == 1)
					{
						$sub_query4 = " Select Serial_ID, ifNull(SerialNo_Used,0), warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
									  " From purchasesserialno ".
									  " where Item_Code = '".$ItemCode."' ".
									  " And SerialNo_Code =  '".$ItemSerialNo."' ".
									  " And Warehouse_Code =  '".$ItemWhCode."' ".
									  " And ifNull(SerialNo_Used,0) = 0 ".
									  " And Journal_Type in ('PI','DR','TR','AI','PD')";
						$sub_result4=mysql_query($sub_query4,$connection)  or die(mysql_error());
						$sub_row4=mysql_fetch_array($sub_result4);
						$RecCount=mysql_num_rows($sub_result4);
									
						if ($RecCount == 0) {
							$IsAvailable = 0;
							$vUsedSerials = $vUsedSerials.', '.$ItemSerialNo;
						}  else {
							$SelectedSerialID      = $sub_row4[0];
							$SelectedSerialQty     = $sub_row4[3];
							$SelectedSerialQtySold = $sub_row4[4];
							$IsAvailable = 1;
						}	
								
					} else {
						$SelectedSerialID      = $sub_row3[0];
						$SelectedSerialQty     = $sub_row3[3];
						$SelectedSerialQtySold = $sub_row3[4];
						$IsAvailable = 1;
					}	
					
				}
				else {
					$IsAvailable = 0;
					$vUnavailableSerials = $vUnavailableSerials.', '.$ItemSerialNo;
				}
				
				if ($IsAvailable == 1)
				{
					fbegin();
					$SerId = get_nextsequence('Serial_Id','',$connection);	
					fcommit();
								
					fbegin();
					$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, DeliveryDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
							 " VALUES ( ".$SerId.", 'DI', $SaDtId, $SaDtId, '".$ItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$ItemWhCode."', '".$_SESSION['useraccount']."' ) ";
												 
					$result=mysql_query($query,$connection);
									
					if ($result){
						//$message = "Generating serials done successfully.";
						fcommit();
					} else {
						$message  = mysql_error(); 
						frollback();
					}
				
				}
	
			} else {
				$vExistsSerials = $vExistsSerials.', '.$ItemSerialNo;
			}	
		}	
		
		if ($vExistsSerials	!= '')
			$message = " Cannot load following serial(s), already exist(s): <br>". substr($vExistsSerials, 2);
		if ($vUnavailableSerials != '')
			$message = $message."<br>"." Cannot load following serial(s), not available in the warehouse (".$ItemWhCode."): <br>". substr($vUnavailableSerials, 2);	
		if ($vUsedSerials != '')
			$message = $message."<br>"." Cannot load following serial(s), are used in the warehouse (".$ItemWhCode."): <br>". substr($vUsedSerials, 2);	

	} else {
		$message = " Cannot load serials, Item or Warehouse is empty.";
	}
	
}

/* if($Mode =='editqty1'){ 
		$query = " UPDATE temp_deliverydt SET ".
						 " DeliveryDt_Quantity =  $QItemQty ";
				
				if ($Module_DoubleUnit == 1) {
					$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
				}
				$query = $query." WHERE DeliveryDt_id = '".$SaDtId."' ";
				//echo $query."<br>";exit;				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	
			echo 1;
			exit;
			

} */

if($Mode == 'deleteall'){
	fbegin();
		foreach($serialtodelete as $serialid){
		$query = " DELETE from temp_purchasesserialno ".
				 " WHERE Serial_ID = ".$serialid.
				 //" AND Logged_Code = '".$_SESSION['useraccount']."' ".
				 " AND ifNull(SerialNo_Used, 0) = 0  ";
		
		$result=mysql_query($query,$connection);
		
		if ($result){
			if($serialNb_quantity_setup == 1){
			
				$query = " UPDATE temp_deliverydt SET ".
						 " DeliveryDt_Quantity =  (ifNull(DeliveryDt_Quantity,0) - 1) ";
						 
				if ($Module_DoubleUnit == 1) {
					$query = $query.", Item_Unit2Qty = ifNull(Item_UnitCoef,0)*(ifNull(DeliveryDt_Quantity,0)) ";
				}		 
				$query = $query." WHERE DeliveryDt_id = '".$SaDtId."' ";
				//echo $query."<br>";exit;				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	
			}
			
			$message = "Delete serial no done successfully.";
			fcommit();
		}else{
			$message  = mysql_error(); 
			frollback();
		}			
		}
		
		
}
$message = ereg_replace(' ','%20',$message);
$ItemWhCode = ereg_replace('&','%26',$ItemWhCode);
if($messagerr !='')
header ("Location: Form_DeliverySerialNo.php?SRItemCode=".$ItemCode."&SRItemQty=".$ItemQty."&SRWhCode=".$ItemWhCode."&SRSaDtId=".$SaDtId."&SRSaId=".$SaId."&perpage=".$PerPage."&SRHideSerialNo=".$HideSerialNo."&message=".$message."".$messagerr);
else if ($Mode == "editqty1" )			
	header ("Location: ./Form_DeliverySerialNo.php");
else header ("Location: Form_DeliverySerialNo.php?SRItemCode=".$ItemCode."&SRItemQty=".$ItemQty."&SRWhCode=".$ItemWhCode."&SRSaDtId=".$SaDtId."&SRSaId=".$SaId."&perpage=".$PerPage."&SRHideSerialNo=".$HideSerialNo."&message=".$message);



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

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

HERE;

?>