<?php

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

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

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

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

include("config.inc.php");

include("function.inc.php");

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

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



$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2 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_TransferWithOneWh,0) As Module_TransferWithOneWh,ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity,ifnull(Module_ZeroQuantity,0) as Module_ZeroQuantity 
				,ifNull(Module_DoubleUnit,0) As Module_DoubleUnit ,ifnull(Module_Unit1Method,0) Module_Unit1Method,ifnull(Module_ReferenceByCostcenter,0) Module_ReferenceByCostcenter 
				,module_serialno, ifnull(module_chargesInTransfer,0) as module_chargesInTransfer
				From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

	$querylog=" select ifNull(FI_Transfer,0) As FI_Transfer ,login_belongstogrp ,ifNull(Login_negativeQty,0) As Login_negativeQty".
			  " 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);
											 }
		

	
$AllowSave = 1;
//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, ifNull(LockedPeriodDays,0) As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
	//echo $sub_query."<br>";			  
	$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);
	}	
//	echo dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($transfer_date));exit;

	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($transfer_date))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '0' && $LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($transfer_date)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
		
		
		//if ($AllowSave == 0) $message='Save not allowed. Exceed Lock Period.';
		if ($ExceedLockPeriod == 1) {
			$AllowSave = 0;
			$message='Save not allowed. Exceed Lock Period.';
		}
	}
	//echo $message;exit;

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


$fromproject1 = $fromproject;
$toproject1 = $toproject;
		
$costcent = "".$costcent;			
if ($costcent == '')
		$costcent1 = 'null';
else
	$costcent1 = "'".$costcent."'";

$tocostcent = "".$tocostcent;	
if ($tocostcent == '')
		$tocostcent1 = 'null';
else
	$tocostcent1 = "'".$tocostcent."'";

$fromproject = "".$fromproject;	
if ($fromproject == '')
		$fromproject = 'null';
	else
		$fromproject = "'".$fromproject."'";

$toproject = "".$toproject;		
if ($toproject == '')
		$toproject = 'null';
	else
		$toproject = "'".$toproject."'";

if ( $mode == 'changerates' && $transfer_id != ''){
	$query = " Select transfer_ID, curencycode, Transfer_Date, amountBase1, amountBase2 ".
	         " From Temp_transfer As transfer ".
	         " Where transfer.transfer_ID = ".$transfer_id;
	//echo $query;
	$rows = selectData($connection, $query);
	
	$vCurCode = $rows[1];
	$vTansferDate = $rows[2];
		
	$vRate   = $txtPurRate;
	$vRateB2 = $txtPurRateB2;
	
	$amount		  = ConvertCurrencyRate($base1, $vCurCode, $vTansferDate, 0, 0, $amountbase1, $connection);
	$amountbase1    = ConvertCurrencyRate($vCurCode, $base1, $vTansferDate, $vRate, $vRateB1, $amount, $connection);
	$amountbase2    = ConvertCurrencyRate($base1, $base2, $vTansferDate, $vRateB1, $vRateB2, $amountbase1, $connection);
	
	if (empty($vRate)) 	 $vRate = 1;
	if (empty($vRateB2)) $vRateB2 = 0;
	
	else if ($vCurCode == $base1) $vRateB1 = 1;
	else $vRateB1 = 0;
	
	$query = " UPDATE Temp_transfer SET ".
	         " transfer_Rate = $vRate, transfer_RateBase1 = $vRateB1, transfer_RateBase2 = $vRateB2, amountBase1 = $amountbase1, amountBase2 =  $amountbase2 ".
			 " WHERE transfer_ID = $transfer_id ";
	$result=mysql_query($query,$connection);
	if ($result){
		$sub_query = " Select transferdt.transferDt_Id, ifNull(transferdt_costbase1,0), ifNull(transferdt_costbase1,0), ifNull(transferdt_chargebase1,0), ".
					 " ifNull(transferdt_chargebase2,0) ".
					 " From temp_transferdt ".
					 " inner join temp_transfer on temp_transfer.transfer_id = transferdt.transfer_id ".
					 " Where transfer_ID = ".$transfer_id;	
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
			$costbase1    = $sub_row[1];
			$costbase2    = $sub_row[2];
			$chargebase1  = $sub_row[3];
			$chargebase2  = $sub_row[4];
			
			if ($vCurCode == $base1) $cost = $costbase1;
			else  $cost = $costbase2;
			
			$costbase1    = ConvertCurrencyRate($vCurCode, $base1, $vTansferDate, $vRate, $vRateB1, $cost, $connection);
			$costbase2    = ConvertCurrencyRate($base1, $base2, $vTansferDate, $vRateB1, $vRateB2, $costbase1, $connection);
			
			if ($vCurCode == $base1) $charge = $chargebase1;
			else  $charge = $chargebase2;
			
			$chargebase1    = ConvertCurrencyRate($vCurCode, $base1, $vTansferDate, $vRate, $vRateB1, $charge, $connection);
			$chargebase2    = ConvertCurrencyRate($base1, $base2, $vTansferDate, $vRateB1, $vRateB2, $chargebase1, $connection);
			
			$update = "update temp_transferdt set transferdt_costbase1 = $costbase1, transferdt_costbase1 = $costbase2, transferdt_chargebase1 = $chargebase1, transferdt_chargebase2 = $chargebase2
						where transferdt_ID = $sub_row[0] ";
			$res = mysql_query($update, $connection);		
			$message  = mysql_error(); 			
		}
		
	}
	header ("Location: ./Form_PurchaseRates.php?actionmode=rateschanged&mainaction=".$mainmode."&PPurId=".$transfer_id."&InvType=TR&message=".$message);
	exit;
}
	
if ($actionmode == 'editheader' && $transfer_id != ''){
	$message = "";
	$Transfer_Date 			= $_GET['Transfer_Date'];
	$transfer_warehousefrom = $_GET['transfer_warehousefrom'];
	$transfer_warehouseto 	= $_GET['transfer_warehouseto'];
	$Driver_Name 			= $_GET['Driver_Name'];
	$Vehicle_No 			= $_GET['Vehicle_No'];
	$ChargesAmount 			= $_GET['ChargesAmount'];
	$curencycode			= $_GET['curencycode'];
	$Transfer_Remark 		= $_GET['Transfer_Remark'];

	$amountb1 = ConvertCurrency($curencycode, $base1, insertDate($Transfer_Date), $ChargesAmount, $connection);
	$amountb2 = ConvertCurrency($curencycode, $base2, insertDate($Transfer_Date), $ChargesAmount, $connection);
	
	if ($amountb1 == '') $amountb1 = 0;
	if ($amountb2 == '') $amountb2 = 0;
	
	$queryupd = "update temp_transfer set transfer_id = '$transfer_id' , Transfer_Date = '$Transfer_Date' , transfer_warehousefrom = '$transfer_warehousefrom', transfer_warehouseto = '$transfer_warehouseto',
				Driver_Name = '$Driver_Name', Vehicle_No = '$Vehicle_No', ChargesAmount = '$ChargesAmount', curencycode = '$curencycode', Transfer_Remark = '$Transfer_Remark',
					where transfer_id = $transfer_id";
		$resupd = mysql_query($queryupd, $connection);
	
	echo "[BRK]";
	echo $message;
  exit;
}	
if ( $actionmoded == 'changeCost'){
	$curr		 = $_GET['curr'];
	$amount		 = $_GET['amount'];
	$transfer_id = $_GET['transfer_id'];
	$Date		 = $_GET['transferdate'];
	
	$amountb1 = ConvertCurrency($curr, $base1, insertDate($Date), $amount, $connection);
	$amountb2 = ConvertCurrency($curr, $base2, insertDate($Date), $amount, $connection);
	
	if ($amountb1 == '') $amountb1 = 0;
	if ($amountb2 == '') $amountb2 = 0;
	
	$query = "update temp_transfer set amountBase1 = '$amountb1' , amountBase2 = '$amountb2' where transfer_id = $transfer_id ";
	$res = mysql_query($query, $connection);
		
	$querydt = "select transferdt_id, item_code, transfer_date, TransferDt_WarehouseTo
				from temp_transferdt
				where transfer_id = $transfer_id ";
	$resdt = mysql_query($querydt, $connection);			
	while ($rwdt = mysql_fetch_array($resdt)){
		
		$queryc = "select round(MeanCostCur('$rwdt[1]', '$rwdt[2]', 1, '$base1', '$curr'), $DecimalBase) ";
		$res = mysql_query($queryc, $connection);
		$row = mysql_fetch_row($res);
		$cost = $row[0];
		if ($cost == '') $cost = 0;
		
		$costb1 = ConvertCurrency($curr, $base1, $rwdt[2], $cost, $connection);
		$costb2 = ConvertCurrency($curr, $base2, $rwdt[2], $cost, $connection);
		
		if ($costb1 == '') $costb1 = 0;
		if ($costb2 == '') $costb2 = 0;
		
		$queryup = "update temp_transferdt set transferdt_costbase1 = '$costb1' , transferdt_costbase2 = '$costb2', 
					transferdt_chargebase1 = 0, transferdt_chargebase2 = 0
					where transferdt_id = $rwdt[0] ";
		$resup = mysql_query($queryup, $connection);
	}
	echo "[BRK]";
	echo $message;
	exit;
}	
if ( $actionmoded == 'getCost'){
	$item_code 	= $_GET['item_code'];
	$date 		= $_GET['transferdate'];
	$curr		= $_GET['curr'];
	$whcode		= $_GET['warehouse_code'];
	
	$query = "select round(MeanCostCur('$item_code', CONCAT('".displayParadoxDate(insertDate($date))." ', RIGHT(NOW(), 8)), 1, '$base1', '$curr'), $DecimalBase) ";
 	$res = mysql_query($query, $connection);
	$row = mysql_fetch_row($res);
	$cost = $row[0];
	if ($cost == '') $cost = 0;
	$message = mysql_error(); 
	
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
	echo $cost;
	exit;
}	
if ($actionmoded=='checkcode'){
	$vcode 		= $_GET['vcode'];
	$vCode_type = $_GET['vCode_type'];
	
	$vcode = "".$vcode;
	$codeExists = 1;
	if ($vCode_type == 'PROJECT' && $vcode != ''){
		$query = "select 1 from project where project_code = '$vcode' ";
		$res = mysql_query($query, $connection);
		$rw = mysql_fetch_row($res);
		if ($rw[0] == '') $codeExists = 0;
	} 
	else if ($vCode_type == 'COSTCENTER' && $vcode != ''){
		$query = "select 1 from costcent where Costcent_code = '$vcode' ";
		$res = mysql_query($query, $connection);
		$rw = mysql_fetch_row($res);	
		if ($rw[0] == '') $codeExists = 0;		
	}
	else if ($vCode_type == 'WAREHOUSE' && $vcode != ''){
		$query = "select 1 from warehouse where warehouse_code = '$vcode' ";
		$res = mysql_query($query, $connection);
		$rw = mysql_fetch_row($res);	
		if ($rw[0] == '') $codeExists = 0;		
	}
	echo "[BRK]";
	echo $codeExists;
	exit;
}	
if($actionmoded=='inportfromexcel'){
 
 
 //fromproject='+fromproject+'&toproject='+toproject+'&fromwarehouse='+fromwarehouse+'&towarehouse='+towarehouse+'&actionmoded='+actionmoded+'&transfer_id='+transfer_id+'&transfer_remark='+transfer_remark+'&transfer_date='+transfer_date+'&drivername='+driver_name+'&documentrefno='+documentrefno+'&vehicle_no='+vehicle_no+'&costcent='+costcent+'&tocostcent='+tocostcent+'&TransType='+TransType;
			$fromwarehouse = $_GET["fromwarehouse"];
			$towarehouse = $_GET["towarehouse"];
			$TransType = $_GET["TransType"];
			$transfer_date = $_GET["transfer_date"];
			$transfer_remark = $_GET["transfer_remark"];
	 
		

		if ($Item_Unit2Qty == '') $Item_Unit2Qty = 1;
		if ($transfer_id=='')
			{
				fbegin();
				$PTransferId = get_nextsequence('transfer_id','',$connection);	
				fcommit();
				
				fbegin();
				/*if ($Module_TransferWithOneWh==0)
					{
						$fromwarehouse = '';
						$towarehouse = '';
					}*/
				$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,Tocostcenter_code,Transfer_BelongsToGroup,User_account,Document_RefNo,Transfer_Type)
						 values
							(".$PTransferId."
							,CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8)),'".ereg_replace("'","\'",$transfer_remark)."',".$fromproject.",".$toproject.",'".$fromwarehouse."','".$towarehouse."','".$driver_name."','".$vehicle_no."','".$_SESSION['useraccount']."',".$costcent1.",".$tocostcent1.",".$login_belongstogrp.",'".$_SESSION['useraccount']."','".$documentrefno."','".$TransType."')";
			

		 
			$result=mysql_query($query,$connection) or die(mysql_error());
				if ($result)
					{
					$transfer_id = $PTransferId;
					fcommit();
					}
				else
					frollback();
					
			}
				 
	$foldername='uploads';
	if (!file_exists($foldername)) {
		mkdir("./uploads", 0700);
	}

	$fileName = $_FILES["image"]["name"]; 
	$fileTmpLoc = $_FILES["image"]["tmp_name"];
	// Path and file name
	$pathAndName = "uploads/".$fileName;
	$pathAndName1 = "uploads/".$fileName;
	// Run the move_uploaded_file() function here
	$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);		
							

	/// excel mode
