<?php
session_start();

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

include("config.inc.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");

//Set Time Execution For the Report
ini_set('max_execution_time', $config['ReportTimeExecution']);

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

$transferdt_remark = ereg_replace("'", "\'", trim($transferdt_remark));
$p_transferdt_remark = ereg_replace("'", "\'", trim($p_transferdt_remark));
		
		if ($p_item_quantity=='')
			$p_item_quantity=0;
		
		if ($p_item_sellingprice1=='')
			$p_item_sellingprice1=0;

if (empty($costcent))
		$costcent = 'null';
	else
		$costcent = "'".$costcent."'";
	


	if ($actionmoded=='mi')
	{
		$upd_Tr = "Update temp_transfer set 
					 transfer_date = '".displayParadoxDate(insertDate($transfer_date))."'
					,Transfer_Remark = '".ereg_replace("'","\'",$transfer_remark)."'
					,Project_code1 = '".$fromproject."'
					,Project_code2 = '".$toproject."'			
					,Costcenter_Code = ".$costcent."
					,Driver_Name = '".$drivername."'
					,vehicle_no = '".$vehicle_no."'
					,Transfer_WarehouseFrom = '".$fromwarehouse."'
					,Transfer_WarehouseTo = '".$towarehouse."'
					where transfer_id = ".$transfer_id
					;
		
		
		$upd_TrDT = "Update Temp_Transferdt set 
					transfer_date = '".displayParadoxDate(insertDate($transfer_date))."'
					,TransferDt_WarehouseFrom= '".$fromwarehouse."'
					,TransferDt_WarehouseTo = '".$towarehouse."'
					,Project_code1 = '".$fromproject."'
					,Project_code2 = '".$toproject."'			
					,Costcent_code = ".$costcent."			
					where transfer_id = ".$transfer_id;
					
		$upd_PurSr = "Update Temp_purchasesserialno set Warehouse_code = '".$towarehouse."'
					where transferdt_id in (select transferdt_id from transferdt where transfer_id = ".$transfer_id.")
					";
		
					
		fbegin();			
		$result1=mysql_query($upd_Tr,$connection) or die(mysql_error());
		$result2=mysql_query($upd_TrDT,$connection) or die(mysql_error());
		$result3=mysql_query($upd_PurSr,$connection) or die(mysql_error());
		
			
			$TrRef = get_nextsequence('transfer_reference','',$connection);
			
			$query = "SELECT CopyData_TempTransfer('".$SMode."', ".$transfer_id.",".$TrRef." ,'".$HTTP_SESSION_VARS['useraccount']."') FROM Dual ";
			$result = selectData($connection, $query);
			$result = $result[0];	
			
			
			if ($result != 0){
				fcommit();
				} else{
				$message  = mysql_error(); 
				frollback();
			}
			
		if ($message!='')
		$message = ereg_replace(' ','%20',$message);
		if ($message!='')
		header ("Location: ./Form_Transfer.php?actionmode=post&message=".$message."&transfer_id=".$transfer_id);
		else
		header ("Location: ./Form_Transfer.php?actionmode=post&transfer_id=".$transfer_id);
		exit;		
	}
	else			
	if ($actionmoded=='i')
	{
		if ($transfer_id=='')
			{
				$PTransferId = get_nextsequence('transfer_id','',$connection);	

				$query = "insert into temp_transfer(Transfer_Id,Transfer_Date,Transfer_Remark,Project_code1,Project_code2,Transfer_WarehouseFrom,Transfer_WarehouseTo,Driver_Name,Vehicle_No,Logged_Code,costcenter_code,Transfer_BelongsToGroup,User_account)
						 values
							(".$PTransferId."
							,'".displayParadoxDate(insertDate($transfer_date))."','".ereg_replace("'","\'",$transfer_remark)."','".$fromproject."','".$toproject."','".$fromwarehouse."','".$towarehouse."','".$driver_name."','".$vehicle_no."','".$HTTP_SESSION_VARS['useraccount']."',".$costcent.",".$login_belongstogrp.",'".$HTTP_SESSION_VARS['useraccount']."')";
			
			
			$result=mysql_query($query,$connection) or die(mysql_error());
				if ($result)
					$transfer_id = $PTransferId;
			}
	
	
						$itemexists=0;
						if ($td!='')
							{
								$query = "select transferdt.item_code,item_withserialno
								from transferdt ,items
								where
								transferdt.item_code = items.item_code
								and transfer_id in (select transfer_id from transfer where transfer_id in(".$td."))
								and item_withserialno = 0
								and items.item_code = '".$itemcode."'
								and item_active = 1
								";
								//echo $query;
								//exit;
								$result=mysql_query($query,$connection) or die(mysql_error());
								$itemexists = mysql_num_rows($result);
							}
							
						$query = "select item_code as item_code, item_description as item_description,item_sellingprice1 as item_sellingprice1 from items where item_code = '".$p_item_code."'
									and (item_withserialno=0 or  item_withserialno='')";
						
						$result=mysql_query($query,$connection) or die(mysql_error());
						while($rows=mysql_fetch_array($result)){
								extract($rows);
								}
							$PTransferdt_id = get_nextsequence('transferdt_id','',$connection);	
									$query = "select BASE1 from setup limit 1";
									$result1=mysql_query($query,$connection)	or die( mysql_error());
										while($row=mysql_fetch_array($result1)){
										extract($row);
										}
										
								$query="select curdt_parity from curdt where currency_code='".$BASE1."'  order by curdt_date desc";
								//echo $query;
								$result1=mysql_query($query,$connection)	or die( mysql_error());
								
								while($row=mysql_fetch_array($result1)){
								extract($row);
								}
								$item_sellingprice2=$p_item_sellingprice1/$curdt_parity;
						
						$query = "insert into temp_transferdt(transferdt_id,transfer_id,transfer_date,item_code,transferdt_quantity,TransferDt_Price,transferdt_pricebase1,transferdt_pricebase2
								,TransferDt_WarehouseFrom,TransferDt_WarehouseTo,transferdt_remark,Logged_code,costcent_code) values(
							  '".$PTransferdt_id."'
							  ,'".$transfer_id."'
							  ,'".displayParadoxDate(insertDate($transfer_date))."'
							   ,'".$p_item_code."'						  
							  ,'".$p_item_quantity."'
							  ,".$p_item_sellingprice1."
							  ,".$p_item_sellingprice1."
							  ,".$item_sellingprice2."
							   ,'".$fromwarehouse."'
							  ,'".$towarehouse."'
							  ,'".$p_transferdt_remark."'
							  ,'".$HTTP_SESSION_VARS['useraccount']."'
							  ,".$costcent."
							   )";
						//echo $query."<br>";	  
						
						//echo $item_code." ".$itemexists;
						//exit;
						if ($td!='')
						{
						if ($item_code!='' and $itemexists!=0)
						$result=mysql_query($query,$connection) or die(mysql_error());
						else
						if ($item_code!='' and $itemexists==0)
						$message='Error:Item%20not%20exists.';
						else
						if ($item_code=='' and $itemexists!=0)
						$message='Error:Item%20with%20serial.';
						else
						if ($item_code=='' and $itemexists==0)
						$message='Error:Item%20with%20serial%20and%20Item%20not%20exists.';
						}
						else /// not in load mode
						{
						if ($item_code!='' )
						$result=mysql_query($query,$connection) or die(mysql_error());
						else
						if ($item_code!='' )
						$message='Error:Item%20not%20exists.';
						else
						if ($item_code=='' )
						$message='Error:Item%20with%20serial.';
						}
						
						$transfer_remark = ereg_replace(" ","%20",$transfer_remark);			
						$transferdt_remark = ereg_replace(" ","%20",$transferdt_remark);			
						$fromwarehouse = ereg_replace("&","%26",$fromwarehouse);			
						$towarehouse = ereg_replace("&","%26",$towarehouse);			
						$driver_name = ereg_replace(" ","%20",$driver_name);

		header ("Location: ./Form_TransferItems.php?fromproject=$fromproject&toproject=$toproject&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&transferdt_remark=$transferdt_remark&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&transfer_date=$transfer_date&drivername=$driver_name&vehicle_no=$vehicle_no&message=$message&td=$td");
		
	}
	else
	if ($actionmoded=='d' and $transferdt_id!='')
		{
			if ($item_withserial==0)
				{
				$Del = "delete from temp_transferdt where transferdt_id = ".$transferdt_id;
				$result=mysql_query($Del,$connection) or die(mysql_error());
				}
			else
			{	
				if ($perserial!='yes')
				{ 
				$Del = "delete from temp_purchasesserialno where transferdt_id = ".$transferdt_id;
				$result=mysql_query($Del,$connection) or die(mysql_error());

				$Del = "delete from temp_transferdt where transferdt_id = ".$transferdt_id;
				$result=mysql_query($Del,$connection) or die(mysql_error());
				
				
				}
				else
				if ($perserial=='yes')
					{
					$Del = "select 1 from temp_purchasesserialno where serial_id = ".$serial_id." and serialno_used=0";				
					$result=mysql_query($Del,$connection) or die(mysql_error());
					$row = mysql_fetch_row($result);		
					if ($row[0]==1)
					{
					$Del = "delete from temp_purchasesserialno where serial_id = ".$serial_id;				
					
					$result1=mysql_query($Del,$connection) or die(mysql_error());
					
					if ($result1)
						{
						$Upd = "update temp_transferdt set TransferDt_Quantity  = TransferDt_Quantity - 1 where transferdt_id = ".$transferdt_id;
						$result=mysql_query($Upd,$connection) or die(mysql_error());					
						}
					}
					else
					$message= "Can%20not%20delete%20serial%20is%20used.";
						$transfer_remark = ereg_replace(" ","%20",$transfer_remark);			
						$transferdt_remark = ereg_replace(" ","%20",$transferdt_remark);			
						$fromwarehouse = ereg_replace("&","%26",$fromwarehouse);			
						$towarehouse = ereg_replace("&","%26",$towarehouse);			
						$driver_name = ereg_replace(" ","%20",$driver_name);						
					header ("Location: ./Form_TransferSerials.php?item=$item&fromwarehouse=$fromwarehouse&towarehouse=$fromwarehouse&fromproject=$fromproject&toproject=$toproject&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&driver_name=$driver_name&vehicle_no=$vehicle_no&costcent=$costcent&transferdt_id=$transferdt_id&actionmoded=$actionmoded&transfer_date=$transfer_date&itemcode=$itemcode&message=$message");
					exit;
					}
			}	
						$transfer_remark = ereg_replace(" ","%20",$transfer_remark);			
						$transferdt_remark = ereg_replace(" ","%20",$transferdt_remark);			
						$fromwarehouse = ereg_replace("&","%26",$fromwarehouse);			
						$towarehouse = ereg_replace("&","%26",$towarehouse);			
						$driver_name = ereg_replace(" ","%20",$driver_name);
		header ("Location: ./Form_Transfer.php?fromproject=$fromproject&toproject=$toproject&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&transferdt_remark=$transferdt_remark&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&transfer_date=$transfer_date&drivername=$driver_name&vehicle_no=$vehicle_no");
		}
	else
	if ($actionmoded=='e' and $transferdt_id!='')
	{
		$upd = "update temp_transferdt set 
				Item_code = '".$itemcode."'
				,TransferDt_Quantity= '".$p_item_quantity."'
				,TransferDt_Price= '".$p_item_sellingprice1."'
				,Transferdt_remark= '".$p_transferdt_remark."'
				where transferdt_id = ".$transferdt_id;		
		$result=mysql_query($upd,$connection) or die(mysql_error());
		
						$transfer_remark = ereg_replace(" ","%20",$transfer_remark);			
						$transferdt_remark = ereg_replace(" ","%20",$transferdt_remark);			
						$fromwarehouse = ereg_replace("&","%26",$fromwarehouse);			
						$towarehouse = ereg_replace("&","%26",$towarehouse);			
						$driver_name = ereg_replace(" ","%20",$driver_name);	
	header ("Location: ./Form_TransferItems.php?fromproject=$fromproject&toproject=$toproject&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&transferdt_remark=$transferdt_remark&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&transfer_date=$transfer_date&drivername=$driver_name&vehicle_no=$vehicle_no&transferdt_id=$transferdt_id&actionmoded=$actionmoded");
	}
	else if ($actionmode=='search' and $transfer_id!='')
	
