<?php

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


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

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

$query_module  = "select Module_SerialNoOut form module";
$result_module = mysql_query($query_module, $connection);
$row_module    = mysql_fetch_array($result_module);	
extract($row_module);					

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 == 'insert' && $ItemSerialNo != '') {

	$query= " Select Count(SerialNo_Code) ".
			" From Temp_Purchasesserialno ".
			" where Temp_Purchasesserialno.PurchaseDt_ID = '".$SaDtId."' ".
			" And Journal_Type = 'SI' ";
	
	$result = selectData($connection, $query);
	$SerialCount = $result[0];	
	/*
if($Module_SerialNoOut == 1){	
$SerialCount = $ItemQty;}
*/
	if ($SerialCount == '') $SerialCount = 0;
	
			
	if ($SerialCount < $ItemQty ) {
	
		$query= " Select Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
				" From Purchasesserialno ".
				" Inner Join DeliveryDt on DeliveryDt.DeliveryDt_ID = Purchasesserialno.PurchaseDt_ID ".
				" Inner Join Temp_SalesDt on Temp_SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_ID ".
				" where Purchasesserialno.Item_Code = '".$ItemCode."' ".
				" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
				" And Temp_SalesDt.SaleDt_ID = '".$SaDtId."' ".
				" And Temp_SalesDt.Journal_Type = 'SI' ".
				" And DeliveryDt.Journal_Type = 'DI' ";
				  
		$result = selectData($connection, $query);
		$SerialNoExists = $result[0];
		//echo $query; exit;
		$IsAvailable = 0;
		$SelectedSerialID = 0;
		$SelectedSerialQty     = 0;
		$SelectedSerialQtySold = 0;
		
		if ($SerialNoExists != '') {
			if ($ItemWhCode != '' && isset($ItemWhCode)) {
			
				$sub_query= " Select *  ".
							" From temp_purchasesserialno ".
							" where Item_Code = '".$ItemCode."' ".
							" And SerialNo_Code =  '".$ItemSerialNo."' ".
							" And Journal_Type in ('SI')";
				 //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 SalesDt on Purchasesserialno.PurchaseDt_id = SalesDt.SaleDt_ID ".
								" Where SalesDt.Sale_id = ".$SaId.
								" And Purchasesserialno.Item_Code = '".$ItemCode."' ".
								" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
								" And Purchasesserialno.Warehouse_Code =  '".$ItemWhCode."' ".
								" And Purchasesserialno.Journal_Type = 'SI' ".
								" Union ".
								" Select Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0) As SerialNo_QuantitySold, 2 As OrderColumn  ".
								" From Purchasesserialno ".
								" Inner Join DeliveryDt on DeliveryDt.DeliveryDt_ID = Purchasesserialno.PurchaseDt_ID ".
								" Inner Join Temp_SalesDt on Temp_SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_ID ".
								" where Purchasesserialno.Item_Code = '".$ItemCode."' ".
								" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
								" And Purchasesserialno.Warehouse_Code =  '".$ItemWhCode."' ".
								" And Temp_SalesDt.SaleDt_ID = '".$SaDtId."' ".
								" And Temp_SalesDt.Journal_Type = 'SI' ".
								" And DeliveryDt.Journal_Type = 'DI' ".
								" 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($Module_SerialNoOut == 1){
						$RecCount = 1;
						$sub_row[1] = 1;
						$sub_row[3] = 1;
						$sub_row[4] = 0;
						$sub_row[0] = 0;
						
					}
					
					if ($RecCount == 0) {
						$IsAvailable = 1;
						$message  = "Insert not allowed, Serial No (".$ItemSerialNo.") is not available in the warehouse (".$ItemWhCode.") . "; 
					}	
					else {
						
						if ($sub_row[1] == 1)
						{
							$sub_query= " Select Serial_ID, ifNull(SerialNo_Used,0), Purchasesserialno.warehouse_code, ifNull(SerialNo_Quantity,1), ifNull(SerialNo_QuantitySold,0)  ".
										" From Purchasesserialno ".
										" Inner Join DeliveryDt on DeliveryDt.DeliveryDt_ID = Purchasesserialno.PurchaseDt_ID ".
										" Inner Join Temp_SalesDt on Temp_SalesDt.RelatedDt_ID = DeliveryDt.DeliveryDt_ID ".
										" where Purchasesserialno.Item_Code = '".$ItemCode."' ".
										" And Purchasesserialno.SerialNo_Code =  '".$ItemSerialNo."' ".
										" And Purchasesserialno.Warehouse_Code =  '".$ItemWhCode."' ".
										" And ifNull(SerialNo_Used,0) = 0 ".
										" And Temp_SalesDt.SaleDt_ID = '".$SaDtId."' ".
										" And Temp_SalesDt.Journal_Type = 'SI' ".
										" And DeliveryDt.Journal_Type = 'DI' ";
								
							//echo $sub_query;exit;			
							$sub_result=mysql_query($sub_query,$connection)  or die(mysql_error());
							$sub_row=mysql_fetch_array($sub_result);
							$RecCount=mysql_num_rows($sub_result);
							
							if ($RecCount == 0) {
								$IsAvailable = 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, duplicate serial no. "; 
				}	
			}
			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, Item Qty[$ItemQty] Exceeded. "; 
	}
	
	if ($IsAvailable == 0)
	{
		fbegin();
		$SerId = get_nextsequence('Serial_Id','',$connection);	
		fcommit();
					
		fbegin();
		$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, SaleDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
				 " VALUES ( ".$SerId.", 'SI', $SaDtId, $SaDtId, '".$ItemCode."', '".$ItemSerialNo."', 0, '".$SelectedSerialID."', '".$SelectedSerialQty."', $SelectedSerialQtySold + 1, '".$ItemWhCode."', '".$HTTP_SESSION_VARS['useraccount']."' ) ";
									 
		$result=mysql_query($query,$connection);
						
		if ($result){
			
			/*$query = " UPDATE temp_salesdt SET ".
					 " SaleDt_Quantity =  (ifNull(SaleDt_Quantity,0) + 1) ".
					 " WHERE SaleDt_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 ($Mode == 'delete' && $SerialId != '') {
	
	
	$query = " SELECT ifNull(SerialNo_Used, 0) As SerialNo_Used from temp_purchasesserialno ".
	         " WHERE Serial_ID = ".$SerialId;
			 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ";
	$result = selectData($connection, $query);
	$SerialNoUsed = $result[0];
	
	if ($SerialNoUsed == 0) {
		fbegin();
		
		$query = " DELETE from temp_purchasesserialno ".
				 " WHERE Serial_ID = ".$SerialId.
				 //" AND Logged_Code = '".$HTTP_SESSION_VARS['useraccount']."' ".
				 " AND ifNull(SerialNo_Used, 0) = 0  ";
		
		$result=mysql_query($query,$connection);
			
		if ($result){
			/*$query = " UPDATE temp_salesdt SET ".
					 " SaleDt_Quantity =  (ifNull(SaleDt_Quantity,0) - 1) ".
					 " WHERE SaleDt_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. "; 
	}	
}


$message = ereg_replace(' ','%20',$message);
$ItemWhCode = ereg_replace('&','%26',$ItemWhCode);
header ("Location: Form_SalesSerialNo.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;

?>