require_once('Spreadsheet/Excel/Reader.php');
    $excel = new Spreadsheet_Excel_Reader();
    $excel->read($pathAndName1); 


	$x=1;
	$arrayemp = array();
	//echo $excel->sheets[0]['numRows'];
	
    while($x<=$excel->sheets[0]['numRows']) { ///rowwwww
            
		$itemcode = $excel->sheets[0]['cells'][$x][1];
		$pitemcode = $excel->sheets[0]['cells'][$x][1];
		$itemdesc = $excel->sheets[0]['cells'][$x][2];
		$fromwarehouse = $excel->sheets[0]['cells'][$x][3];
		$towarehouse = $excel->sheets[0]['cells'][$x][4];						
		$p_item_quantity = $excel->sheets[0]['cells'][$x][5];						

		
		$queryitem = " SELECT Count(*) FROM Items WHERE Item_Code = '".$itemcode."'";
		//echo $queryitem."<br>";
				
			$resultitem = selectData($connection, $queryitem);
		
		// if item not exists then checks barcode
		if ($resultitem[0] == 0) {
			$sub_query = " SELECT Item_Code FROM Items WHERE item_barcode = '".$itemcode."' or item_barcode2 = '".$itemcode."' or item_barcode3 = '".$itemcode."'";
			
			$sub_result = selectData($connection, $sub_query);
			$itemcode = $sub_result[0];
			$pitemcode = $sub_result[0];
			
			if ($itemcode == '' || empty($itemcode)) {
				$ErrorExists = 1;
				$message  = "Insert not allowed. Item not found."; 
				
				echo $message;				
				echo "[BRK]";
				echo $transfer_id;
				exit;
			}	
		}
						
				
			$query = "SELECT Client_SellingPrice FROM Clients WHERE Ledger_Number = '".$PSaClientCode."'";
			//echo "<br><br>".$query;
			$result = selectData($connection, $query);
			$c_sp = $result[0];
	
			$query = " SELECT ifNull(Item_Vat,0), ifNull(Item_Unit,0), ifNull(Item_Promotion,0), ifNull(Item_tax1,0), ifNull(Item_tax2,0), ".
					 " ifNull(Item_tax3,0), ifNull(Item_tax4,0), ifNull(Item_tax5,0), Currency_Code, Item_SellingPrice1, Item_SellingPrice2, ".
					 " Item_SellingPrice3, Item_SellingPrice4, Item_SellingPrice5, Item_SellingPrice6 ".
					 " FROM Items WHERE item_Code = '".$txtItemCode."'";
					 
			$result = selectData($connection, $query);
			$ItemVat    = $result[0];
			$ItemUnit   = $result[1];
			$ItemPromo  = $result[2];
			$ItemTax1   = $result[3];	
			$ItemTax2   = $result[4];	
			$ItemTax3   = $result[5];	
			$ItemTax4   = $result[6];	
			$ItemTax5   = $result[7];	
			$ItemCurr   = $result[8];	
			
			
			$i_sp   = $result[9];
			
			switch ($c_sp){
				case "II":
					$i_sp = $result[10]; break;
				case "III":
					$i_sp = $result[11]; break;
				case "IV":
					$i_sp = $result[12]; break;
				case "V":
					$i_sp = $result[13]; break;
				case "VI":
					$i_sp = $result[14]; break;
			}
			
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = 0;
			}
				
			
											
			if ($Module_Delivery == 0) {	
			
				if ($SalesTTC == 1) {
					$p_item_sellingprice1      = $i_sp;
					$p_item_sellingprice1      = ConvertCurrency($ItemCurr, $PSaCurr, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);
					$vSaDtPriceTTCBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);
					$vSaDtPriceTTCBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);

					$p_item_sellingprice1      = ($p_item_sellingprice1 / (1 + $ItemVat/100));
					$vSaDtPriceBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);
					$vSaDtPriceBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);
							
				} else	{
					$p_item_sellingprice1      = $i_sp;
					
					$p_item_sellingprice1      = ConvertCurrency($ItemCurr, $PSaCurr, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);
					$vSaDtPriceBase1 = ConvertCurrency($PSaCurr, $base1, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);
					$vSaDtPriceBase2 = ConvertCurrency($PSaCurr, $base2, insertMySQLDate($PSaDate), $p_item_sellingprice1, $connection);
					
					$p_item_sellingprice1      = 0;
					$vSaDtPriceTTCBase1 = 0;
					$vSaDtPriceTTCBase2 = 0;
							
				}
				
			}	
					
					
					{
						//$checkqty_query =  "select QtyExistsWSorder_TEMP('".$itemcode."','".$fromwarehouse."',now(),0,'TR',null,null)";
						$checkqty_query =  " select QtyExists('".$itemcode."','".$fromwarehouse."','".displayParadoxDate(insertDate($transfer_date))." 23:59:59','".$transfer_id."','TR',null,null)  - ifnull(q1.qty,0)
							  from (select
									ifnull(sum(TransferDt_Quantity),0) as qty
									from temp_transferdt where transfer_id='".$transfer_id."' and item_code = '".$itemcode."'
									)q1";
							
						
						$checkqtyresult=mysql_query($checkqty_query,$connection) or die(mysql_error());
						$checkqtyrows=mysql_fetch_array($checkqtyresult);
						
						//echo $checkqtyrows[0]." ".$p_item_quantity." ".$Module_NegativeQuantity." ".$Login_negativeQty;
						//echo $p_item_quantity;
						if (($checkqtyrows[0] < $p_item_quantity) and (($Module_NegativeQuantity==0) or ($Login_negativeQty==0)) )
						
							{			
										$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);
										$documentrefno = ereg_replace(" ","%20",$documentrefno);
										$message = "Quantity%20entered%20can%20not%20exceeds%20".$checkqtyrows[0];
											//echo $checkqty_query;
											//exit;
								//header ("Location: ./Form_TransferItems.php?fromproject=$fromproject1&toproject=$toproject1&fromwarehouse=$fromwarehouse&costcent=$costcent&tocostcent=$tocostcent&towarehouse=$towarehouse&transferdt_remark=$transferdt_remark&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&transfer_date=$transfer_date&drivername=$driver_name&documentrefno=$documentrefno&vehicle_no=$vehicle_no&message=$message&td=$td&item_withserial=$item_withserial&transferdt_id=$transferdt_id&transit=$transit&TransType=$TransType");
								echo $message;				
								echo "[BRK]";
								echo $transfer_id;
							exit;
							}
						}
						$itemexists=0;
						
									
								$query="select 1 from warehouse where warehouse_production=1 and warehouse_code = '".$fromwarehouse."'";
								$result=mysql_query($query,$connection) or die(mysql_error());
								$isprod = mysql_num_rows($result);
						if ($isprod=='')  
									$isprod=0;
									
						if ($td!='')
							{
							
					
//echo $query;
								//exit;
								
								$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 if($isprod=1,(item_withserialno=0 or  item_withserialno=''),(item_withserialno=0 or  item_withserialno='' or item_withserialno=1))
								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,ifnull(Item_Production,0) as Item_Production,ifnull(Item_SemiFinished,0) as Item_SemiFinished 
									,Item_Unit
									from items where item_code = '".$pitemcode."'
									and if($isprod=1,(item_withserialno=0 or  item_withserialno=''),(item_withserialno=0 or  item_withserialno='' or item_withserialno=1))";
						
						$result=mysql_query($query,$connection) or die(mysql_error());
						while($rows=mysql_fetch_array($result)){
								extract($rows);
								}
								
						$query1 = "select ifnull(Item_Production,0) as Item_Production,ifnull(Item_SemiFinished,0) as Item_SemiFinished from items where item_code = '".$pitemcode."'
									";
						
						$result1=mysql_query($query1,$connection) or die(mysql_error());
						while($rows1=mysql_fetch_array($result1)){
								extract($rows1);
								}
								
						
						 if (($Item_Production==1)	and ($Item_SemiFinished==0))
								{
									$ItemcodeFinished = "'".$pitemcode."'";
									$ItemcodeSemiFinished = 'Null';
								}	
						else
						 if (($Item_Production==0)	and ($Item_SemiFinished==1))
								{
									$ItemcodeSemiFinished = "'".$pitemcode."'";
									$ItemcodeFinished = 'Null';
								}
						else				
								{
									$ItemcodeSemiFinished = 'Null';
									$ItemcodeFinished = 'Null';
								}
						
							$query = "SELECT ifNull(Item_Pack, 0) ".
								" FROM Items WHERE Item_Code = '".$pitemcode."'";
						$result   = selectData($connection, $query);
						$ItemPack = $result[0];
						
					//	if ($lstItemType == "AllItems" || $lstItemType == "SemiFinishSingle" || $lstItemType == "rawmaterials"  || $lstItemType == "FinsihGoodSingle") {
						if ($ItemPack==0){
						
							$PTransferdt_id = get_nextsequence('transferdt_id','',$connection);	
									$query = "select BASE1 from setup limit 1";
									
									$result1=mysql_query($query,$connection)	or die( mysql_error());
									$row=mysql_fetch_array($result1);
									$BASE1	=$row[0];
										
								$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;
						
						
						if ($Item_Unit=='')
							$Item_Unit = 1;
							
						if ($Item_Unit2Qty=='')
							$Item_Unit = 0;
							
						if ($p_item_sellingprice1=='')	
							$p_item_sellingprice1 = 0;
						fbegin();
						$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,tocostcent_code,Item_CodeFinished,Item_CodeSemiFinished";
								
								if ($Module_DoubleUnit==1)
								$query = $query."
								,Item_UnitCoef
								,Item_Unit2Qty ";
								
								
								$query = $query.") values(
							  '".$PTransferdt_id."'
							  ,'".$transfer_id."'
							  ,CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
							   ,'".$pitemcode."'						  
							  ,'".$p_item_quantity."'
							  ,".$p_item_sellingprice1."
							  ,".$p_item_sellingprice1."
							  ,".$item_sellingprice2."
							   ,'".$fromwarehouse."'
							  ,'".$towarehouse."'
							  ,''
							  ,'".$_SESSION['useraccount']."'
							  ,".$costcent1."
							  ,".$tocostcent1."
							  ,".$ItemcodeFinished."
							  ,".$ItemcodeSemiFinished."
							  ";
							
							if ($Module_DoubleUnit==1)
								$query = $query.",'".$Item_Unit."' ,'".$Item_Unit2Qty."' ";
							   
					   
								$query = $query.")";
						//echo $query;
						}
						else 
						{
				
				fbegin();
				$txtItemCode = $pitemcode;
				$txtPurDtQty = $p_item_quantity;
				if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack") {
					$querypackdt = " SELECT PackDt1.Item_Code, PackDt1.Item_CodePackDt, PackDt1.PackDt_Quantity, PackDt1.PackDt_CostPercentage ".
								   " FROM PackDt, PackDt As PackDt1, Items ".
								   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
								   " AND PackDt.Item_CodePackDt = PackDt1.Item_Code ".
								   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
								   " AND ifNull(Items.Item_SemiFinished,0) = 1 ".
								   " UNION ".
								   " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, PackDt.PackDt_Quantity, PackDt.PackDt_CostPercentage ".
								   " FROM PackDt, Items ".
								   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
								   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
								   " AND ifNull(Items.Item_SemiFinished,0) = 0 ";				
				} else {
					$querypackdt = " SELECT Item_Code, Item_CodePackDt,PackDt_Quantity,PackDt_CostPercentage ".
								   " FROM PackDt ".
								   " WHERE Item_Code = '".$txtItemCode."'  ";
				}
				
				//echo $querypackdt;
				//	exit;
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
				
					if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack")	$vItemCodePacked = '';
					else $vItemCodePacked = $rowspackdt[0];
					
					$vItemCode       = $rowspackdt[1];
					$vPackDtQty      = $rowspackdt[2];
					
					$itemquery = "select Item_SellingPrice1,Item_SellingPrice1Base1,Item_SellingPrice1Base2 from  items where item_code='".$rowspackdt[0]."'";					
					$resultitemPrice=mysql_query($itemquery, $connection) or die(mysql_error());
					$rowsprice=mysql_fetch_array($resultitemPrice);
					$p_item_sellingprice1  = $rowsprice[0];
					$p_item_sellingpriceBase1  = $rowsprice[1];
					$p_item_sellingpriceBase2  = $rowsprice[2];
					
					$vPurDtId = get_nextsequence('transferdt_id','',$connection);				
					$vPurDtQty = $txtPurDtQty*$vPackDtQty;
					
					$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,tocostcent_code
					,Item_CodePacked,Item_qtyPacked ,Item_CodeFinished,Item_CodeSemiFinished
					) values(
							  '".$vPurDtId."'
							  ,'".$transfer_id."'
							  ,CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
							   ,'".$vItemCode."'						  
							  ,'".$vPurDtQty."'
							  ,'".$p_item_sellingprice1."'
							  ,'".$p_item_sellingpriceBase1."'
							  ,'".$p_item_sellingpriceBase2."'
							   ,'".$fromwarehouse."'
							  ,'".$towarehouse."'
							  ,''
							  ,'".$_SESSION['useraccount']."'
							  ,".$costcent1."
							  ,".$tocostcent1."
							  ,  if('".$vItemCodePacked."'='', Null, '".$vItemCodePacked."')
							  ,".$txtPurDtQty."
							  ,".$ItemcodeFinished."
							  ,".$ItemcodeSemiFinished."
							   );";
						
					$result=mysql_query($query,$connection) or die(mysql_error());						
					//echo $query;
				} // End Loop Of Packdt
					
						if ($result)
							fcommit();
						else
							frollback();
		}
	 
		
						// after adding semi finished pack and finished good pack
						//if ($lstItemType == "AllItems" || $lstItemType == "SemiFinishSingle"  || $lstItemType == "rawmaterials"  || $lstItemType == "FinsihGoodSingle"){
						if ($ItemPack==0){
						if ($td!='')
						{
						if ($itemcode!='' and $itemexists!=0)
						$result=mysql_query($query,$connection) or die(mysql_error());
						else
						if ($itemcode!='' and $itemexists==0)
						$message='Error:Item%20not%20exists.';
						else
						if ($itemcode=='' and $itemexists!=0)
						$message='Error:Item%20with%20serial.';
						else
						if ($itemcode=='' and $itemexists==0)
						$message='Error:Item%20with%20serial%20and%20Item%20not%20exists.';
						}
						else /// not in load mode
						{
						if ($itemcode!='' )
						$result=mysql_query($query,$connection) or die(mysql_error());
						else
						if ($itemcode!='' )
						$message='Error:Item%20not%20exists.';
						else
						if ($itemcode=='' )
						$message='Error:Item%20with%20serial1.';
					 
						}
					
						if ($result)
							fcommit();
						else
							frollback();
						}
						$x+=1;
}						
						$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);
						$documentrefno = ereg_replace(" ","%20",$documentrefno);
 
		//header ("Location: ./Form_TransferItems.php?fromproject=$fromproject1&toproject=$toproject1&costcent=$costcent&tocostcent=$tocostcent&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&documentrefno=$documentrefno&vehicle_no=$vehicle_no&message=$message&td=$td&item_withserial=$item_withserial&transferdt_id=$transferdt_id&transit=$transit&TransType=$TransType");
		//echo $message;				
		//header ("Location: ./Form_TransferRequestItems.php?fromproject=$fromproject1&toproject=$toproject1&costcent=$costcent&tocostcent=$tocostcent&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&transferdtrequest_remark=$transferdtrequest_remark&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&transfer_date=$transfer_date&drivername=$driver_name&documentrefno=$documentrefno&vehicle_no=$vehicle_no&message=$message&td=$td&item_withserial=$item_withserial&transferdtrequest_id=$transferdtrequest_id&transit=$transit&TransType=$TransType");
		
		
		header ("Location: ./Form_Transfer.php?actionmode=edit&message=".$message."&transfer_id=".$transfer_id."&TransType=".$TransType);		
		exit;

}
else