{


		

	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO Temp_transfer(Transfer_Id, Transfer_Reference, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, 
				Project_code1, Project_code2, Costcenter_Code, Journal_id, TransferDt_ID, SendReceive_Reference, Transfer_BelongsToGroup, 
				Synchronized, Adjustment_id, Driver_Name, 
				Vehicle_No, f_Date, Requestedby, User_account, Company_Name, Transfer_WarehouseFrom, Transfer_WarehouseTo, Logged_Code)
			  Select Transfer_Id, Transfer_Reference, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code, Journal_id, TransferDt_ID, SendReceive_Reference, Transfer_BelongsToGroup, Synchronized, 
			 Adjustment_id, Driver_Name, Vehicle_No, f_Date, Requestedby, User_account, Company_Name, Transfer_WarehouseFrom, Transfer_WarehouseTo
			 , '".$HTTP_SESSION_VARS['useraccount']."' FROM Transfer ".
			 " WHERE Transfer_id = ".$transfer_id;
	
	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 	
			 
	$query = " INSERT INTO temp_transferdt (TransferDt_id, Transfer_Id, Transfer_Date, Item_Barcode, Item_code, Size_Measure, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity, TransferDt_ExpireDate, TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, Project_Code1, Project_Code2, Costcent_Code, 
				Transferdt_remark, Color_Code, Cur_code, Transferdt_posted, PreProduction_Serial, Item_CodePacked, Synchronized, Item_qtyPacked, TransferDt_DirectStkDbt, TransferDt_DirectStkCrd, TransferDt_DirectStkCur, TransferDt_PricePerUnit, TransferDt_QtyUnit, 
				Date, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id, Logged_Code)
				select TransferDt_id, Transfer_Id, Transfer_Date, Item_Barcode, Item_code, Size_Measure, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity, TransferDt_ExpireDate, TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Transfer_Posted, Project_Code1, Project_Code2, Costcent_Code, Transferdt_remark, Color_Code, Cur_code, 
				Transferdt_posted, PreProduction_Serial, Item_CodePacked, Synchronized, Item_qtyPacked, TransferDt_DirectStkDbt, TransferDt_DirectStkCrd, TransferDt_DirectStkCur, TransferDt_PricePerUnit, TransferDt_QtyUnit, Date, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id
				, '".$HTTP_SESSION_VARS['useraccount']."' 
				FROM transferdt  WHERE transfer_id = ".$transfer_id;
	
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 			
			
	$query = " INSERT INTO temp_purchasesserialno 
				(Serial_ID, Journal_Type, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_UsedSold, RelatedSerial_IdSold, Sale_id, SerialNo_posted, Warehouse_code, RealPurchaseDt_ID, ProdDtItem_ID, Synchronized, DeliveryDt_ID, AdjustmentDt_ID, TransferDt_ID, SaleDt_ID, ProductionDt_ID, RPurchaseDt_ID, Production_ID, flagunique, SerialNo_Quantity, SerialNo_QuantitySold, Logged_Code) 
				select Serial_ID,Journal_Type, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_UsedSold, RelatedSerial_IdSold, Sale_id, SerialNo_posted, Warehouse_code, RealPurchaseDt_ID, ProdDtItem_ID, Synchronized, DeliveryDt_ID, AdjustmentDt_ID, TransferDt_ID, SaleDt_ID, ProductionDt_ID, RPurchaseDt_ID, Production_ID, TransferDt_ID, SerialNo_Quantity, SerialNo_QuantitySold, '".$HTTP_SESSION_VARS['useraccount']."' 
				FROM purchasesserialno  WHERE transferdt_id in (select transferdt_id from transferdt where transfer_id = ".$transfer_id.")";
	
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 			
			
			
			
		if ($message!='')
			$message = ereg_replace(' ','%20',$message);
		if ($message!='')
			header ("Location: ./Form_TransferSearch.php?PMode=1&message=".$message."&transfer_id=".$transfer_id);
		else
			header ("Location: ./Form_TransferSearch.php?PMode=1");
		exit;	

}
	else if ($actionmode=='deletepending' and $pendingtransfer_id!='')	
	{
		fbegin();
		$query ="delete from temp_purchasesserialno where transferdt_id in (select transferdt_id from temp_transferdt
																		where transfer_id = ".$pendingtransfer_id.")";
		$result=mysql_query($query,$connection) or die(mysql_error());
		
		$query ="delete from temp_transferdt where transfer_id = ".$pendingtransfer_id;
		$result2=mysql_query($query,$connection) or die(mysql_error());
					
		$query ="delete from temp_transfer where transfer_id = ".$pendingtransfer_id;
		$result3=mysql_query($query,$connection) or die(mysql_error());
		
		
		if (!result or !result2 or !result3)
		frollback();
		else
		fcommit();
		
		header ("Location: ./Form_TransferSearchPending.php");
		
	}
	
function displayParadoxDate($data){
	return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2);
}
function insertDate($data){
	return substr($data, 6, 4) . substr($data, 3, 2) . substr($data, 0, 2);
}
function fbegin()
{
	mysql_query("START TRANSACTION");
}
function fcommit(){
	mysql_query("COMMIT");
}
function frollback()
{
	mysql_query("ROLLBACK");
}
function selectData($conn, $query){
	$result = mysql_query($query, $conn);
	$cur = mysql_fetch_row($result);		
	return $cur;
}
function updateData($conn, $query, $commit){
	if (mysql_query($query, $conn)){				
		return true;
	}else{
		return false;
	}
}
?>