if($actionmode=='addtempdt'){

$query = "select  transfer_remark from transfer where transfer.transfer_id = ".$LoadItemsForm;
$result=mysql_query($query,$connection)  or die(mysql_error());	
$row=mysql_fetch_array($result);
$p_transfer_remark = $row[0];

if($p_transfer_remark!=''){
					$q = " update temp_transfer set transfer_remark = '".$p_transfer_remark."' where transfer_id = ".$transfer_id;
					$result=mysql_query($q,$connection)  or die(mysql_error());	
					
			}

if($module_serialno==0 and $transfer_id !=''){
$query="  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
		, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id, ToCostcent_Code, Date, Item_CodeFinished, Item_CodeSemiFinished
		, PTRANSFERdt_id, Transferrequest_Reference, Transferrequestdt_Id
		  From Transferdt where transfer_id = $LoadItemsForm ";
//echo $query;exit;		
$result=mysql_query($query,$connection) or die(mysql_error());
	
while($rows=mysql_fetch_array($result)){
	fbegin();
	$PTransferdt_id = get_nextsequence('transferdt_id','',$connection);	
	fcommit();
	
	$querydt2 = "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,Item_codefinished,Item_codesemifinished,Transferrequestdt_Id,Transferrequest_reference)
				select 	".GetSQLValueString($PTransferdt_id,'double').",".GetSQLValueString($transfer_id,'double')." 
				, A.Transfer_Date, A.Item_Barcode, A.Item_code, A.Size_Measure, A.TransferDt_WarehouseFrom, a.TransferDt_WarehouseTo,
				A.TransferDt_Quantity- sum(ifnull(b.transferdt_quantity,0)) as transferdt_quantity
				, A.TransferDt_ExpireDate, A.TransferDt_Price, A.TransferDt_PriceBase1, A.TransferDt_PriceBase2,
				A.Transfer_Posted, A.Project_Code1, A.Project_Code2, A.Costcent_Code, 
				A.Transferdt_remark, A.Color_Code, A.Cur_code, A.Transferdt_posted, A.PreProduction_Serial, 
				A.Item_CodePacked, A.Synchronized, a.Item_qtyPacked, A.TransferDt_DirectStkDbt, A.TransferDt_DirectStkCrd,
				a.TransferDt_DirectStkCur, A.TransferDt_PricePerUnit, A.TransferDt_QtyUnit, 
				A.Date, A.Item_ManufacturedCode, A.Item_UnitCoef, A.Item_Unit2Qty, $rows[0],'".$_SESSION['useraccount']."',
				A.Item_codefinished,A.Item_codesemifinished,a.Transferrequestdt_Id,A.Transferrequest_reference
				from Transferdt A left join transferdt B on B.Relateddt_id=A.transferdt_id
				where A.transferdt_id = $rows[0]  group by a.transferdt_id ";
				
 
	$resultdt2=mysql_query($querydt2,$connection) or die(mysql_error());
	
 
}

 
}








exit;
}
		if ($AllowSave==1) 
		if ($transfer_id!='' and $actionmode!='search' and $actionmoded != 'd')
		{
		$upd = "Update temp_transfer set 
					 transfer_date = CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
					,Transfer_Remark = '".ereg_replace("'","\'",$transfer_remark)."'
					,Project_code1 = ".$fromproject."
					,Project_code2 = ".$toproject."			
					,Costcenter_Code = ".$costcent1."
					,ToCostcenter_Code = ".$tocostcent1."
					,Document_RefNo = '".$documentrefno."'
					,Driver_Name = '".$drivername."'
					,vehicle_no = '".$vehicle_no."'";
					if ($Module_TransferWithOneWh==1)
					$upd=$upd." ,Transfer_WarehouseFrom = '".$fromwarehouse."'
					,Transfer_WarehouseTo = '".$towarehouse."'";
					
					$upd = $upd." where transfer_id = ".$transfer_id
					;
		
	//echo $upd;
	//exit;
		$result1=mysql_query($upd,$connection) or die(mysql_error());
					
		if ($Module_TransferWithOneWh==1){			
		$upd = "Update temp_transferdt set ";
		$upd = $upd."TransferDt_WarehouseFrom = '".$fromwarehouse."'";
		$upd = $upd.",TransferDt_Warehouseto = '".$towarehouse."'";
		$upd = $upd."where transfer_id = ".$transfer_id;
		$result1=mysql_query($upd,$connection) or die(mysql_error());
		}
		
		if ($towarehouse!='' and $Module_TransferWithOneWh==1) {
		$upd = "Update temp_purchasesserialno set 		
					Warehouse_code = '".$towarehouse."'
					where transferdt_id in (select transferdt_id from temp_transferdt where transfer_id = ".$transfer_id.")";
		
		$result1=mysql_query($upd,$connection) or die(mysql_error());
		}
		}			
	
	if ($actionmoded=='mi')
	{
		if ($AllowSave==0) {
			header ("Location: ./Form_Transfer.php?actionmode=post&message=".$message."&transfer_id=".$transfer_id."&TransType=".$TransType);	
			exit;
			}
						
		$totalChargesAmount	= $_POST['txtChargesAmount'];
		$chargesCurr 		= $_POST['txtChargesCurr'];
		
		if ($totalChargesAmount == '') 	$totalChargesAmount = 0;
		
			
		if ($chargesCurr == '') 
			$chargesCurr = $base1;
		
		if ($module_chargesInTransfer == 1){
			$amountBase1 = ConvertCurrency($chargesCurr, $base1, insertMySQLDate($transfer_date), $totalChargesAmount, $connection);
			$amountBase2 = ConvertCurrency($chargesCurr, $base2,  insertMySQLDate($transfer_date), $totalChargesAmount, $connection);
			
		} else {
			$amountBase1 = 0;
			$amountBase2 = 0;
		} 
		if ($amountBase1 == '') $amountBase1 = 0;
		if ($amountBase2 == '') $amountBase2 = 0;
		
		$upd_Tr = "Update temp_transfer set 
					 transfer_date = CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
					,Transfer_Remark = '".ereg_replace("'","\'",$transfer_remark)."'
					,Project_code1 = ".$fromproject."
					,Project_code2 = ".$toproject."			
					,Costcenter_Code = ".$costcent1."
					,ToCostcenter_Code = ".$tocostcent1."
					,Driver_Name = '".$drivername."'
					,Document_RefNo = '".$documentrefno."'
					,vehicle_no = '".$vehicle_no."' ";
				
				if ($Module_TransferWithOneWh==1)
				$upd_Tr = $upd_Tr." ,Transfer_WarehouseFrom = '".$fromwarehouse."'
										,Transfer_WarehouseTo = '".$towarehouse."' ";
				
				$upd_Tr=$upd_Tr." ,amountBase1 = '".$amountBase1."', amountBase2 = '".$amountBase2."', curencycode = '".$chargesCurr."'
								where transfer_id = ".$transfer_id;
		
		
		$upd_TrDT = "Update Temp_Transferdt set 
					transfer_date =CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))";
					if ($Module_TransferWithOneWh==1){
					$upd_TrDT =	$upd_TrDT.",TransferDt_WarehouseFrom= '".$fromwarehouse."' ";
					$upd_TrDT =	$upd_TrDT.",TransferDt_WarehouseTo = '".$towarehouse."' ";
					}
					$upd_TrDT =	$upd_TrDT.",Project_code1 = ".$fromproject."
					,Project_code2 = ".$toproject."			
					,Costcent_code = ".$costcent1."
					,ToCostcent_code = ".$tocostcent1."
					where transfer_id = ".$transfer_id;
		
		if ($towarehouse!='' and $Module_TransferWithOneWh==1) {
		$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());
		if ($towarehouse!='' and $Module_TransferWithOneWh==1) 
			$result3=mysql_query($upd_PurSr,$connection) or die(mysql_error());
		if ($result1 and $result2 and ($result3  or $Module_TransferWithOneWh==0) ) {
				fcommit();
				} else{
				$message  = mysql_error(); 
				frollback();
			}
			
			$query = "Select Count(*) From Transfer Where Transfer_id = ".$transfer_id;
				$result1 = selectData($connection, $query);
				$Ref = $result1[0];
				
				$query_checkDelivery  = "select count(*) as TransferExist from transfer where transfer_id = '$transfer_id'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($TransferExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
			
			fbegin();

			$queryrel = "select relatedserial_id from purchasesserialno where transferdt_id in(
                              select transferdt_id from transferdt where transfer_id in (select transfer_id from transfer where transfer_id = ".$transfer_id."))";
			
			$resultrel=mysql_query($queryrel,$connection) or die(mysql_error());
			while ($rowsrel=mysql_fetch_array($resultrel))
				{
				 if ($rowsrel[0]!='')
					{
						$queryrel2 = "update purchasesserialno set serialno_used = 0 where serial_id = ".$rowsrel[0];
						$resultrel2=mysql_query($queryrel2,$connection) or die(mysql_error());
					}	
				}
			$resultcheckTrans = 0;
			$querycheckTrans = "SELECT  1 from temp_transfer where transfer_id = ".$transfer_id;
			//echo $querycheckTrans;
			//exit;
			$resultcheckTrans = selectData($connection, $querycheckTrans);
			$resultcheckTrans = $resultcheckTrans[0];	
			
			if ($module_chargesInTransfer == 1){
				calculateCharge($transfer_id, $base1, $base2, insertDate($transfer_date), $connection);				
			}
			
			if ($resultcheckTrans==1) {
			$query = "SELECT CopyData_TempTransfer('".$SMode."', ".$transfer_id.",null,'".$_SESSION['useraccount']."') FROM Dual ";
			//echo $query;
			//exit;
			$result = selectData($connection, $query);
			$result = $result[0];	
			
			if ($result != 0){
				fcommit();
				
				
				
				If ($Ref == 0 or $Ref == '') // // if adding new transfer only
				{
				fbegin();	
				if($Module_ReferenceByCostcenter==1) {
						if ($TransType=='Tr')
							$TrRef = get_nextsequence('Transfer_reference',$costcent,$connection);
						else if ($TransType=='Rm')
							$TrRef = get_nextsequence('RmTransfer_reference',$costcent,$connection);				
							}
				else 	{
						if ($TransType=='Tr')
							$TrRef = get_nextsequence('Transfer_reference','',$connection);
						else if ($TransType=='Rm')
							$TrRef = get_nextsequence('RmTransfer_reference','',$connection);				
						}
				
				if ($TrRef!='')
					fcommit();
					else
					frollback();
						$updseq="update transfer set transfer_reference = ".$TrRef." where transfer_id = ".$transfer_id;
						$result = selectData($connection, $updseq);
				}		
				if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$transfer_id', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'transfer', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}		
					
				if ($module_chargesInTransfer == 1){
					$message = Create_TransferJv($transfer_id, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 

				}				
			} 
			else{
				$message  = 'Error In CopyData_TempTransfer Function'; 
				frollback();
				
			}
		} // end of check if found in transfer
		if ($message!='')
		$message = ereg_replace(' ','%20',$message);
		if ($message!='')
		header ("Location: ./Form_Transfer.php?actionmode=post&message=".$message."&transfer_id=".$transfer_id."&TransType=".$TransType);
		else
		//header ("Location: ./Form_Transfer.php?actionmode=post&transfer_id=".$transfer_id."&TransType=".$TransType);
		header ("Location: ./Form_Transfer.php?TransType=".$TransType."&actionmode=post&transfer_id=".$transfer_id);
		exit;		
	}
	else			
	if ($actionmoded=='i' || $actionmoded=='submitbarcode')
	{
		
		if ($actionmoded=='submitbarcode') {
			$itemcode 				= $_GET["value1"];
			$p_item_code 			= $_GET["value1"];
			$p_item_quantity 		= $_GET["value2"];
			$p_item_sellingprice1 	= $_GET["value3"];
			$fromwarehouse 			= $_GET["value4"];
			$fromwarehouse 			= trim(strtoupper($fromwarehouse));
			$towarehouse 			= $_GET["value5"];
			$towarehouse 			= trim(strtoupper($towarehouse));
			$p_transferdt_remark 	= $_GET["value6"];
			$Item_Unit2Qty 			= $_GET["value17"];
			$TransType 				= $_GET["TransType"];
			$TransBatchno 			= $_GET["STrDtBatchno"];
			$transferdt_heatno 		= $_GET['transferdt_heatno'];
			$TransPackagingno 		= $_GET["STrDtPackagingno"];
			$TransNbrunit 			= $_GET["STrDtNbrunit"];
		} else {
			$itemcode 				= $_GET["value1"];
			$p_item_code 			= $_GET["value1"];
			$p_item_quantity 		= $_GET["value2"];
			$fromwarehouse 			= $_GET["value4"];
			$fromwarehouse 			= trim(strtoupper($fromwarehouse));
			$towarehouse 			= $_GET["value5"];
			$towarehouse 			= trim(strtoupper($towarehouse));
			$TransType 				= $_GET["TransType"];
			$p_transferdt_remark 	= $_GET["value6"];
			$TransBatchno 			= $_GET["STrDtBatchno"];
			$transferdt_heatno 		= $_GET['transferdt_heatno'];
			$TransPackagingno 		= $_GET["STrDtPackagingno"];
			$TransNbrunit 			= $_GET["STrDtNbrunit"];
			
			
			
		/*	$sub_query = " SELECT Item_Code FROM Items WHERE item_barcode = '".$itemcode."' or item_barcode2 = '".$itemcode."' or item_barcode3 = '".$itemcode."'";
			$sub_result = selectData($connection, $sub_query);
			$itemcode = $sub_result[0];
			$p_item_code = $sub_result[0];*/
			
		}
		
		
		$totalChargesAmount	= $_GET['totalChargesAmount'];
		$chargesCurr 		= $_GET['chargesCurr'];
		
		$costamount 		= $_GET['costamount'];
		$chargeamount 		= $_GET['chargeamount'];
		
		if ($costamount == '')	 		$costamount = 0;
		if ($chargeamount == '')		$chargeamount = 0;
		if ($totalChargesAmount == '') 	$totalChargesAmount = 0;
		
			
		if ($chargesCurr == '') 
			$chargesCurr = $base1;
		
		if ($module_chargesInTransfer == 1){
			$amountBase1 = ConvertCurrency($chargesCurr, $base1, insertMySQLDate($transfer_date), $totalChargesAmount, $connection);
			$amountBase2 = ConvertCurrency($chargesCurr, $base2,  insertMySQLDate($transfer_date), $totalChargesAmount, $connection);
			
		} else {
			$amountBase1 = 0;
			$amountBase2 = 0;
		} 
		if ($amountBase1 == '') $amountBase1 = 0;
		if ($amountBase2 == '') $amountBase2 = 0;
		
		if($TransBatchno == '') $TransBatchno = "NULL";
		else $TransBatchno = "'".$TransBatchno."'";
		if($transferdt_heatno == '') $transferdt_heatno = "NULL";
		else $transferdt_heatno = "'".$transferdt_heatno."'";
		if($TransPackagingno == '') $TransPackagingno = 0;
		if($TransNbrunit == '') $TransNbrunit = 0;
		if($p_transferdt_remark == '') $p_transferdt_remark = "NULL";
		else $p_transferdt_remark = "'".ereg_replace("'","\'",$p_transferdt_remark)."'"; 
		
		//echo $itemcode."-".$p_item_code."-".$_GET["value1"];
		if ($Item_Unit2Qty == '') $Item_Unit2Qty = 1;
		if ($transfer_id=='')
		{ 
			fbegin();
			$PTransferId = get_nextsequence('transfer_id','',$connection);	
			fcommit();
			
			fbegin();
		
			$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,Tocostcenter_code,Transfer_BelongsToGroup,User_account,Document_RefNo,Transfer_Type, amountBase1, amountBase2, curencycode)
					 values
					(".$PTransferId.",CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8)),'".ereg_replace("'","\'",$transfer_remark)."',".$fromproject.",".$toproject.",
					'".$fromwarehouse."','".$towarehouse."','".$driver_name."','".$vehicle_no."','".$_SESSION['useraccount']."',".$costcent1.",".$tocostcent1.",".$login_belongstogrp.",
					'".$_SESSION['useraccount']."','".$documentrefno."','".$TransType."', '".$amountBase1."', '".$amountBase2."', '".$chargesCurr."' )";
			//echo $query;//exit;
	
			 $result=mysql_query($query,$connection) or die(mysql_error());
			if ($result)
			{
				$transfer_id = $PTransferId;
				fcommit();
			}
			else
				frollback(); 
				
		}
				
		$queryitem = " SELECT Count(*) FROM Items WHERE Item_Code = '".$itemcode."'";
		
		$resultitem = selectData($connection, $queryitem);
		
		// if item not exists then checks barcode
		if ($resultitem[0] == 0) {
			$sub_query = " SELECT Item_Code FROM Items WHERE item_barcode = '".$itemcode."' or item_barcode2 = '".$itemcode."' or item_barcode3 = '".$itemcode."'";
			$sub_result = selectData($connection, $sub_query);
			$itemcode = $sub_result[0];
			$p_item_code = $sub_result[0];
			
			if ($itemcode == '' || empty($itemcode)) {
				$ErrorExists = 1;
				$message  = "Insert not allowed. Item not found."; 
				
				echo $message;				
				echo "[BRK]";
				echo $transfer_id;
				exit;
			}	
		}
					
					
					
		{
			//$checkqty_query =  "select QtyExistsWSorder_TEMP('".$itemcode."','".$fromwarehouse."',now(),0,'TR',null,null)";
			$checkqty_query =  " select QtyExists('".$itemcode."','".$fromwarehouse."','".displayParadoxDate(insertDate($transfer_date))." 23:59:59','".$transfer_id."','TR',null,null)  - ifnull(q1.qty,0)
				  from (select
						ifnull(sum(TransferDt_Quantity),0) as qty
						from temp_transferdt where transfer_id='".$transfer_id."' and item_code = '".$itemcode."'
						)q1";
				
			
			$checkqtyresult=mysql_query($checkqty_query,$connection) or die(mysql_error());
			$checkqtyrows=mysql_fetch_array($checkqtyresult);
			
			//echo $checkqtyrows[0]." ".$p_item_quantity." ".$Module_NegativeQuantity." ".$Login_negativeQty;
			//echo $p_item_quantity;
			if (($checkqtyrows[0] < $p_item_quantity) and (($Module_NegativeQuantity==0) or ($Login_negativeQty==0)) )
			
				{ 
							$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);
							$documentrefno = ereg_replace(" ","%20",$documentrefno);
							$message = "Quantity%20entered%20can%20not%20exceeds%20".$checkqtyrows[0];
					echo $message;				
					echo "[BRK]";
					echo $transfer_id;
				exit;
				}
			}
		$itemexists=0;
		
					
				$query="select 1 from warehouse where warehouse_production=1 and warehouse_code = '".$fromwarehouse."'"; 
				$result=mysql_query($query,$connection) or die(mysql_error());
				$isprod = mysql_num_rows($result);
		if ($isprod=='')  
			$isprod=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 if($isprod=1,(item_withserialno=0 or  item_withserialno=''),(item_withserialno=0 or  item_withserialno='' or item_withserialno=1))
				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,ifnull(Item_Production,0) as Item_Production,ifnull(Item_SemiFinished,0) as Item_SemiFinished 
					,Item_Unit
					from items where item_code = '".$p_item_code."'
					and if($isprod=1,(item_withserialno=0 or  item_withserialno=''),(item_withserialno=0 or  item_withserialno='' or item_withserialno=1))";
					//echo $query; exit;
		$result=mysql_query($query,$connection) or die(mysql_error());
		while($rows=mysql_fetch_array($result)){
				extract($rows);
				}
				
		$query1 = "select ifnull(Item_Production,0) as Item_Production,ifnull(Item_SemiFinished,0) as Item_SemiFinished from items where item_code = '".$p_item_code."'
					";
		
		$result1=mysql_query($query1,$connection) or die(mysql_error());
		while($rows1=mysql_fetch_array($result1)){
				extract($rows1);
				}
								
						
		 if (($Item_Production==1)	and ($Item_SemiFinished==0))
				{
					$ItemcodeFinished = "'".$p_item_code."'";
					$ItemcodeSemiFinished = 'Null';
				}	
		else
		 if (($Item_Production==0)	and ($Item_SemiFinished==1))
				{
					$ItemcodeSemiFinished = "'".$p_item_code."'";
					$ItemcodeFinished = 'Null';
				}
		else				
				{
					$ItemcodeSemiFinished = 'Null';
					$ItemcodeFinished = 'Null';
				}
						
		$query = " SELECT ifNull(Item_Pack, 0) ".
				" FROM Items WHERE Item_Code = '".$p_item_code."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		
		
		if ($module_chargesInTransfer == 1){
			$costbase1 = ConvertCurrency($chargesCurr, $base1, insertMySQLDate($transfer_date), $costamount, $connection);
			$costbase2 = ConvertCurrency($chargesCurr, $base2,  insertMySQLDate($transfer_date), $costamount, $connection);
			
			$chargebase1 = ConvertCurrency($chargesCurr, $base1, insertMySQLDate($transfer_date), $chargeamount, $connection);
			$chargebase2 = ConvertCurrency($chargesCurr, $base2,  insertMySQLDate($transfer_date), $chargeamount, $connection);
			
		} else {
			$costbase1 	 = 0;
			$costbase2 	 = 0;
			$chargebase1 = 0;
			$chargebase2 = 0;
		}
		 
		if ($costbase1 == '') $costbase1 	 = 0;
		if ($costbase2 == '') $costbase2 	 = 0;
		if ($chargebase1 == '') $chargebase1 = 0;
		if ($chargebase2 == '') $chargebase2 = 0;
		
		if ($ItemPack==0){
		
			$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;
		
		
		if ($Item_Unit=='')
			$Item_Unit = 1;
			
		if ($Item_Unit2Qty=='')
			$Item_Unit = 0;
			
		if ($p_item_sellingprice1=='')	
			$p_item_sellingprice1 = 0;
		fbegin();
		$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,tocostcent_code,Item_CodeFinished,Item_CodeSemiFinished";
				
				if ($Module_DoubleUnit==1)
				$query = $query."
				,Item_UnitCoef
				,Item_Unit2Qty ";
				
				
		$query = $query.",transferdt_heatno, TransferDt_BatchNo, TransferDt_packagingNo,TransferDt_nbrUnit, transferdt_costbase1, transferdt_costbase2, transferdt_chargebase1, transferdt_chargebase2) 
			values(
			  '".$PTransferdt_id."'
			  ,'".$transfer_id."'
			  ,CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
			   ,'".$p_item_code."'						  
			  ,'".$p_item_quantity."'
			  ,".$p_item_sellingprice1."
			  ,".$p_item_sellingprice1."
			  ,".$item_sellingprice2."
			   ,'".$fromwarehouse."'
			  ,'".$towarehouse."'
			  ,".$p_transferdt_remark."
			  ,'".$_SESSION['useraccount']."'
			  ,".$costcent1."
			  ,".$tocostcent1."
			  ,".$ItemcodeFinished."
			  ,".$ItemcodeSemiFinished."
			  ";
			
			if ($Module_DoubleUnit==1)
				$query = $query.",'".$Item_Unit."' ,'".$Item_Unit2Qty."' ";
			   
	   
				$query = $query.",$transferdt_heatno,$TransBatchno, $TransPackagingno,$TransNbrunit, $costbase1, $costbase2, $chargebase1, $chargebase2 )";	
			//	echo $query;
		//$result=mysql_query($query,$connection) or die(mysql_error());		
		}
	else 
		{
				
			fbegin();
			$txtItemCode = $p_item_code;
			$txtPurDtQty = $p_item_quantity;
			if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack") {
				$querypackdt = " SELECT PackDt1.Item_Code, PackDt1.Item_CodePackDt, PackDt1.PackDt_Quantity, PackDt1.PackDt_CostPercentage ".
							   " FROM PackDt, PackDt As PackDt1, Items ".
							   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
							   " AND PackDt.Item_CodePackDt = PackDt1.Item_Code ".
							   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
							   " AND ifNull(Items.Item_SemiFinished,0) = 1 ".
							   " UNION ".
							   " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, PackDt.PackDt_Quantity, PackDt.PackDt_CostPercentage ".
							   " FROM PackDt, Items ".
							   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
							   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
							   " AND ifNull(Items.Item_SemiFinished,0) = 0 ";				
			} else {
				$querypackdt = " SELECT Item_Code, Item_CodePackDt,PackDt_Quantity,PackDt_CostPercentage ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$txtItemCode."'  ";
			}
			
			//echo $querypackdt;
			//	exit;
			$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
			while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
			
				if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack")	$vItemCodePacked = '';
				else $vItemCodePacked = $rowspackdt[0];
				
				$vItemCode       = $rowspackdt[1];
				$vPackDtQty      = $rowspackdt[2];
				
				$itemquery = "select Item_SellingPrice1,Item_SellingPrice1Base1,Item_SellingPrice1Base2 from  items where item_code='".$rowspackdt[0]."'";					
				$resultitemPrice=mysql_query($itemquery, $connection) or die(mysql_error());
				$rowsprice=mysql_fetch_array($resultitemPrice);
				$p_item_sellingprice1  = $rowsprice[0];
				$p_item_sellingpriceBase1  = $rowsprice[1];
				$p_item_sellingpriceBase2  = $rowsprice[2];
				
				$vPurDtId = get_nextsequence('transferdt_id','',$connection);				
				$vPurDtQty = $txtPurDtQty*$vPackDtQty;
				
				$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,tocostcent_code
				,Item_CodePacked,Item_qtyPacked ,Item_CodeFinished,Item_CodeSemiFinished, TransferDt_BatchNo, TransferDt_packagingNo,TransferDt_nbrUnit
				, transferdt_costbase1, transferdt_costbase2, transferdt_chargebase1, transferdt_chargebase2) values(
						  '".$vPurDtId."'
						  ,'".$transfer_id."'
						  ,CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
						   ,'".$vItemCode."'						  
						  ,'".$vPurDtQty."'
						  ,'".$p_item_sellingprice1."'
						  ,'".$p_item_sellingpriceBase1."'
						  ,'".$p_item_sellingpriceBase2."'
						   ,'".$fromwarehouse."'
						  ,'".$towarehouse."'
						  ,".$p_transferdt_remark."
						  ,'".$_SESSION['useraccount']."'
						  ,".$costcent1."
						  ,".$tocostcent1."
						  ,  if('".$vItemCodePacked."'='', Null, '".$vItemCodePacked."')
						  ,".$txtPurDtQty."
						  ,".$ItemcodeFinished."
						  ,".$ItemcodeSemiFinished."
						   ,$TransBatchno, $TransPackagingno,$TransNbrunit, $costbase1, $costbase2, $chargebase1, $chargebase2);";
				echo $query;
				$result=mysql_query($query,$connection) or die(mysql_error());						
				
			} // End Loop Of Packdt
				
					if ($result)
						fcommit();
					else
						frollback();
		}
	
		
						// after adding semi finished pack and finished good pack
						//if ($lstItemType == "AllItems" || $lstItemType == "SemiFinishSingle"  || $lstItemType == "rawmaterials"  || $lstItemType == "FinsihGoodSingle"){
						if ($ItemPack==0){
						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.';
						}
					
						if ($result)
							fcommit();
						else
							frollback();
						}
						
						$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);
						$documentrefno = ereg_replace(" ","%20",$documentrefno);

		//header ("Location: ./Form_TransferItems.php?fromproject=$fromproject1&toproject=$toproject1&costcent=$costcent&tocostcent=$tocostcent&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&documentrefno=$documentrefno&vehicle_no=$vehicle_no&message=$message&td=$td&item_withserial=$item_withserial&transferdt_id=$transferdt_id&transit=$transit&TransType=$TransType");
		echo $message;				
		//header ("Location: ./Form_TransferRequestItems.php?fromproject=$fromproject1&toproject=$toproject1&costcent=$costcent&tocostcent=$tocostcent&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&transferdtrequest_remark=$transferdtrequest_remark&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&transfer_date=$transfer_date&drivername=$driver_name&documentrefno=$documentrefno&vehicle_no=$vehicle_no&message=$message&td=$td&item_withserial=$item_withserial&transferdtrequest_id=$transferdtrequest_id&transit=$transit&TransType=$TransType");
		echo "[BRK]";
		
		echo $transfer_id;
		
		exit;
	}
	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)
					{
						$tr = "select transferdt_id from temp_purchasesserialno where serial_id = ".$serial_id;				
						
						$resulttr=mysql_query($tr,$connection) or die(mysql_error());
						$rowtr = mysql_fetch_row($resulttr);
						
						$Del = "delete from temp_purchasesserialno where serial_id = ".$serial_id;				
						$result1=mysql_query($Del,$connection) or die(mysql_error());
					
					if ($result1)
						{
						
						if ($Module_DoubleUnit==1 and $Module_Unit1Method == 1)						{
								$Upd = "update temp_transferdt set TransferDt_Quantity  = TransferDt_Quantity - 1 ";								
								$Upd = $Upd ." ,Item_Unit2Qty = TransferDt_Quantity * ifnull(Item_UnitCoef,1) ";
								$Upd = $Upd ." where transferdt_id = ".$rowtr[0];
							}
						else							
							if ($Module_DoubleUnit==1 and $Module_Unit1Method == 0)						{
								$Upd = "update temp_transferdt set Item_Unit2Qty  = Item_Unit2Qty - 1 ";								
								$Upd = $Upd ." ,TransferDt_Quantity = Item_Unit2Qty * ifnull(Item_UnitCoef,1) ";
								$Upd = $Upd ." where transferdt_id = ".$rowtr[0];
							}	
						else 		
							if ($Module_DoubleUnit==0)						{	
								$Upd = "update temp_transferdt set TransferDt_Quantity  = TransferDt_Quantity - 1 ";								
								$Upd = $Upd ." where transferdt_id = ".$rowtr[0];
								}
						
						$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);						
						$documentrefno = ereg_replace(" ","%20",$documentrefno);						
					
					header ("Location: ./Form_TransferSerials.php?item=$item&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&fromproject=$fromproject1&toproject=$toproject1&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&driver_name=$driver_name&documentrefno=$documentrefno&vehicle_no=$vehicle_no&costcent=$costcent&tocostcent=$tocostcent&transferdt_id=$transferdt_id&actionmoded=$actionmoded&transfer_date=$transfer_date&itemcode=$itemcode&message=$message&perpage=$perpage&TransType=$TransType");
					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);
						$documentrefno = ereg_replace(" ","%20",$documentrefno);
		//header ("Location: ./Form_Transfer.php?fromproject=$fromproject1&toproject=$toproject1&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&transferdt_remark=$transferdt_remark&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&transfer_date=$transfer_date&costcent=$costcent&tocostcent=$tocostcent&drivername=$driver_name&documentrefno=$documentrefno&vehicle_no=$vehicle_no&perpage=$perpage&TransType=$TransType");
		}
		
	if ($actionmoded=='d' and $transferdt_id=='')
		{ 

					$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)
					{
						$tr = "select transferdt_id from temp_purchasesserialno where serial_id = '".$serial_id."'";				
						
						$resulttr=mysql_query($tr,$connection) or die(mysql_error());
						$rowtr = mysql_fetch_row($resulttr);
						
						$Del = "delete from temp_purchasesserialno where serial_id = ".$serial_id;				
						$result1=mysql_query($Del,$connection) or die(mysql_error());
					
					if ($result1)
						{
					
						
						if ($Module_DoubleUnit==1 and $Module_Unit1Method == 1)						{
								$Upd = "update temp_transferdt set TransferDt_Quantity  = TransferDt_Quantity - 1 ";								
								$Upd = $Upd ." ,Item_Unit2Qty = TransferDt_Quantity * ifnull(Item_UnitCoef,1) ";
								$Upd = $Upd ." where transferdt_id = ".$rowtr[0];
							}
						else							
							if ($Module_DoubleUnit==1 and $Module_Unit1Method == 0)						{
								$Upd = "update temp_transferdt set Item_Unit2Qty  = Item_Unit2Qty - 1 ";								
								$Upd = $Upd ." ,TransferDt_Quantity = Item_Unit2Qty * ifnull(Item_UnitCoef,1) ";
								$Upd = $Upd ." where transferdt_id = ".$rowtr[0];
							}	
						else 		
							if ($Module_DoubleUnit==0)						{	
								$Upd = "update temp_transferdt set TransferDt_Quantity  = TransferDt_Quantity - 1 ";								
								$Upd = $Upd ." where transferdt_id = ".$rowtr[0];
								}
						
						
						$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);						
						$documentrefno = ereg_replace(" ","%20",$documentrefno);						
					
					header ("Location: ./Form_TransferSerials.php?item=$item&fromwarehouse=$fromwarehouse&towarehouse=$towarehouse&fromproject=$fromproject1&toproject=$toproject1&actionmode=$actionmode&transfer_id=$transfer_id&transfer_remark=$transfer_remark&driver_name=$driver_name&documentrefno=$documentrefno&vehicle_no=$vehicle_no&costcent=$costcent&tocostcent=$tocostcent&transferdt_id=$transferdt_id&actionmoded=$actionmoded&transfer_date=$transfer_date&itemcode=$itemcode&message=$message&perpage=$perpage&TransType=$TransType");
					exit;
					
		}		
else if ($actionmode=='checkwarehousecode'){

$vwarehousecode = $_GET["vwarehousecode"];

$query = " select warehouse_code from warehouse where warehouse_code = '".$vwarehousecode ."' ";
$result=mysql_query($query,$connection)  or die(mysql_error());
$row=mysql_fetch_row($result);

echo "[BRK]";
if ($row[0]!='')
	echo $row[0];
else	
	echo 0;
echo "[BRK]";	
}
	else
	
	if ($actionmoded=='e' and $transferdt_id!='')
	{
	
	
		$itemcode = $_GET["value1"];
		$p_item_quantity = $_GET["value2"];
		$p_item_sellingprice1 = $_GET["value3"];
		$fromwarehouse = $_GET["value4"];
		$fromwarehouse = trim(strtoupper($fromwarehouse));
		$towarehouse = $_GET["value5"];
		$towarehouse = trim(strtoupper($towarehouse));
		$p_transferdt_remark = $_GET["value6"]; 
		$Item_Unit2Qty = $_GET["value17"];
		
		$TransBatchno = $_GET["STrDtBatchno"];
		$TransPackagingno = $_GET["STrDtPackagingno"];
		$TransNbrunit = $_GET["STrDtNbrunit"];

		if($TransBatchno == '') $TransBatchno = "NULL";
		else $TransBatchno = "'".$TransBatchno."'";
		if($TransPackagingno == '') $TransPackagingno = 0;
		if($TransNbrunit == '') $TransNbrunit = 0;
		
		if($p_transferdt_remark == '') $p_transferdt_remark = "NULL";
		else $p_transferdt_remark = "'".ereg_replace("'","\'",$p_transferdt_remark)."'";
		
		
		$totalChargesAmount	= $_GET['totalChargesAmount'];
		$chargesCurr 		= $_GET['chargesCurr'];
		
		$costamount 		= $_GET['costamount'];
		$chargeamount 		= $_GET['chargeamount'];
		
		if ($costamount == '')	 		$costamount = 0;
		if ($chargeamount == '')		$chargeamount = 0;
		if ($totalChargesAmount == '') 	$totalChargesAmount = 0;
	
		
		if ($chargesCurr == '') 
			$chargesCurr = $base1;
		
		if ($module_chargesInTransfer == 1){
			$costbase1 = ConvertCurrency($chargesCurr, $base1, insertMySQLDate($transfer_date), $costamount, $connection);
			$costbase2 = ConvertCurrency($chargesCurr, $base2,  insertMySQLDate($transfer_date), $costamount, $connection);
			
			$chargebase1 = ConvertCurrency($chargesCurr, $base1, insertMySQLDate($transfer_date), $chargeamount, $connection);
			$chargebase2 = ConvertCurrency($chargesCurr, $base2,  insertMySQLDate($transfer_date), $chargeamount, $connection);
			
		} else {
			$costbase1 	 = 0;
			$costbase2 	 = 0;
			$chargebase1 = 0;
			$chargebase2 = 0;
		}
		 
		if ($costbase1 == '') $costbase1 	 = 0;
		if ($costbase2 == '') $costbase2 	 = 0;
		if ($chargebase1 == '') $chargebase1 = 0;
		if ($chargebase2 == '') $chargebase2 = 0;
		
		$queryitem = " SELECT Count(*) FROM Items WHERE Item_Code = '".$itemcode."'";
		
		$resultitem = selectData($connection, $queryitem);
		
		// if item not exists then checks barcode
		if ($resultitem[0] == 0) {
			$sub_query = " SELECT Item_Code FROM Items WHERE item_barcode = '".$itemcode."' or item_barcode2 = '".$itemcode."' or item_barcode3 = '".$itemcode."'";
			$sub_result = selectData($connection, $sub_query);
			$itemcode = $sub_result[0];
			$p_item_code = $sub_result[0];
			
			if ($itemcode == '' || empty($itemcode)) {
				$ErrorExists = 1;
				$message  = "Insert not allowed. Item not found."; 
				
				echo $message;				
				echo "[BRK]";
				echo $transfer_id;
				exit;
			}	
		}
		
		if ($Item_Unit2Qty == '') $Item_Unit2Qty = 1;
		//$checkqty_query =  "select QtyExistsWSorder('".$itemcode."','".$fromwarehouse."',now(),0,'TR',null,null)";
			$checkqty_query =  " select QtyExists('".$itemcode."','".$fromwarehouse."','".displayParadoxDate(insertDate($transfer_date))." 23:59:59',".$transfer_id.",'TR',null,null)  - q1.qty
							  from (select
									ifnull(sum(TransferDt_Quantity),0) as qty
								  from temp_transferdt where transfer_id='".$transfer_id."' and item_code = '".$itemcode."'
									and transferdt_id <> ".$transferdt_id." )q1";
							
	
		$checkqtyresult=mysql_query($checkqty_query,$connection) or die(mysql_error());
		$checkqtyrows=mysql_fetch_array($checkqtyresult);
		
		
		if (($checkqtyrows[0] < $p_item_quantity)  and (($Module_NegativeQuantity==0) or ($Login_negativeQty==0))  and $Module_ZeroQuantity==0)
		$message = "Quantity%20entered%20can%20not%20exceeds%20".$checkqtyrows[0];
		ELSE
		{
		$upd = "update temp_transferdt set 
				Item_code = '".$itemcode."'
				,TransferDt_Quantity= '".$p_item_quantity."'
				,transferdt_heatno= '".$transferdt_heatno."'
				,TransferDt_Price= '".$p_item_sellingprice1."' ";
				
				if ($Module_DoubleUnit==1)
				$upd = $upd .",Item_Unit2Qty= '".$Item_Unit2Qty."' ";
				
				$upd = $upd .",transferdt_heatno= '".$transferdt_heatno."' ";
				
				$upd = $upd.",Transferdt_remark= ".$p_transferdt_remark." "
							.",TransferDt_BatchNo= ".$TransBatchno." "
							.",TransferDt_packagingNo= ".$TransPackagingno." "
							.",TransferDt_nbrUnit= ".$TransNbrunit." ";
				
		if ($Module_TransferWithOneWh==0)
		$upd = $upd." ,TransferDt_WarehouseFrom = '".$fromwarehouse."'
					,TransferDt_WarehouseTo = '".$towarehouse."' ";
		
				
		$upd = $upd." , transferdt_costbase1 = $costbase1, transferdt_costbase2 = $costbase2, transferdt_chargebase1 = $chargebase1, transferdt_chargebase2 = $chargebase2
					where transferdt_id = ".$transferdt_id;


		$result=mysql_query($upd,$connection) or die(mysql_error());
		
		$upd = "update temp_purchasesserialno set warehouse_code='".$towarehouse."', 
				serialno_date=CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8)) 
				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);	
						$documentrefno = ereg_replace(" ","%20",$documentrefno);	
	//echo $upd	;
	//echo "[BRK]";
	//echo $message;
	exit;
	//header ("Location: ./Form_TransferItems.php?fromproject=$fromproject1&toproject=$toproject1&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&documentrefno=$documentrefno&vehicle_no=$vehicle_no&transferdt_id=$transferdt_id&actionmoded=$actionmoded&item_withserial=$item_withserial&transferdt_id=$transferdt_id&message=$message&transit=$transit&TransType=$TransType");
	}
	else if ($actionmode=='search' and $transfer_id!='')
	
{
	
 //echo "we are hre ";exit;
	$message='';
	$message1='';
	$message2='';
	fbegin();
	//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,ToCostcenter_Code, 
				Journal_id, TransferDt_ID, SendReceive_Reference, Transfer_BelongsToGroup, Synchronized, Adjustment_id, Driver_Name, Document_RefNo , Vehicle_No, f_Date, Requestedby, User_account, Company_Name, 
				Transfer_WarehouseFrom, Transfer_WarehouseTo, Logged_Code,Transfer_Type,Transferrequest_Id, amountBase1, amountBase2, curencycode)
				Select Transfer_Id, Transfer_Reference, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code, ToCostcenter_Code, 
				Journal_id, TransferDt_ID, SendReceive_Reference, Transfer_BelongsToGroup, Synchronized, Adjustment_id, Driver_Name,Document_RefNo, Vehicle_No, f_Date, Requestedby, User_account, Company_Name, 
				Transfer_WarehouseFrom, Transfer_WarehouseTo, '".$_SESSION['useraccount']."','".$TransType."',Transferrequest_Id, amountBase1, amountBase2, curencycode
				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,Item_codefinished,Item_codesemifinished,Transferrequest_Reference,Transferrequestdt_Id,Transferdt_HeatNo, 
				TransferDt_BatchNo, TransferDt_packagingNo,TransferDt_nbrUnit, transferdt_costbase1, transferdt_costbase2, transferdt_chargebase1, transferdt_chargebase2,transferdt_VATchargebase1, transferdt_VATchargebase2)
				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, '".$_SESSION['useraccount']."' ,Item_codefinished,Item_codesemifinished,Transferrequest_Reference,Transferrequestdt_Id,Transferdt_HeatNo, 
				TransferDt_BatchNo, TransferDt_packagingNo,TransferDt_nbrUnit, transferdt_costbase1, transferdt_costbase2, transferdt_chargebase1, transferdt_chargebase2,transferdt_VATchargebase1, transferdt_VATchargebase2
				FROM transferdt  WHERE transfer_id = ".$transfer_id;
				
				//echo $query;exit;
	  
		if (!updateData($connection, $query, true))
			$message1  = 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, '".$_SESSION['useraccount']."' 
				FROM purchasesserialno  WHERE transferdt_id in (select transferdt_id from transferdt where transfer_id = ".$transfer_id.")";
	//echo $query;exit;
		if (!updateData($connection, $query, true))
			$message2  = mysql_error(); 			
			
	$query = " insert into temp_transfercharges (Transfer_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption,
			  Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, transfercharges_remark, ChargesCostcent_code)
			  select Transfer_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption,
			  Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, transfercharges_remark, ChargesCostcent_code
			  from transfercharges where transfer_id = $transfer_id";	
			  
			//  echo $query;exit;
	if (!updateData($connection, $query, true))
			$message3  = mysql_error(); 		  
		
		if ($message!='' || $message1!='' || $message2!='' || $message3 !='')
		frollback();
		else
		fcommit();

		
		if ($message!='')
			$message = ereg_replace(' ','%20',$message);
		if ($message!='')
			header ("Location: ./Form_TransferSearch.php?PMode=1&message=".$message."&transfer_id=".$transfer_id."&TransType=".$TransType);
		else
			header ("Location: ./Form_TransferSearch.php?PMode=1&TransType=".$TransType);
		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?TransType=".$TransType);
		
	}
	else if ($actionmode=='delete')
		{
			$AllowDelete=0;
				//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) {
					$query = "SELECT date_format(transfer_date,'%d/%m/%Y') FROM transfer WHERE transfer_id = ".$transfer_id;
					$result = selectData($connection, $query);
					$txtDate  = $result[0];
			 
					if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $AllowDelete = 1;
					if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $AllowDelete = 1;
					if($AllowDelete==1) $message  = 'Delete not allowed, Exceed Lock Period.';
				}
	
	
	if($AllowDelete==0){
		fbegin();
		
			$queryrel = "select relatedserial_id from purchasesserialno where transferdt_id in(
                              select transferdt_id from transferdt where transfer_id in (select transfer_id from transfer where transfer_id = ".$transfer_id."))";
			$resultrel=mysql_query($queryrel,$connection) or die(mysql_error());
			while ($rowsrel=mysql_fetch_array($resultrel))
				{
				 $queryrel2 = "update purchasesserialno set serialno_used = 0 where serial_id = ".$rowsrel[0];
				 $resultrel2=mysql_query($queryrel2,$connection) or die(mysql_error());
				}
				
		$query ="delete from purchasesserialno where transferdt_id is not null and journal_type='TR' and transferdt_id in (select transferdt_id from transferdt
																		where transfer_id = ".$transfer_id.")";
		$result=mysql_query($query,$connection) or die(mysql_error());
		//hi nadine
		if($config['log_file'] == 1){
			$company = explode("_", $_SESSION['dbName']);
			$currCompany = strtoupper($company[0]);
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$transfer_id', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'transfer', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		$queryj = "select journal_id from transfer where transfer_id = ".$transfer_id; 
		$resj = mysql_query($queryj, $connection);
		$rowj = mysql_fetch_row($resj);
		$journal_id = $rowj[0];
		
		$query ="delete from transferdt where transfer_id = ".$transfer_id;
		$result2=mysql_query($query,$connection) or die(mysql_error());
		
		$query ="delete from transfer where transfer_id = ".$transfer_id;
		$result3=mysql_query($query,$connection) or die(mysql_error());
		
		
			if (!result or !result2 or !result3)
				frollback();
			else{
				fcommit();
				$querycst = "delete from cstjour where journaldt_id in (select journaldt_id from journaldt where journal_id=$journal_id) ";
				$rescst = mysql_query($querycst, $connection);
				
				$querydt = "delete from journaldt where journal_id = $journal_id ";
				$resdt = mysql_query($querydt, $connection);
				
				$queryjv = "delete from journal where journal_id = $journal_id";
				$resjv = mysql_query($queryjv, $connection);
			}
		}
		header ("Location: ./Form_TransferSearch.php?TransType=".$TransType."&message=".$message);
		}
//UnConfirmed Sorder
else if($mainmode == "ConfirmTransfer" && $TrId != ''){

$query = "Update Transfer set transfer_confirmed = 1 where transfer_id = $TrId ";

if (updateData($connection, $query, true))
		$message = "Transfer Confirmed";
	else
		$message  = mysql_error();

		
$query = "Update TransferDt set Synchronized = 1 where transfer_id = $TrId ";		

$result3=mysql_query($query,$connection) or die(mysql_error());echo$fromdate;

echo "<form name='confirmac' method='POST' >";
echo "<input type='hidden' name='fromproject' value='".htmlentities($fromproject1,ENT_QUOTES)."'>";
echo "<input type='hidden' name='toproject' value='".htmlentities($toproject1,ENT_QUOTES)."'>";
echo "<input type='hidden' name='viewproject' value='".htmlentities($viewproject,ENT_QUOTES)."'>";
echo "<input type='hidden' name='keyword' value='".htmlentities($keyword,ENT_QUOTES)."'>";
echo "<input type='hidden' name='showDetails' value='".htmlentities($showDetails,ENT_QUOTES)."'>";
echo "<input type='hidden' name='orderby' value='".htmlentities($orderby,ENT_QUOTES)."'>";
echo "<input type='hidden' name='trStatus' value='".htmlentities($trStatus,ENT_QUOTES)."'>";
echo "<input type='hidden' name='fromdate' value='".htmlentities($fromdate,ENT_QUOTES)."'>";
echo "<input type='hidden' name='todate' value='".htmlentities($todate,ENT_QUOTES)."'>";
echo "<input type='hidden' name='perpage' value='".htmlentities($perpage,ENT_QUOTES)."'>";

echo "</form>";

echo "<script>";
echo " document.confirmac.action='Form_TransferSearch.php?message=".$message."&TransType=".$TransType."';";
echo " document.confirmac.submit();";	
echo"</script>"; 
exit;

}
else if($mainmode == "unconfirmorder" && $SSaId != ''){
	$query = "UPDATE Sorder SET sorder_confirmed = 0 WHERE sorder_id = ".$SSaId."";

	if (updateData($connection, $query, true))
		$message = "Preparation Order Unconfirmed";
	else
		$message  = mysql_error();

		header ("Location: ./Form_Transfer_LoadSorder.php?PMode=1&GeneratedId=".$PGeneratedId."&message=".$message);		
	
}
else if($mainmode == "copyrequest" && $TrReqId != ''){


	fbegin();	
	$vSaId = get_nextsequence('transfer_id','',$connection);	
	fcommit();
	$PGeneratedId = $vSaId;
	
	$query = " select Transferrequest_reference from Transferrequest where Transferrequest_id = ".$TrReqId;
	$result = mysql_query($query,$connection) or die(mysql_error());
	$row=mysql_fetch_array($result);
	$ref = $row[0];
	 
$query = " INSERT INTO Temp_transfer(Transfer_Id, Transfer_Reference, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, 
				Project_code1, Project_code2, Costcenter_Code,ToCostcenter_Code, Journal_id, TransferDt_ID, SendReceive_Reference, Transfer_BelongsToGroup, 
				Synchronized, Adjustment_id, Driver_Name, Document_RefNo , 
				Vehicle_No, f_Date, Requestedby, User_account, Company_Name, Transfer_WarehouseFrom, Transfer_WarehouseTo, Logged_Code,Transfer_Type,Transferrequest_Id)
				Select ".$vSaId.", null, now(), Transferrequest_Remark, Transferrequest_Posted, Transferrequest_Edit, Project_code1, Project_code2, Costcenter_Code, ToCostcenter_Code, Journal_id, TransferrequestDt_ID, SendReceive_Reference, Transferrequest_BelongsToGroup, Synchronized, 
				Adjustment_id, Driver_Name,Document_RefNo, Vehicle_No, f_Date, Requestedby, User_account, Company_Name, Transferrequest_WarehouseFrom, Transferrequest_WarehouseTo
				, '".$_SESSION['useraccount']."','".$TransType."',Transferrequest_Id FROM Transferrequest ".
				" WHERE Transferrequest_id = ".$TrReqId;
	//echo $query."<br>";exit;
	if (!updateData($connection, $query, true))
      $message  = mysql_error(); 	
			 

			
		$query = "Select TransferrequestDt_id, Transferrequest_Id, Transferrequest_Date, Item_Barcode, Item_code, Size_Measure, TransferrequestDt_WarehouseFrom, TransferrequestDt_WarehouseTo, TransferrequestDt_Quantity, TransferrequestDt_ExpireDate, TransferrequestDt_Price, TransferrequestDt_PriceBase1, TransferrequestDt_PriceBase2, Transferrequest_Posted, Project_Code1, Project_Code2, Costcent_Code, Transferrequestdt_remark, Color_Code, Cur_code, 
				Transferrequestdt_posted, PreProduction_Serial, Item_CodePacked, Synchronized, Item_qtyPacked, TransferrequestDt_DirectStkDbt, TransferrequestDt_DirectStkCrd, TransferrequestDt_DirectStkCur, TransferrequestDt_PricePerUnit, TransferrequestDt_QtyUnit, Date, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id
				,'".$_SESSION['useraccount']."' ,Item_codefinished,Item_codesemifinished
				FROM transferrequestdt  WHERE transferrequest_id = ".$TrReqId." and ifnull(upper(TransferrequestDt_status),'r') = 'A' ";
			
		$result = mysql_query($query,$connection) or die(mysql_error());	
		while($row=mysql_fetch_array($result)){
			
			fbegin();
			$vSaDtId = get_nextsequence('transferdt_id','',$connection);	
			fcommit();
		
		
			$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,Item_codefinished,Item_codesemifinished,Transferrequestdt_Id,Transferrequest_reference,
				TransferDt_BatchNo, TransferDt_packagingNo,TransferDt_nbrUnit, transferdt_heatno)
				select ".$vSaDtId.",  ".$vSaId.", now(), Item_Barcode, Item_code, Size_Measure, TransferrequestDt_WarehouseFrom, TransferrequestDt_WarehouseTo, TransferrequestDt_Quantity, TransferrequestDt_ExpireDate, TransferrequestDt_Price, TransferrequestDt_PriceBase1, TransferrequestDt_PriceBase2, Transferrequest_Posted, Project_Code1, Project_Code2, Costcent_Code, Transferrequestdt_remark, Color_Code, Cur_code, 
				Transferrequestdt_posted, PreProduction_Serial, Item_CodePacked, Synchronized, Item_qtyPacked, TransferrequestDt_DirectStkDbt, TransferrequestDt_DirectStkCrd, TransferrequestDt_DirectStkCur, TransferrequestDt_PricePerUnit, TransferrequestDt_QtyUnit, Date, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, relateddt_id
				, '".$_SESSION['useraccount']."' ,Item_codefinished,Item_codesemifinished,Transferrequestdt_Id,'".$ref."', TransferrequestDt_BatchNo,TransferrequestDt_packagingNo,TransferrequestDt_nbrUnit,
				transferrequestdt_heatno
				FROM transferrequestdt  WHERE transferrequestdt_id = ".$row[0]."  and ifnull(upper(TransferrequestDt_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_TransferLoadRequest.php?PMode=1&GeneratedId=".$PGeneratedId."&message=".$message);		
}
//Search Confirmed Sorder
else if($mainmode == "confirmedsorder" && $SSaId != ''){

	if (!isset($PSaCurr))
	   $PSaCurr = $base1;
	   
	fbegin();	
	$vSaId = get_nextsequence('transfer_id','',$connection);	
	fcommit();
	
	$Acc_Query = " SELECT Sale_Acctax1, Sale_Acctax2, Sale_Acctax3, Sale_Acctax4, Sale_Acctax5, if( ifNull(CreditCurdefault,0)=1, CreditCur, '".$PSaCurr."') As CreditCur, ".
				 " CreditAccount, TipsAccount, VatAccount, CreditAccountVAT, PromotionAccount, TransportAccount ".
				 " FROM salessetup ";
					 
	$Acc_Result = selectData($connection, $Acc_Query);
	
		
		$query = " INSERT INTO temp_transfer (Transfer_Id, Transfer_Reference, Sorder_reference, Transfer_Date, Transfer_Remark,  
					Transfer_Posted, Transfer_Edit, Project_code1, Project_code2, Costcenter_Code,ToCostcenter_Code
					,Driver_Name
					,vehicle_no
					,documentrefno
					,Transfer_WarehouseFrom
					,Transfer_Warehouseto
					,transfer_type
					,User_account
					, Logged_Code) ".
				 " SELECT $vSaId, Null, Sorder_reference, now(), Sorder_Remark,
					0,0,".$fromproject.",".$toproject.",'".$costcent."','".$tocostcent."'
					,'".$drivername."'
					,'".$vehicle_no."'
					,'".$documentrefno."'
					,'".$fromwarehouse."'
					,'".$towarehouse."'
					,'TR'
					, Sorder.User_Account, '".$_SESSION['useraccount']."' ".
				 " FROM Sorder  WHERE Sorder_id = ".$SSaId;
	$PGeneratedId = $vSaId;
	//echo $query; 
	//exit;	
	if (updateData($connection, $query, true))
    {   	
		$vSaDtCostBase1  = 0;
		$vSaDtCostBase2  = 0;
		
		
	
			
		
		$sub_query = " SELECT SorderDt_id, Sorderdt.Currency_Code, now(), Sorderdt.Client_Code, Sorderdt.Project_Code, Sorderdt.CostCent_Code, Sorderdt.Warehouse_Code, Sorderdt.Item_code, ".
					 " Sorderdt.Item_CodePacked, ifNull(SorderDt_Quantity,0), ".
					 " ifNull(SorderDt_Price,0), ifNull(SorderDt_PriceBase1,0), ifNull(SroderDt_PriceBase2,0), ifNull(SorderDt_Discount,0), ifNull(SorderDt_DiscountAmount,0), ".
					 " ifNull(SorderDt_DiscountBase1,0), ifNull(SorderDt_DiscountBase2,0), ifNull(Sorderdt.Item_Vat,0), ifNull(SorderDt_PriceTTC,0), SorderDt_Remark, SorderDt_DirectStkDbt, ".
					 " SorderDt_DirectStkCrd, SorderDt_DirectStkCur, SorderDt_ItemAccount, ifNull(Sorderdt.Item_Tax1,0), ifNull(Sorderdt.Item_Tax2,0), ifNull(Sorderdt.Item_Tax3,0), ifNull(Sorderdt.Item_Tax4,0), ".
					 " ifNull(Sorderdt.Item_Tax5,0), ifNull(Sorderdt_posted,0), ifNull(Sorderdt_OldData,0), ifNull(Sorderdt_promotion,0), Sorderdt.Item_UnitCoef, Sorderdt.Item_Unit2Qty, Sorderdt.User_Account, ".
					 " ifNull(item_withserialno,0) As ItemWithSerialNo, ifNull(Item_QtyPacked,0) As Item_QtyPacked ".
					 " FROM Sorderdt Inner Join Items on Sorderdt.Item_Code = Items.Item_Code ".
					 " WHERE Sorder_id = ".$SSaId;
		//echo $sub_query; exit;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($row=mysql_fetch_array($sub_result)){
		
			fbegin();
			$txtSaDtId = get_nextsequence('transferdt_id','',$connection);	
			fcommit();

			
			$vSaDtQty = 0;	
		
			
			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0) ".
					"  FROM Items WHERE item_Code = '".$row[7]."'";
			$result = selectData($connection, $query);
			$item_vat = $result[0];
			$Item_MaxQty = $result[1];
			$ItemGroupCode = $result[2];
			$ItemProd   = $result[3];
			$ItemTTCInc = $result[4];
			$ItemUnit   = $result[5];
			$ItemPromo  = $result[6];
			
				
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = $vItemUnitCoef * $vSaDtQty;
			}
				
			// Get DirectStock Accounts
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, DiscountAccount, VatAccount, CreditAccountVAT, CreditAccount, PromotionAccount  ".
					 " FROM salessetup ";
							 
			$result = selectData($connection, $query);
					
			$vSaStpDirectStkDbt = $result[0];
			$vSaStpDirectStkCrd = $result[1];
			$vSaStpDirectStkCur = $result[2];	
			$vSaStpDiscAcc      = $result[3];	
			$vSaStpVatAcc       = $result[4];	
			$vSaStpCreditVatAcc = $result[5];	
			$vSaStpCreditAcc    = $result[6];	
			$vSaStpPromoAcc     = $result[7];	
					
				
			$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
					 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc, Trans_discountacc, Trans_PromotionAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'TR' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
							 
			$result = selectData($connection, $query);
					
			$vTranStpDirectStkDbt = $result[0];
			$vTranStpDirectStkCrd = $result[1];
			$vTranStpDirectStkCur = $result[2];
			$vTranStpVatAcc       = $result[3];
			$vTranStpNonRmVatAcc  = $result[4];
			$vTranStpRmVatAcc     = $result[5];
			$vTranStpNonRmTTCIncAcc  = $result[6];
			$vTranStpRmTTCIncAcc     = $result[7];
			$vTranStpNonRmAcc        = $result[8];
			$vTranStpRmAcc           = $result[9];
			$vTranStpDiscAcc         = $result[10];
			$vTranStpPromoAcc        = $result[11]; 
					
			if ($Module_RawMaterial == 1) {
				$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vSaDtDirectStkCur = $vTranStpDirectStkCur;
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				$vSaDtPromoAcc     = $vTranStpPromoAcc;
						
				if ($item_vat > 0) {
					if ($ItemProd == 1)	$vSaDtItemAcc = $vTranStpNonRmVatAcc; else $vSaDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vSaDtItemAcc = $vTranStpRmTTCIncAcc; else $vSaDtItemAcc = $vTranStpRmAcc;
					}
				}	
			} 
			else {
				$vSaDtDirectStkDbt = $vSaStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vSaStpDirectStkCrd;
				$vSaDtDirectStkCur = $vSaStpDirectStkCur;		
				$vSaDtVatAcc       = $vSaStpVatAcc;
				$vSaDtDiscAcc      = $vSaStpDiscAcc;
				$vSaDtPromoAcc     = $vSaStpPromoAcc;
						
				if ($item_vat > 0)
					$vSaDtItemAcc = $vSaStpCreditVatAcc;
				else
					$vSaDtItemAcc = $vSaStpCreditAcc;	
												
			}
					
			//Stopped 20120612 due to dajcom request			
			//if (($row[35] == 0 && $vSaDtQty > 0) || ($row[35] == 1) ) {
			
				$query_cost = " select ifNull(MeanCostCur('".$row[7]."', '".$row[2]."', 1, '', ''),0) MeanCostAmountB1 ,  ".
							  " ifNull(MeanCostCur('".$row[7]."', '".$row[2]."', 2, '', ''),0) MeanCostAmountB2 from dual  ";
				$result_cost = selectData($connection, $query_cost);
				
				$vSaDtCostBase1  = $result_cost[0];
				$vSaDtCostBase2  = $result_cost[1];
				if (empty($vSaDtCostBase1)) $vSaDtCostBase1 = 0;
				if (empty($vSaDtCostBase2)) $vSaDtCostBase2 = 0;
				//echo $query_cost; exit;
			
				
				
					$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$row[1]."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$row[1]."' )";
					$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];
					
					$vSaDtPriceTTC      = $row[18];
					$vSaDtPriceTTCBase1 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt1;
					$vSaDtPriceTTCBase2 = ($vSaDtPriceTTC*$rate_dt)/$rate_dt2;	

				/*
				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
				,tocostcent_code,Item_CodeFinished,Item_CodeSemiFinished
			
				*/
				
					fbegin();
					
					//if ($row[35]==1)
					//	$trd_qty=0;
						//else
						$trd_qty=$row[9];
						
					$sub_query1 = " INSERT INTO temp_transferdt (
					transferdt_id,transfer_id,transfer_date,item_code,transferdt_quantity,TransferDt_Price,
					transferdt_pricebase1,transferdt_pricebase2
					,project_code1,project_code2
					,costcent_code,tocostcent_code
					,TransferDt_WarehouseFrom,TransferDt_WarehouseTo
					,transferdt_remark
					,Item_CodeFinished,Item_CodeSemiFinished,Logged_code ";
					if ($Module_DoubleUnit==1)
						$sub_query1 = $sub_query1 .",Item_Unit2Qty,Item_UnitCoef ";
					
					
					$sub_query1 = $sub_query1 ." ) 
					  VALUES ( ".$txtSaDtId.", ".$vSaId.", now(),
					'".$row[7]."','".$trd_qty."','".$row[10]."','".$row[11]."','".$row[12]."'
					,".$fromproject.",".$toproject."
					,'".$costcent."','".$tocostcent."'
					,'".$row[6]."','".$towarehouse."'					
					,'".ereg_replace("'", "\'", trim($row[19]))."',null,null,'".$_SESSION['useraccount']."' ";
					
						if ($Module_DoubleUnit==1 and $Module_Unit1Method == 1)
							$sub_query1 = $sub_query1 .",$ItemUnit * $trd_qty,$ItemUnit ";
						else
						if ($Module_DoubleUnit==1 and $Module_Unit1Method == 0)
							$sub_query1 = $sub_query1 .",$ItemUnit / $trd_qty,$ItemUnit ";
							
							
					$sub_query1 = $sub_query1 .")";
				
				//echo "<br>".$ItemUnit." ".$row[4]." ".$sub_query1."<br>"; 
				//exit;
			$result=mysql_query($sub_query1,$connection);
			
				if ($result){
				fcommit();
			}else{
				$txtSaDtId = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
				
			
			
			}
		
	//exit;
	
}

	
header ("Location: ./Form_Transfer_LoadSorder.php?PMode=1&GeneratedId=".$PGeneratedId."&message=".$message);		
}	
else if ($actionmoded=='CopyTransfer')
{
			fbegin();
						
						$query =  "select null
							  ,null
							  ,CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
							   ,item_code						  
							  ,transferdt_quantity
							  ,TransferDt_Price
							  ,transferdt_pricebase1
							  ,transferdt_pricebase2
							   ,'".$fromwarehouse."'
							  ,'".$towarehouse."'
							  ,transferdt_remark
							  ,'".$_SESSION['useraccount']."'						  
							  ,Item_CodeFinished
							  ,Item_CodeSemiFinished
							  ,transferdt_id
							  ,ifnull(Item_Unit2Qty,0)
							  ,ifnull(Item_UnitCoef,0)
							   from transferdt where transfer_id= '".$loadedtransfer_id."'";
							$result=mysql_query($query,$connection);
							//echo $query;
							
							while ($row=mysql_fetch_array($result)){
							$PTransferdt_id = get_nextsequence('transferdt_id','',$connection);	
						
							$query1 = "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,Item_CodeFinished,Item_CodeSemiFinished,relateddt_id ";
								
								if ($Module_DoubleUnit==1)
									$query1 = $query1 .",Item_Unit2Qty,Item_UnitCoef ";
								
								
								$query1 = $query1 .") values(
								'".$PTransferdt_id."'
							  ,'".$transfer_id."'
							  ,CONCAT('".displayParadoxDate(insertDate($transfer_date))." ', RIGHT(NOW(), 8))
							   ,'".$row[3]."'
							  ,'".$row[4]."'
							  ,'".$row[5]."'
							  ,'".$row[6]."'
							  ,'".$row[7]."'
							   ,'".$row[8]."'
							  ,'".$row[9]."'
							  ,'".$row[10]."'
							  ,'".$_SESSION['useraccount']."'						  
							  ,'".$row[12]."'
							  ,'".$row[13]."'
							  ,'".$row[14]."' ";
							  
							  if ($Module_DoubleUnit==1)
							  $query1 = $query1 .",'".$row[15]."'
												,'".$row[16]."' ";
							  
							  $query1 = $query1 ." )"	;
							  
							$result1=mysql_query($query1,$connection) or die(mysql_error());
							
							//echo $query1."<br>";

								$newid = $PTransferdt_id;
								
								$query2 = "select Serial_ID,journal_type,serialno_code,item_code,transferdt_id,serialno_quantity,Warehouse_code,null,flagunique,PurchaseDt_ID,RelatedSerial_Id
										   FROM purchasesserialno  WHERE transferdt_id = ".$row[14]; 
								$result2=mysql_query($query2,$connection) or die(mysql_error());
								
								while ($row2=mysql_fetch_array($result2)){
								
								$PSerial_id = get_nextsequence('serial_id','',$connection);	
								
								$query3 = " INSERT INTO temp_purchasesserialno 
								(Serial_ID,journal_type,serialno_code,item_code,transferdt_id,serialno_quantity,Warehouse_code,logged_code,flagunique,PurchaseDt_ID,RelatedSerial_Id ) 
								values(
								'".$PSerial_id."'
								,'TR'
								,'".$row2[2]."'
								,'".$row2[3]."'
								,'".$newid."'
								,'".$row2[5]."'
								,'".$towarehouse."'
								,'".$_SESSION['useraccount']."'				
								,'".$row2[8]."'
								,'".$newid."'
								,'".$row2[0]."' )								
								";
								//echo $query3."<br>";
								$result3=mysql_query($query3,$connection) or die(mysql_error());	
								$yy=1;	
									}								
							}
			
			
			
		if ($result3 and $yy==1){
		
		
				fcommit(); }
		else		
		if ($result2 and $yy!=1){
				fcommit();
			}else{
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}
			
	if ($message =='')	
		header ("Location: ./Form_LoadItems.php?transfer_id=".$transfer_id."&costcent=".$costcent."&tocostcent=".$tocostcent);								  
	else	
		header ("Location: ./Form_LoadItems.php?message=$message$transfer_id=".$transfer_id."&costcent=".$costcent."&tocostcent=".$tocostcent);
							

}
else if ($actionmode=='checkitemcode'){

$vitemcode = $_GET["vitemcode"];
$vitemdesc = $_GET["vitemdesc"];
$codedesc = $_GET["codedesc"];

if ($codedesc==1)
	$query = " select item_description,Item_UnitSalesDesc,Item_UnitPurchaseDesc ,item_unit from items where item_code = '".$vitemcode ."' and  ifNull(item_active,0) = 1 ";
	else
	$query = " select item_code,Item_UnitSalesDesc,Item_UnitPurchaseDesc,item_unit from items where item_description = '".$vitemdesc ."' and  ifNull(item_active,0) = 1 ";
	
$result=mysql_query($query,$connection)  or die(mysql_error());
$row=mysql_fetch_row($result);

echo "[BRK]";
if ($row[0]!='')
	echo $row[0];
else	
	echo 0;
echo "[BRK]";	

echo $row[1]."[BRK]";
echo $row[2]."[BRK]";

echo $row[3]."[BRK]";

exit;
}
else if ($actionmode=='checkwarehousecode'){

$vwarehousecode = $_GET["vwarehousecode"];

$query = " select warehouse_code from warehouse where warehouse_code = '".$vwarehousecode ."' ";
$result=mysql_query($query,$connection)  or die(mysql_error());
$row=mysql_fetch_row($result);

echo "[BRK]";
if ($row[0]!='')
	echo $row[0];
else	
	echo 0;
echo "[BRK]";	
}


else if ($actionmode == 'duplicateTransfer' && $transfer_id != ''){
	$errorExist = 0;
	
	fbegin();
	$PTransferId = get_nextsequence('transfer_id','',$connection);	
	fcommit();
	
	fbegin();
	$queryheader = "insert into temp_transfer ( Transfer_Id, Transfer_Reference, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, Journal_id, Project_code1, Project_code2, Costcenter_Code, TransferDt_ID,
					SendReceive_Reference, Transfer_BelongsToGroup, Synchronized, Adjustment_id, documentrefno, Driver_Name, Vehicle_No, Requestedby, User_account, transfer_warehousefrom,
					transfer_warehouseto, ToCostcenter_Code, Company_Name, f_Date, Document_RefNo, Transfer_Type, BRANCH_CODE, PTRANSFER_id, Transfer_LOADHHT, Logged_Code )
					select $PTransferId, NULL, Transfer_Date, Transfer_Remark, Transfer_Posted, Transfer_Edit, Journal_id, Project_code1, Project_code2, Costcenter_Code, TransferDt_ID,
					SendReceive_Reference, Transfer_BelongsToGroup, Synchronized, Adjustment_id, documentrefno, Driver_Name, Vehicle_No, Requestedby, '".$_SESSION['useraccount']."', transfer_warehousefrom,
					transfer_warehouseto, ToCostcenter_Code, Company_Name, f_Date, Document_RefNo, Transfer_Type, BRANCH_CODE, PTRANSFER_id, Transfer_LOADHHT, '".$_SESSION['useraccount']."' 					
					from transfer
					where transfer_id = $transfer_id ";
	$resheader = mysql_query($queryheader, $connection);
	if ($resheader){
		fcommit();
		$errorExist = 0;
	} else {
		frollback();
		$message = mysql_error(); 		
		$errorExist = 1;
	}
	
	if ($errorExist == 0){
		
		
		$querydt = "select Transfer_Date, Item_Barcode, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity, TransferDt_ExpireDate,
					TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Project_code1, Project_code2, Costcent_Code, SIZE_MEASURE, Transferdt_remark, Color_Code, TRANSFER_POSTED,
					Cur_code, Transferdt_posted, PreProduction_Serial, Item_CodePacked, Synchronized, Item_qtyPacked, TransferDt_DirectStkDbt, TransferDt_DirectStkCrd, TransferDt_DirectStkCur,
					TransferDt_PricePerUnit, TransferDt_QtyUnit, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, ToCostcent_Code, Date, Item_CodeFinished, Item_CodeSemiFinished,
					transferdt_heatno, TransferDt_BatchNo, TransferDt_packagingNo, TransferDt_nbrUnit
					from transferdt
					where transfer_id = $transfer_id ";
		$resdt = mysql_query($querydt, $connection);	
		while($rwdt = mysql_fetch_array($resdt)){
			fbegin();
				$PTransferDtId = get_nextsequence('transferdt_id','',$connection);	
			fcommit();
			$queryins = "insert into temp_transferdt (TransferDt_id, Transfer_Id, Transfer_Date, Item_Barcode, Item_code, TransferDt_WarehouseFrom, TransferDt_WarehouseTo, TransferDt_Quantity, TransferDt_ExpireDate,
					TransferDt_Price, TransferDt_PriceBase1, TransferDt_PriceBase2, Project_code1, Project_code2, Costcent_Code, SIZE_MEASURE, Transferdt_remark, Color_Code, TRANSFER_POSTED,
					Cur_code, Transferdt_posted, PreProduction_Serial, Item_CodePacked, Synchronized, Item_qtyPacked, TransferDt_DirectStkDbt, TransferDt_DirectStkCrd, TransferDt_DirectStkCur,
					TransferDt_PricePerUnit, TransferDt_QtyUnit, Item_ManufacturedCode, Item_UnitCoef, Item_Unit2Qty, ToCostcent_Code, Date, Item_CodeFinished, Item_CodeSemiFinished,
					transferdt_heatno, TransferDt_BatchNo, TransferDt_packagingNo, TransferDt_nbrUnit, Logged_Code) values ".
					"($PTransferDtId, $PTransferId, '$rwdt[0]', ".strformat($rwdt[1]).", ".strformat($rwdt[2]).", ".strformat($rwdt[3]).", ".strformat($rwdt[4]).", ".strformat($rwdt[5]).", ".strformat($rwdt[6]).",". 
					" ".strformat($rwdt[7]).", ".strformat($rwdt[8]).", ".strformat($rwdt[9]).", ".strformat($rwdt[10]).", ".strformat($rwdt[11]).", ".strformat($rwdt[12]).",".strformat($rwdt[13]).", ".strformat($rwdt[14]).", 
					".strformat($rwdt[15]).", ".strformat($rwdt[16]).", ".
					" ".strformat($rwdt[17]).", ".strformat($rwdt[18]).", ".strformat($rwdt[19]).", ".strformat($rwdt[20]).", ".strformat($rwdt[21]).", ".strformat($rwdt[22]).", ".strformat($rwdt[23]).", 
					".strformat($rwdt[24]).", ".strformat($rwdt[25]).", ".
					" ".strformat($rwdt[26]).", ".strformat($rwdt[27]).", ".strformat($rwdt[28]).", ".strformat($rwdt[29]).", ".strformat($rwdt[30]).", ".strformat($rwdt[31]).", ".strformat($rwdt[32]).", 
					".strformat($rwdt[33]).", ".strformat($rwdt[34])." , ".
					" ".strformat($rwdt[35]).", ".strformat($rwdt[36]).", ".strformat($rwdt[37]).", ".strformat($rwdt[38]).", '".$_SESSION['useraccount']."' )";	
			$resins = mysql_query($queryins, $connection);			
		}		
	}
	
	if ($errorExist == 0)
		header ("Location: ./Form_TransferSearch.php?message=Transfer%20has%20been%20copied&TransType=".$TransType);
	else
		header ("Location: ./Form_TransferSearch.php?message=".$message."&TransType=".$TransType);
	exit;
}
	
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;
	}
}
function insertMySQLDate($data){
	$data = insertDate($data);
	return substr($data, 0, 4) ."-". substr($data, 4, 2) ."-".substr($data, 6, 2)." ".strftime("%H").":".strftime("%M").":".strftime("%S");;
}

function dateDiff ($d1, $d2) {
	return round(abs(strtotime($d1)-strtotime($d2))/86400);
}

function displayToday(){
	return strftime("%d")."/".strftime("%m")."/".strftime("%Y");
}
	//Return Date in YYYY-MM-DD HH:MM:SS format. Supplied Format: DD/MM/YYYY

function ConvertCurrency($FromCurr, $ToCurr, $FromDate, $Amount, $connection)
	{
		$query = "SELECT ifNull(convertcurfunc('".$FromCurr."', '".$ToCurr."', '".$FromDate."', 0, 0, '', '', ifNull($Amount,0)),0) From Dual ";//echo $query;
		$result = selectData($connection, $query);
		
		Return	$result[0];

	}

function strformat($str){
	if($str == '') $str = "NULL";
	else $str = "'".ereg_replace("'", "\'", trim($str))."'";
	return $str;
}

function calculateCharge($transfer_id, $base1, $base2, $FromDate, $connection){
	$querytot = "select sum(TransferDt_Quantity*(if (curencycode = '$base1', transferdt_costbase1, transferdt_costbase2))), if (curencycode = '$base1', amountBase1, amountBase2), curencycode
				from temp_transferdt
				inner join temp_transfer on temp_transfer.transfer_id = temp_transferdt.transfer_id
				where temp_transferdt.transfer_id = $transfer_id
				group by temp_transferdt.transfer_id";
	$resulttot = mysql_query($querytot, $connection);			
	$rowtot = mysql_fetch_row($resulttot);
	
	$SumQtyCost = $rowtot[0];
	$amount 	= $rowtot[1];
	$curr   	= $rowtot[2];
	
	$querydt = "select TransferDt_Quantity, if('$curr'='$base1', transferdt_costbase1, transferdt_costbase2), transferdt_id
				from temp_transferdt
				where transfer_id = $transfer_id";
	$resdt = mysql_query($querydt, $connection);			
	while ($rwdt = mysql_fetch_array($resdt)){
		$qty  			= $rwdt[0];
		$cost 			= $rwdt[1];
		$transferdt_id  = $rwdt[2];
		
		if ($cost == '') $cost = 0;
		if ($cost != 0)
			$chargeamount = (($qty*$cost*$amount)/($SumQtyCost))/$qty;
		else $chargeamount = 0;
		
		$chargeamountB1 = ConvertCurrency($curr, $base1, $FromDate, $chargeamount, $connection);
		$chargeamountB2 = ConvertCurrency($curr, $base2, $FromDate, $chargeamount, $connection);
		
		if ($chargeamountB1 == '') $chargeamountB1 = 0;
		if ($chargeamountB2 == '') $chargeamountB2 = 0;
		
		$queryup = "update temp_transferdt set transferdt_chargebase1 = $chargeamountB1, transferdt_chargebase2 = $chargeamountB2
					where transferdt_id = $transferdt_id ";
		$resup = mysql_query($queryup, $connection);
	}
}


function Create_TransferJv($PTransfer_id, $DbName, $DbLabel, $UserAccount, $UserName) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	fbegin();
	$resultvars = mysql_query("set @id :=0 ", $conn);

	$query = " call Create_transferAutoJv(".$PTransfer_id.", 0, '".$DbName."', '".$DbLabel."', '".$UserAccount."', '".$UserName."', 0, @id) "; //echo $query;exit;
	$result = mysql_query($query,$conn);
    $error = mysql_error();
	
	$query1 = " select @id from dual ";
	$result1 = mysql_query($query1,$conn) or die(mysql_error());
	$cur1 = mysql_fetch_row($result1);
	

	fcommit();
	
	
    if ($cur1[0] == -2)
	   $error = 'Error In Procedure Create_PurchaseAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_PurchaseJv: '.$error;

	Return $error;
	

}

?>