<?php

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

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

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

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


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


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

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, Setup_SorderMailMsg, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage, 
			 ifnull(Project_FromItems,0) as Project_FromItems, ifnull(costcentminimum,0) as costcentminimum 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 Module_AdditionalTaxes, ifNull(module_negativeSorder,0) As Module_NegativeQuantity, ifNull(Module_rawmaterial,0) As Module_RawMaterial, ".
			 " ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(module_paymentterms,0) As Module_PaymentTerms, ".
             " ifNull(module_creditlimit,0) As Module_CreditLimit, ifNull(Module_SorderAutoConfirm,0) As Module_SorderAutoConfirm, ".
             " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_CreditLimitByProj,0) As Module_CreditLimitByProj, ifNull(Module_SendSorderMail,0) As Module_SendSorderMail, ".
			 " ifNull(Module_SorderCheckQtyOnPost,0) As Module_SorderCheckQtyOnPost, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_CreditLimitCheckPend,0) As Module_CreditLimitCheckPend, ifNull(Module_GenerateSorderJV,0) As Module_GenerateSorderJV ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC, TransportAccount, ClientCur From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}
$querySalesSetup="Select ifnull(SubItem_Production,0) as SubItem_Production,ifnull(show_discountAmount,0) as show_discountAmount From SorderSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

$SubItem_Production = 1;

//User Access
$querylog=" select ifNull(Fa_clientpaymentterms,0) As FA_ClientPaymentTerms, ifNull(Clientscreditlimit,0) As FA_ClientCreditLimit, ".
          " ifNull(login_belongstogrp,0) As FI_BelongsToGrp, ifNull(FI_SorderRejectUnconfirmed,0) As FI_SorderRejectUnconfirmed, ".
		  " ifNull(Login_SOrderNegativeQty,0) As Login_negativeQty, ifNull(FI_AllowEditIfDelivered,0) As FI_AllowEditIfDelivered, ".
		  " ifNull(Perc_CreditLimit,0) As Perc_CreditLimit, ifNull(FI_SorderAllowConfirmCash,0) As FI_SorderAllowConfirmCash,".
		  " ifNull(FI_SalebelowCost,0) as FI_SalebelowCost ".
		  " 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);
}

$queryuser = "select ifNull(Fa_clientpaymentterms,0) As FA_ClientPaymentTerms from ".$_SESSION['dbLabel'].".users where user_account='".$_SESSION['useraccount']."';";
/*
print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<script type="text/javascript" language="javascript">


</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>
<body>
<form name='insertsorder' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SSorId' value='$SSorId'>
<input type='text' name='SSorDtId' value='$SSorDtId'>
<input type='text' name='SOption' value='$SOption'>
<input type='text' name='SSorVatChkbx' value='$SSorVatChkbx'>
HERE;

*/

$message = '';

 if ($mode == "checkduplicate" ){

//$disc = GetDiscountValue($PItem,$vSaClient,$connection);

$query = " select  GetDiscountValue('".$vSaClient."','".$PItem."'),ifnull(client_discountonInvoice,0),ifNull(Client_PaymentTerms,0) from Clients where ledger_number = '".$vSaClient."'";
$result=mysql_query($query, $connection) or die(mysql_error());
$row=mysql_fetch_array($result);
$disc=$row[0];
if($disc == '') $disc = 0;
$client_discountonInvoice=$row[1];
if($client_discountonInvoice=='') $client_discountonInvoice=0;
$Client_PaymentTerms=$row[2];

$query = " select  1 from temp_sorderdt where item_code='".$PItem."' and sorder_id = '".$SSaId."'";

$result=mysql_query($query, $connection) or die(mysql_error());
$row=mysql_fetch_row($result);
echo $row[0];
echo "[BRK]";
echo $disc; 
echo "[BRK]";
echo $client_discountonInvoice;
echo "[BRK]";
echo $Client_PaymentTerms;
exit;
}
else
if ($mode == "getclientname"){
	
		$query = "SELECT Ledger_number,Ledger_name,client_discountonInvoice 
					FROM Clients ";
					
		if($choice==0)
			$query = $query." WHERE Upper(Ledger_number) = Upper('".str_replace('\\','\\\\',$clientcode)."') ";
		else
			$query = $query." WHERE Upper(Ledger_name) = Upper('".str_replace('\\','\\\\',$clientcode)."') ";
					
		$result = selectData($connection, $query);
		$ClientCode = $result[0];
		$ClientName = $result[1];
		$client_discountonInvoice = $result[2];
		echo"[BRK]";
		echo $ClientCode;
		echo"[BRK]";
		echo $ClientName;
		echo"[BRK]";
		echo $client_discountonInvoice;
 
exit;
} 
if ($mode == "transfer") {


$query = " select Transfer_WarehouseTo from sordersetup ";
$resultSalesOrderSetup=mysql_query($query,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesOrderSetup)){
	extract($rowSalesSetup);
}


//Get Default Project
$querydflproject="select project_code as defaultproject from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_project=1 ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}

//Get Default Coscenter
$querydflcostcent="select costcent_code as defaultcostcent from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_costcenter=1 ";
$resultdflcostcent=mysql_query($querydflcostcent,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflcostcent)){
	extract($rows);
}


if ($Transfer_WarehouseTo=='')
						$message = 'No default warehouse set.';
else {
		$query = "select Sorder_date,Sorder_reference,Project_Code,Costcent_code,Sorder_remark from sorder where sorder_id = ".$SorId;
		$result=mysql_query($query,$connection) or die(mysql_error());
		while($row=mysql_fetch_array($result)){
			extract($row);
	}


	fbegin();
	if($Module_ReferenceByCostcenter==1)
		$vTrRef = get_nextsequence('transfer_reference',$Costcent_code,$connection);
	else	
		$vTrRef = get_nextsequence('transfer_reference','',$connection);
	fcommit();


	fbegin();
	$PTransferId = get_nextsequence('transfer_id','',$connection);	
	fcommit();
				
fbegin();			
$query = "insert into transfer(Transfer_Id,Transfer_Reference,Transfer_Date,Transfer_Remark,Project_code1,Project_code2,costcenter_code,User_account,Transfer_Type)
						 values ($PTransferId,$vTrRef,'$Sorder_date','Auto Transfer From Sales Order #: $SorRef','$Project_Code','$defaultproject','$Costcent_code','".$_SESSION['useraccount']."','TR')";
						// echo $query."<bR>";
						// exit;
$result = mysql_query($query);


$query = "insert into transferdt(transferdt_id,transfer_id,Transfer_Date,Item_code,Project_Code1,Project_Code2,Costcent_Code,Transferdt_remark,TransferDt_WarehouseFrom,TransferDt_WarehouseTo,TransferDt_Quantity,cur_code) 
				select NextSequence('Transferdt_id',''),$PTransferId,'$Sorder_date',item_code,Project_Code ,'$defaultproject',CostCent_Code
							,SorderDt_Remark,Warehouse_Code,'$Transfer_WarehouseTo',SorderDt_Quantity,Currency_Code 
							from sorderdt where sorder_id = $SorId ";
//echo $query."<bR>";							
$result2 = mysql_query($query);


$query = " update SorderDT set SorderDT.Warehouse_Code = '$Transfer_WarehouseTo' where Sorder_id = $SorId ";
//echo $query."<bR>";
$result3 = mysql_query($query);		


$query = " update Sorder set transfer_id = $PTransferId where Sorder_id = $SorId ";
//echo $query."<bR>";
$result4 = mysql_query($query);												 
	  
	  
		if($result && $result2 && $result3 && $result4) {
			fcommit();
			$message = 'It had been transfered to Ref: '.$vTrRef;
			}
		else
			frollback();
			
}



header ("Location: ./Form_SalesOrderSearch.php?mode=transfer&startrange=".$startrange."&perpage=".$perpage."&message=".$message);
}
else
//Submit Record Mode
if ($mode == "submitrecord" || $mode == "submitrecord-ajax"){
	
	$ErrorExists = 0;
	
	if ($txtAssignedUser == '') $txtAssignedUser = $_SESSION['useraccount'];
	
	if (!isset($PSorCurr))
	   $PSorCurr = $base1;
	   
	if (!isset($sorder_export))
	   $sorder_export = 0;
	   
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSorCurr."' )";
	$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];
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PSorCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PSorCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PSorProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PSorProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}	
	}
	if ($PSorClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PSorClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Code.';
		}
	}
	if ($PSorSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSorSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Salesman Code.';
		}
	}
	if ($PSorClientDtCode != '') {
		$sub_query = " Select Count(Detail_Code) From ClientsDetail ".
					 " Where Detail_Code = '".$PSorClientDtCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Detail Code.';
		}
	}
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if($FI_SalebelowCost == 0){ // jp
		$sub_queryX = " select ifNull(Item_Promotion, 0)  from items where item_code = '".$txtItemCode."'"; 
		$sub_resultX = selectData($connection, $sub_queryX);
		$itemisPromo = $sub_resultX[0];
		if( $itemisPromo == 0){
			$sub_query = " select meancostcur('".$txtItemCode."', now() ,1, '$base1','$base1'); "; 
			$sub_result = selectData($connection, $sub_query);
			if($sub_result[0] > $txtSorDtPrice ){
				$ErrorExists = 1;
				$message = 'Insert not allowed. Price Below Cost.';
			}
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	


	//Insert Master Table
	if ($SSorId == "" && $ErrorExists == 0){
	
		if (empty($PSorDiscountAmt))
			$PSorDiscountAmt = 0;
		if (empty($PSorDiscount))
			$PSorDiscount = 0;
			
		$PSorCostCentCode = "".$PSorCostCentCode;
		$PSorProjectCode = "".$PSorProjectCode;
		
		if ($PSorCostCentCode == '')
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSorCostCentCode."'";
			
		if ($PSorProjectCode == '')
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSorProjectCode."'";
			
		if (empty($PSorClientDtCode)) $ClientDtCode = 'Null';
		else	$ClientDtCode = "'".$PSorClientDtCode."'";	
		
		if (empty($PVehicleWeight)) $PVehicleWeight = 0;
		if (empty($PPayMode)) $PPayMode = 0;
			
		fbegin();	
		$PSorId = get_nextsequence('sorder_id','',$connection);	
		fcommit();

		//$query = "SELECT Client_CashMode FROM Clients WHERE Ledger_Number = '".$PSorClientCode."'";
		//echo "<br><br>".$query;
		//$result = selectData($connection, $query);
		//$c_cashmode = $result[0];
		//if ($c_cashmode == 1 && $Module_SorderAutoConfirm == 1) $SorderConfirmed = 1; else $SorderConfirmed = 0; 
		
		if ($Module_SorderAutoConfirm == 1) $SorderConfirmed = 1; else $SorderConfirmed = 0; 
		
		// Get Vat Checkbox From Client
		$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSorClientCode."'";
		$result = selectData($connection, $query);
		$PSorVatChkbx = $result[0];
		if($sorder_export=='') $sorder_export=0;
		fbegin();
		$sorder_date         = $_GET['sorder_date'];
		$sorder_card_msg     = $_GET['sorder_card_msg'];
		$sorder_contact      = $_GET['sorder_contact'];
		$sorder_contactphone = $_GET['sorder_contactphone']; 
		if($sorder_date == '') $sorder_date = $PSorDate;
		
		$query = " INSERT INTO temp_sorder (Sorder_id, Sorder_Reference, Sorder_Date, Sorder_RequestDate, Sorder_MaturityDate, Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryPlace, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Sorder_Posted, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, ".
				 " Sorder_DiscountBase2, Sorder_DiscountPer, Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_VatChckbx, Sorder_confirmed, Sorder_disapproved, Sorder_type, Sorder_TotalQuantity, Sorder_TotalQuantityUsed, ".
				 " Sorder_Paymentmode, Journal_Type, Journal_Id, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, Sorder_Status, Sorder_DriverName, Sorder_VehicalNo, Sorder_VehicleWeight, Sorder_TransportAccount, User_Account, Logged_Code, ".
				 " Sorder_Export, Sorder_ClientSorderDate, Sorder_ShippingWay, Sorder_ShipName, Sorder_ClientPhone, assignto_user) ".
				 " VALUES ( ".$PSorId.", Null,  '".insertMySQLDate($PSorDate)."', '".insertMySQLDate($PSorRequestDate)."', ".
				 "          '".insertMySQLDate($PSorMaturityDate)."', '".ereg_replace("'", "\'", trim($PSorRemark))."', '".ereg_replace("'", "\'", trim($PSorClientCode))."', ".
				 "          '".ereg_replace("'", "\'", trim($PSorIAddress))."', '".ereg_replace("'", "\'", trim($PSorDAddress))."', '".ereg_replace("'", "\'", trim($PSorSalesmanCode))."', '".$PSorCurr."', ".
				 "          $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PSorVatChkbx, $SorderConfirmed, 0, '".$PSorType."', 0, 0, $PPayMode, 'SO', Null, 0, $FI_BelongsToGrp, $ClientDtCode, 0, ".
				 "          '".ereg_replace("'", "\'", trim($PDriverName))."', '".ereg_replace("'", "\'", trim($PVehicalNo))."', $PVehicleWeight, '".$TransportAccount."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."',$sorder_export, 
				 '".insertMySQLDate($sorder_date)."', '".$sorder_card_msg."', '".$sorder_contact."', '".$sorder_contactphone."', '".$txtAssignedUser."')";
					 
			 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SSorId = $PSorId;
			fcommit();
		}else{
			$PSorId = "";
			$SSorId = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
	
	}

	//Insert Detail Tables
	if ($SSorId != "" && $SSorDtId == "" && $txtItemCode != ""  && $ErrorExists == 0){
	
		if (empty($PSorDiscountAmt))
			$PSorDiscountAmt = 0;
		if (empty($PSorDiscount))
			$PSorDiscount = 0;
			
		if (empty($txtSorDtPrice))
			$txtSorDtPrice = 0;
		if (empty($txtSorDtDiscount))
		   $txtSorDtDiscount = 0;
		if (empty($txtSorDtDiscountAmt))
		   $txtSorDtDiscountAmt = 0;
		if (empty($txtSorDtOQty))
		   $txtSorDtOQty = 0;      
		if (empty($txtSorDtCQty))
		   $txtSorDtCQty = 0;      
		if (empty($txtSorDtQty))
		   $txtSorDtQty = 0;      	
		if (empty($txtSorDtQty2))
		   $txtSorDtQty2 = 0;      	  
		if (empty($sorderdt_promo))
		   $sorderdt_promo = 0; 
	   if (empty($PProdQty))
		   $PProdQty = 0; 
	   if (empty($PSentProd))
		   $PSentProd = 0;    
	   
			if (empty($sorderdt_quantitybox))
				$sorderdt_quantitybox = 0;      	  
			
			if (empty($sorderdt_itemunit))
				$sorderdt_itemunit = 0;      	  
			
			if (empty($sorderdt_itempackage))
				$sorderdt_itempackage = 0;      	  
					
			
		$PSorCostCentCode = "".$PSorCostCentCode;
		$PSorProjectCode = "".$PSorProjectCode;
		if ($PSorCostCentCode == '')
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSorCostCentCode."'";
			
		if ($PSorProjectCode == '')
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSorProjectCode."'";	
		
		$txtProjectCodeDt = "".$txtProjectCodeDt;
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}
		
		
		$vSorDtPriceTTC      = 0;
		$vSorDtPriceTTCBase1 = 0;
		$vSorDtPriceTTCBase2 = 0;					
		$vSorDtPrice      	 = 0;
		$vSorDtPriceBase1	 = 0;
		$vSorDtPriceBase2	 = 0;
		$vSorDtDiscAmt       = 0;
		$vSorDtDiscAmtBase1  = 0;
		$vSorDtDiscAmtBase2  = 0;
		$vItemVat = 0;
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vSorDtTax1 = 0;
		$vSorDtTax2 = 0;
		$vSorDtTax3 = 0;
		$vSorDtTax4 = 0;
		$vSorDtTax5 = 0;
		
		
		$InsertAllow = 1;
		$QtyExistExceeded   = 0;
		if($costcentminimum == 1 && $CostCentCodeDt != ''){
			$query = "select ifnull(min(min_price),0) from costcenterPrice where costcenter_code = $CostCentCodeDt and item_code = '$txtItemCode';";
			$result = mysql_query($query,$connection);
			$rw = mysql_fetch_row($result);
			$min_price = $rw[0];
			if($min_price == '') $min_price = 0;
			if($min_price != 0 && $min_price > $txtSorDtPrice){
				$InsertAllow=0;
				$message = "Price should be greater than or equal to $min_price";
			}		
		}
		//Check If Item Exists In SorderDt, If So Stop User
		/*$query = " Select Count(*) ".
				 " From Temp_SorderDt As SorderDt ".
				 " Inner Join Items on Items.Item_Code = SorderDt.Item_Code ".
				 " Where Sorder_ID = '".$SSorId."' ";
				 
		if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All")		 
			$query = $query." And SorderDt.Item_Code = '".$txtItemCode."' ".
							" And SorderDt.Warehouse_Code = '".$lstWarehouse."' ".
							" And (SorderDt.Item_CodePacked is null or SorderDt.Item_CodePacked  = '') ";
		else
			$query = $query." And Item_CodePacked = '".$txtItemCode."' ".
							" And SorderDt.Warehouse_Code = '".$lstWarehouse."' ".
							" And (SorderDt.Item_CodePacked is not null and SorderDt.Item_CodePacked  != '') ";
				 
		//echo $query; exit;		 
		$result = selectData($connection, $query);
		if(empty($result[0])) $result[0] = 0;
		if ($result[0] > 0) {
			$InsertAllow = 0;
			$message = "Insert not allowed, duplicate item.";
		}*/
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		
		if ($InsertAllow == 1) {
		
			// Case Not Pack Item
			//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
			if ($ItemPack != 1) {


				$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
						" FROM Items WHERE item_Code = '".$txtItemCode."'";
				$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];
				$ItemNonStock  = $result[7];
				//$item_vat = $item_vat/100;
				$tax_flag = 0;
				$notax_flag = 1;
				if ($item_vat > 0){
					$tax_flag = 1;
					$notax_flag = 0;
				}	
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					/*if ($ItemUnit > 0) {
						$vItemUnitCoef = 1/$ItemUnit;
						$vItemUnit2Qty = $vItemUnitCoef * $txtSorDtOQty;
					}*/
					
					$vItemUnitCoef = $ItemUnit;
					$vItemUnit2Qty = $txtSorDtQty2;
				
				}
				
				//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
				if ($ItemNonStock == 0 && $Module_SorderCheckQtyOnPost == 1) {
					$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PSorDate)."', 0, 'SO', '', '') QtyExists From Dual ";
					$sub_result = selectData($connection, $sub_query);
					$vItemQtyExists = 0;
					$vItemQtyExists = $sub_result[0];
					
					$sub_query1 = " Select ifNull(Sum(ifNull(TransferDt_Quantity,0)),0) FROM Temp_TransferDt ".
								  " WHERE Item_code = '".$txtItemCode."'  And  TransferDt_WarehouseFrom = '".$lstWarehouse."' ";
					$sub_result1 = selectData($connection, $sub_query1);
					if (empty($sub_result1[0])) $sub_result1[0] = 0;
					
					$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
					
						
					if (abs($txtSorDtQty) > $vItemQtyExists && abs($txtSorDtQty) > 0 && ($PSorType == 'SO' || $PSorType==''))
						$QtyExistExceeded = 1;
				}
				
				
				if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
					fbegin();
					$txtSorDtId = get_nextsequence('sorderdt_id','',$connection);	
					fcommit();

					$txtSorDtQty = $txtSorDtOQty - $txtSorDtCQty;
					//if item promotion the set price to zero
					// jp & tony  stopped no need to make the price = 0 
					// if($ItemPromo == 1 || $sorderdt_promo == 1) $txtSorDtPrice = 0;
					
					if ($SalesTTC == 1) {
						$vSorDtPriceTTC      = $txtSorDtPrice;
						$vSorDtPriceTTCBase1 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt1;
						$vSorDtPriceTTCBase2 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt2;	

						//Added 2011/10/27
						//if ($PSorVatChkbx == 1)	$vSorDtPrice = ($vSorDtPriceTTC / (1 + $item_vat/100));
						//else $vSorDtPrice = $txtSorDtPrice;					
					
						$vSorDtPrice      = ($vSorDtPriceTTC / (1 + $item_vat/100));
						$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
						$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
								
					} else	{
						$vSorDtPrice      = $txtSorDtPrice;
						$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
						$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
						
						$vSorDtPriceTTC      = 0;
						$vSorDtPriceTTCBase1 = 0;
						$vSorDtPriceTTCBase2 = 0;
								
					}	
						
					
					// Calculation For Detail Discount Amount
					if($show_discountAmount == 1)
					$vSorDtDiscAmt = $txtSorDtDiscountAmt;
					else 
					$vSorDtDiscAmt       = ((($vSorDtPrice*$txtSorDtQty) - ($vSorDtPrice*$txtSorDtQty*$txtSorDtDiscount/100))*$PSorDiscount)/100;
					$vSorDtDiscAmtBase1  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt1;
					$vSorDtDiscAmtBase2  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt2;

					if ($Module_AdditionalTaxes == 1) {
						
						// Calculation of Item Tax Amounts
						$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
								 " FROM Clients ".
								 " WHERE Ledger_number = '".$PSorClientCode."'";
												 
						$result = selectData($connection, $query);
						$vCltTax1 = $result[0];
						$vCltTax2 = $result[1];
						$vCltTax3 = $result[2];
						$vCltTax4 = $result[3];
						$vCltTax5 = $result[4];
										
						$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
								 " FROM Items ".
								 " WHERE Item_Code = '".$txtItemCode."'";
												 
						$result = selectData($connection, $query);

							
						if ($vCltTax1 != 0)	$vSorDtTax1 = $result[0];
						if ($vCltTax2 != 0)	$vSorDtTax2 = $result[1];
						if ($vCltTax3 != 0)	$vSorDtTax3 = $result[2];
						if ($vCltTax4 != 0)	$vSorDtTax4 = $result[3];
						if ($vCltTax5 != 0)	$vSorDtTax5 = $result[4];
								
					}
					
					
					// 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, ".
							 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'SO' ".
							 " 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]; 
					$vSaDtWasteDbt 			= $result[12]; 
					$vSaDtWasteCrd 			= $result[13]; 
					$vSaDtExportAcc 		= $result[14]; 
					//$vSaDtChkGeneralAcc		= $result[15]; 
					 
					if ($Module_RawMaterial == 1 || $SubItem_Production == 1) {
						$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vSaDtDirectStkCur = $vTranStpDirectStkCur;
						$vSaDtVatAcc       = $vTranStpVatAcc;
						$vSaDtDiscAcc      = $vTranStpDiscAcc;
						$vSaDtPromoAcc     = $vTranStpPromoAcc;
						
						//if($vSaDtChkGeneralAcc == 0){
							if ($item_vat > 0 && $PSorVatChkbx == 1) {
								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 && $PSorVatChkbx == 1)
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditAcc;	
								
					}
					
					$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtDirectStkDbt."') from dual ";

					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vSaDtDirectStkDbt = $sub_resultVat[0];
					
					$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtDirectStkCrd."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vSaDtDirectStkCrd = $sub_resultVat[0];
					
					$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtWasteDbt."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
					
					$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtWasteCrd."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
				
					if($sorderdt_clientdiscount=='') $sorderdt_clientdiscount=0;
					if($sorderdt_itemdiscount=='')  $sorderdt_itemdiscount=0;

					
					fbegin();
					
					$query = " INSERT INTO temp_sorderdt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
							 " SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
							 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, Sorderdt_promotion, Sorderdt_ItemAccount, Logged_Code, sorderdt_quantitybox, sorderdt_itemunit, sorderdt_itempackage,".
							 " sorderdt_clientdiscount,sorderdt_itemdiscount, Sorderdt_DirectStkDbt,Sorderdt_DirectStkCrd, Sorderdt_DirectStkCur, Sorderdt_DirectWasteDbt, Sorderdt_DirectWasteCrd, Sorderdt_exportAccount, Sorderdt_PromoAcc, ".
							 " sorderdt_ProdQty, sorderdt_sentProduction) ".
							 " VALUES ( ".$txtSorDtId.", ".$PSorId.", '".$PSorCurr."', '".insertMySQLDate($PSorDate)."', '".ereg_replace("\'", "''", trim($PSorClientCode))."',  ".
							 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$txtItemCode."', Null, $txtSorDtQty, 0, $vSorDtPrice, $vSorDtPriceBase1, $vSorDtPriceBase2, $txtSorDtDiscount, $vSorDtDiscAmt, $vSorDtDiscAmtBase1, $vSorDtDiscAmtBase2, $item_vat, ".
							 "          $vSorDtPriceTTC, '".ereg_replace("'", "\'", trim($txtSorDtRemark))."',  $vSorDtTax1, $vSorDtTax2, $vSorDtTax3, $vSorDtTax4, $vSorDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $txtSorDtOQty, $txtSorDtCQty, if(ifNull($txtSorDtCQty,0) > 0, now(), Null), ".
							 "          if(ifNull($txtSorDtCQty,0) > 0, '".$_SESSION['useraccount']."', Null), $sorderdt_promo, '".$vSaDtItemAcc."', '".$_SESSION['useraccount']."', $sorderdt_quantitybox, $sorderdt_itemunit, '$sorderdt_itempackage', ".
							 " $sorderdt_clientdiscount,$sorderdt_itemdiscount, ".strformat($vSaDtDirectStkDbt).", ".strformat($vSaDtDirectStkCrd).",".strformat($vSaDtDirectStkCur).", ".strformat($vSaDtWasteDbt).", ".strformat($vSaDtWasteCrd).", ".strformat($vSaDtExportAcc).", ".strformat($vSaDtPromoAcc).", ".
							 " $PProdQty, $PSentProd) ";
 
					// $query."<br>";//exit;				
					$result=mysql_query($query,$connection);
								
					if ($result){
						fcommit();
						if($SubItem_Production == 1){
							$querydt = " insert into temp_itemsdt(Item_Code, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2, transid) ".
										" select Item_Code, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2, $txtSorDtId ".
										" from itemsdt ".
										" where item_code='$txtItemCode';";
							$resdt = mysql_query($querydt,$connection);			
						}
					}else{
						$txtSorDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error($connection); 
						
						frollback();
					}	
				} else {
					$txtSorDtId = "";
					$ErrorExists = 1;
					$message  = "Qty[".abs($txtSorDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")"; 
				}	
				

	
			}	// End Case Not Pack Item
			else {
			
				$promo_display = true;
				$promo_exhausted = 0;
				
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$txtItemCode."'  ";
									   
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
						
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtQty = $rowspackdt[2];
					$vPackDtCostPer = $rowspackdt[3];
					$vPackDtPromo = $rowspackdt[4];
					$vPackDtPromoQty = $rowspackdt[5];
					
					$query = " SELECT ifNull(Item_NonStock,0) ".
							 " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$ItemNonStock  = $result[0];
						
					
					// Check For Each Detail Promo Item If Promotion Exhausted For Date / Qty
					if($vPackDtPromo == 1 && $vPackDtPromoQty > 0){
						
						if (insertParadoxDate(substr($rowspackdt[6], 0, 10)) <= insertToday() && insertParadoxDate(substr($rowspackdt[7], 0, 10)) >= insertToday()){
							//$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$txtItemCode."' AND Transaction_Date >= '".$sub_result[1]."' AND Transaction_Date <= '".$sub_result[2]."'";
							$sub_query = " Select Sum(ifNull(SorderDt_Quantity,0)) ".
										 " From SorderDt ".
										 " Inner Join Sorder on SorderDt.Sorder_ID = Sorder.Sorder_ID ".
										 " Where SorderDt.Item_CodePacked = '".$txtItemCode."' ".
										 " And SorderDt.Item_Code = '".$vItemCode."' ".
										 " And ifNull(Sorder.Sorder_disapproved,0) = 0 ".
										 " And ifNull(SorderDt.Sorderdt_OldData,0) = 0 ".
										 " And Sorder.Sorder_Type = 'SO' ".
										 " And Sorder.Sorder_Date >= '".$rowspackdt[6]."' and Sorder.Sorder_Date <= '".$rowspackdt[7]."' ";

							//echo "<br><br>".$sub_query;exit;
							$sub_result = selectData($connection, $sub_query);

							if ($vPackDtPromoQty <= ($sub_result[0] + $txtSorDtOQty*$vPackDtQty)){
								$promo_exhausted = 1;
							}
						}else{
							$promo_exhausted = 1;
						}
						
					}
					
					//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
					if ($ItemNonStock == 0  && $Module_SorderCheckQtyOnPost == 1) {
						$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PSorDate)."', 0, 'SO', '', '') QtyExists From Dual ";
						$sub_result = selectData($connection, $sub_query);
						$vItemQtyExists = 0;
						$vItemQtyExists = $sub_result[0];
							
						$sub_query1 = " Select ifNull(Sum(ifNull(TransferDt_Quantity,0)),0) FROM Temp_TransferDt ".
									  " WHERE Item_code = '".$vItemCode."'  And  TransferDt_WarehouseFrom = '".$lstWarehouse."' ";
						$sub_result1 = selectData($connection, $sub_query1);
						if (empty($sub_result1[0])) $sub_result1[0] = 0;
						
						$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
						$vSorDtQty      = $vSorDtQty*$vPackDtQty;
							
								
						if (abs($vSorDtQty) > $vItemQtyExists && abs($vSorDtQty) > 0)
							$QtyExistExceeded = 1;
					}
					
					if ($promo_exhausted == 1) break;
				}

						
				
				//echo $promo_exhausted.$querypackdt; exit;			
				if ($promo_exhausted == 0 && ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1))){
					fbegin();
					
					$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
								   " FROM PackDt ".
								   " WHERE Item_Code = '".$txtItemCode."'  ";
									   
					$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
					while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
						
						$vItemCodePacked = $rowspackdt[0];
						$vItemCode = $rowspackdt[1];
						$vPackDtQty = $rowspackdt[2];
						$vPackDtCostPer = $rowspackdt[3];
						$vPackDtPromo = $rowspackdt[4];
						$vPackDtPromoQty = $rowspackdt[5];
						
											
						

						fbegin();
						$vSorDtId = get_nextsequence('sorderdt_id','',$connection);
						fcommit();

						$vSorDtOQty = $txtSorDtOQty*$vPackDtQty;
						$vSorDtCQty = $txtSorDtCQty*$vPackDtQty;
						$vSorDtQty  = $vSorDtOQty - $vSorDtCQty;
							
							
								
						$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock,0) ".
								 " FROM Items WHERE item_Code = '".$vItemCode."'";
						$result = selectData($connection, $query);
						$item_vat 	   = $result[0];
						$Item_MaxQty   = $result[1];
						$ItemGroupCode = $result[2];
						$ItemProd	   = $result[3];
						$ItemTTCInc    = $result[4];
						$ItemUnit  	   = $result[5];
						$ItemNonStock  = $result[7];
						
						$tax_flag = 0;
						$notax_flag = 1;
						if ($item_vat > 0){
							$tax_flag = 1;
							$notax_flag = 0;
						}

						$vItemUnitCoef = 0;
						$vItemUnit2Qty = 0;
						if ($Module_DoubleUnit == 1) {
							/*if ($ItemUnit > 0) {
								$vItemUnitCoef = 1/$ItemUnit;
								$vItemUnit2Qty = $vItemUnitCoef * $vSorDtOQty;
							}*/
							
							$vItemUnitCoef = $ItemUnit;
							
							if ($Module_Unit1Method == 1)
								$vItemUnit2Qty = $vSorDtQty*$vItemUnitCoef;
							else	
								$vItemUnit2Qty = $vSorDtQty/$vItemUnitCoef;
						}	
						
						
								
						
							$vSorDtPriceTTC      = 0;
							$vSorDtPriceTTCBase1 = 0;
							$vSorDtPriceTTCBase2 = 0;					
							$vSorDtPrice      	 = 0;
							$vSorDtPriceBase1 	 = 0;
							$vSorDtPriceBase2 	 = 0;
							$vSorDtDiscAmt       = 0;
							$vSorDtDiscAmtBase1  = 0;
							$vSorDtDiscAmtBase2  = 0;
									
							$vCltTax1 = 0;
							$vCltTax2 = 0;
							$vCltTax3 = 0;
							$vCltTax4 = 0;
							$vCltTax5 = 0;
							$vSorDtTax1 = 0;
							$vSorDtTax2 = 0;
							$vSorDtTax3 = 0;
							$vSorDtTax4 = 0;
							$vSorDtTax5 = 0;

									
							if ($SalesTTC == 1) {
								$vSorDtPriceTTC      = (($txtSorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vSorDtPriceTTCBase1 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt1;
								$vSorDtPriceTTCBase2 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt2;

								//Added 2011/10/27
								//if ($PSorVatChkbx == 1)	$vSorDtPrice = ($vSorDtPriceTTC / (1 + $item_vat/100));
								//else $vSorDtPrice = $vSorDtPriceTTC;												
										
								$vSorDtPrice      = ($vSorDtPriceTTC / (1 + $item_vat/100));
								$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
								$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
										
							} else	{
								$vSorDtPrice      = (($txtSorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
								$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
										
								$vSorDtPriceTTC      = 0;
								$vSorDtPriceTTCBase1 = 0;
								$vSorDtPriceTTCBase2 = 0;
										
							}
									
							// Calculation For Detail Discount Amount
							if($show_discountAmount == 1)
							$vSorDtDiscAmt = $txtSorDtDiscountAmt;
							else 
							$vSorDtDiscAmt       = ((($vSorDtPrice*$vSorDtQty) - ($vSorDtPrice*$vSorDtQty*$txtSorDtDiscount/100))*$PSorDiscount)/100;
							$vSorDtDiscAmtBase1  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt1;
							$vSorDtDiscAmtBase2  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt2;

							if ($Module_AdditionalTaxes == 1) {
									
								// Calculation of Item Tax Amounts
								$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
										 " FROM Clients ".
										 " WHERE Ledger_number = '".$PSorClientCode."'";
															 
								$result = selectData($connection, $query);
								$vCltTax1 = $result[0];
								$vCltTax2 = $result[1];
								$vCltTax3 = $result[2];
								$vCltTax4 = $result[3];
								$vCltTax5 = $result[4];
													
								$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
										 " FROM Items ".
										 " WHERE Item_Code = '".$vItemCode."'";
															 
								$result = selectData($connection, $query);

										
								if ($vCltTax1 != 0)	$vSorDtTax1 = $result[0];
								if ($vCltTax2 != 0)	$vSorDtTax2 = $result[1];
								if ($vCltTax3 != 0)	$vSorDtTax3 = $result[2];
								if ($vCltTax4 != 0)	$vSorDtTax4 = $result[3];
								if ($vCltTax5 != 0)	$vSorDtTax5 = $result[4];
											
							}
					
							// 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, ".
									  " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
									 " FROM transactionsetup ".
									 " WHERE Journal_type = 'SO' ".
									 " 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]; 
							$vSaDtWasteDbt 			= $result[12]; 
							$vSaDtWasteCrd 			= $result[13]; 
							$vSaDtExportAcc 		= $result[14]; 
							
							if ($Module_RawMaterial == 1 || $SubItem_Production == 1) {
								$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
								$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
								$vSaDtDirectStkCur = $vTranStpDirectStkCur;
								$vSaDtVatAcc       = $vTranStpVatAcc;
								$vSaDtDiscAcc      = $vTranStpDiscAcc;
								$vSaDtPromoAcc     = $vTranStpPromoAcc;
											
								if ($item_vat > 0 && $PSorVatChkbx == 1) {
									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 && $PSorVatChkbx == 1)
									$vSaDtItemAcc = $vSaStpCreditVatAcc;
								else
									$vSaDtItemAcc = $vSaStpCreditAcc;	
							}	

							$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtDirectStkDbt."') from dual ";
							$sub_resultVat = selectData($connection, $sub_queryVat);
							if ($sub_resultVat[0] != '') $vSaDtDirectStkDbt = $sub_resultVat[0];
							
							$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtDirectStkCrd."') from dual ";
							$sub_resultVat = selectData($connection, $sub_queryVat);
							if ($sub_resultVat[0] != '') $vSaDtDirectStkCrd = $sub_resultVat[0];
							
							$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtWasteDbt."') from dual ";
							$sub_resultVat = selectData($connection, $sub_queryVat);
							if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
							
							$sub_queryVat = " SELECT GetAllVATAccount('".$PSorClientCode."','".$vSaDtWasteCrd."') from dual ";
							$sub_resultVat = selectData($connection, $sub_queryVat);
							if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
					
							$query = " INSERT INTO temp_sorderdt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
									 " Item_QtyPacked, SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
									 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, Sorderdt_promotion, Sorderdt_ItemAccount,".
									 " Logged_Code,  Sorderdt_DirectStkDbt,Sorderdt_DirectStkCrd, Sorderdt_DirectStkCur, Sorderdt_DirectWasteDbt, Sorderdt_DirectWasteCrd, Sorderdt_exportAccount, Sorderdt_PromoAcc, sorderdt_ProdQty, sorderdt_sentProduction ) ".
									 " VALUES ( ".$vSorDtId.", ".$PSorId.", '".$PSorCurr."', '".insertMySQLDate($PSorDate)."', '".ereg_replace("\'", "''", trim($PSorClientCode))."',  ".
									 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$vItemCode."', '".$vItemCodePacked."', $vSorDtQty, 0, $txtSorDtOQty, $vSorDtPrice, $vSorDtPriceBase1, $vSorDtPriceBase2, $txtSorDtDiscount, $vSorDtDiscAmt, $vSorDtDiscAmtBase1, $vSorDtDiscAmtBase2, $item_vat, ".
									 "          $vSorDtPriceTTC, '".ereg_replace("'", "\'", trim($txtSorDtRemark))."',  $vSorDtTax1, $vSorDtTax2, $vSorDtTax3, $vSorDtTax4, $vSorDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $vSorDtOQty, $vSorDtCQty, if(ifNull($vSorDtCQty,0) > 0, now(), Null), ".
									 "          if(ifNull($vSorDtCQty,0) > 0, '".$_SESSION['useraccount']."', Null), $vPackDtPromo, '".$vSaDtItemAcc."', '".$_SESSION['useraccount']."' , ".
									 " ".strformat($vSaDtDirectStkDbt).", ".strformat($vSaDtDirectStkCrd).",".strformat($vSaDtDirectStkCur).", ".strformat($vSaDtWasteDbt).", ".strformat($vSaDtWasteCrd).", ".strformat($vSaDtExportAcc).", ".strformat($vSaDtPromoAcc).", ".
									 " $PProdQty, $PSentProd ) ";

							$result=mysql_query($query,$connection);
											
							//echo $query;
						
						
					} // End Loop Of Packdt
					
				
					if ($result){
						fcommit();
						if($SubItem_Production == 1){
							$querydt = " insert into temp_itemsdt(Item_Code, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2, transid) ".
										" select Item_Code, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2, $vSorDtId ".
										" from itemsdt ".
										" where item_code='$vItemCode';";
							$resdt = mysql_query($querydt,$connection);			
						}
					}else{
						$txtSorDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error($connection); 
						frollback();
					}	
					
						
				} else{
					$txtSorDtId = "";
					$ErrorExists = 1;
					
					if ($promo_exhausted == 1)
						$message = $message . "<br>Item ".$lstItem." COULD NOT be Added. Promo Qty / Period Exhausted";
					else if ($QtyExistExceeded == 1)
						$message  = "Qty[".abs($vSorDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
						
					frollback();
				}
				
			} // End CasePack Item
			
			if ($ErrorExists == 0) {
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SSorId, $PSorDate, $PSorVatChkbx, $PSorDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
				$message  = $message . $CalculateResult;
			}
		
		}
		
	} // End Case Insert In Detail Tables
	

} 
//Edit Detail Tables
else if ($mode == "editdt" || $mode == "editdt-ajax"){

	$ErrorExists == 0;
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	
	if($FI_SalebelowCost == 0){ // jp
		$sub_queryX = " select ifNull(Item_Promotion, 0)  from items where item_code = '".$txtItemCode."'"; 
		$sub_resultX = selectData($connection, $sub_queryX);
		$itemisPromo = $sub_resultX[0];
		if($itemisPromo == 0){
			$sub_query = " select meancostcur('".$txtItemCode."', now() ,1, '$base1','$base1'); "; 
			$sub_result = selectData($connection, $sub_query);
			if($sub_result[0] > $txtSorDtPrice ){
				$ErrorExists = 1;
				$message = 'Insert not allowed. Price Below Cost.';
			}
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	if($costcentminimum == 1 && $txtCostCentCodeDt != ''){
			$query = "select ifnull(min(min_price),0) from costcenterPrice where costcenter_code = $txtCostCentCodeDt and item_code = '$txtItemCode' ;";
			$res = mysql_query($query,$connection);
			$rw = mysql_fetch_row($res);
			$min_price = $rw[0];
			if($min_price == '') $min_price = 0;
			if($min_price != 0 && $min_price > $txtSorDtPrice){
				$ErrorExists=1;
				$message = "Price should be greater than or equal to $min_price";
			}		
		}
	if ($SSorId != "" && $SSorDtId != "" && $ErrorExists == 0) {
		
		
		if (empty($txtSorDtPrice))
			$txtSorDtPrice = 0;
		if (empty($txtSorDtDiscount))
		    $txtSorDtDiscount = 0;
		if (empty($txtSorDtDiscountAmt))
		    $txtSorDtDiscountAmt = 0;					
		if (empty($txtSorDtOQty))
		    $txtSorDtOQty = 0;
		if (empty($txtSorDtCQty))
		   $txtSorDtCQty = 0;      
		if (empty($txtSorDtQty))
		   $txtSorDtQty = 0;   
		if (empty($txtSorDtQty2))
		   $txtSorDtQty2 = 0;  

	   if (empty($sorderdt_quantitybox))
		   $sorderdt_quantitybox = 0;   

	   if (empty($sorderdt_itemunit))
		   $sorderdt_itemunit = 0;  

	   if (empty($sorderdt_itempackage))
		   $sorderdt_itempackage = 0;       
		
		if (empty($sorderdt_promo))
		   $sorderdt_promo = 0;  
	   
		$txtProjectCodeDt = "".$txtProjectCodeDt;
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt =='')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}		   
		
				
		$query = "SELECT Item_Vat, ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) FROM Items WHERE item_Code = '".$txtItemCode."'";
		$result = selectData($connection, $query);
		$item_vat     = $result[0];
		$ItemPromo    = $result[1];
		$ItemNonStock = $result[2];
		//$item_vat = $item_vat/100;
		$tax_flag = 0;
		$notax_flag = 1;
		if ($item_vat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
		
		//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
		if ($ItemNonStock == 0 && $Module_SorderCheckQtyOnPost == 1) {
			$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PSorDate)."', 0, 'SO', '', '') QtyExists From Dual ";
			$sub_result = selectData($connection, $sub_query);
			$vItemQtyExists = 0;
			$vItemQtyExists = $sub_result[0];
					
			$sub_query1 = " Select ifNull(Sum(ifNull(TransferDt_Quantity,0)),0) FROM Temp_TransferDt ".
						  " WHERE Item_code = '".$txtItemCode."'  And  TransferDt_WarehouseFrom = '".$lstWarehouse."' ";
			$sub_result1 = selectData($connection, $sub_query1);
			if (empty($sub_result1[0])) $sub_result1[0] = 0;
					
			$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
					
						
			if (abs($txtSorDtQty) > $vItemQtyExists && abs($txtSorDtQty) > 0 && ($PSorType == 'SO' || $PSorType==''))
				$QtyExistExceeded = 1;
		}
		
		if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
			
			$vSorTaxable = 0;
			$vSorNoneTaxable = 0;
			$vSorDtTotalOld = 0;
			$vSorDtTotalTTCOld = 0;
			$vSorGrossTotal = 0;
			$vSorDiscount = 0;
			$vSorDiscountAmt = 0;
			$vSorVat = 0;
			$vSorVatBase1 = 0;
			$vSorVatBase2 = 0;
			$WarningMsg = '';
			$vSorDtTotal = 0;
			$vSorCltCode = '';
			$vItemVat    = 0;
			$vSorQty     = 0;
			
			if ($PSentProd == '') $PSentProd = 0;
			if ($PProdQty == '') $PProdQty = 0;
		
			$vSorDtDiscAmt       = 0;
			$vSorDtDiscAmtBase1  = 0;
			$vSorDtDiscAmtBase2  = 0;
			
			$querycur = "update Temp_Sorder set Currency_code ='$PSorCurr' Where Sorder_ID = ".$SSorId;	
			$result=mysql_query($querycur,$connection) or die(mysql_error());
			$querycur = "update Temp_Sorderdt set Currency_code ='$PSorCurr' Where Sorder_ID = ".$SSorId;	
			$result=mysql_query($querycur,$connection) or die(mysql_error());
			
			$query = " Select Currency_code, ifNull(Sorder_Taxable,0), ifNull(Sorder_NoneTaxable,0), ifNull(Sorder_DiscountPer,0), Client_code ".
					 " From Temp_Sorder As Sorder ".
					 " Where Sorder_ID = ".$SSorId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";			 
					 
			
			$result=mysql_query($query,$connection) or die(mysql_error());
			$rows=mysql_fetch_array($result);
			
			$vSorCurr        = $rows[0];
			//$vSorTaxable     = $rows[1];
			//$vSorNoneTaxable = $rows[2];
			$vSorDiscount    = $rows[3];
			$vSorCltCode     = $rows[4];
			
			
			$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vSorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vSorCurr."' )";
			$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];
			
			
			$txtSorDtQty = $txtSorDtOQty - $txtSorDtCQty;			
			//if item promotion the set price to zero
				// if($ItemPromo == 1 || $sorderdt_promo == 1) $txtSorDtPrice = 0;
			
			if ($SalesTTC == 1) {
				$vSorDtPriceTTC      = $txtSorDtPrice;
				$vSorDtPriceTTCBase1 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt1;
				$vSorDtPriceTTCBase2 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt2;					
				
				//Added 2011/09/24
				if ($PSorVatChkbx == 1)	$vSorDtPrice = ($vSorDtPriceTTC / (1 + $item_vat/100));
				else $vSorDtPrice = $txtSorDtPrice;
				
				//$vSorDtPrice      = ($vSorDtPriceTTC / (1 + $item_vat/100));
				$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
				$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
							
			} else	{
				$vSorDtPrice      = $txtSorDtPrice;
				$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
				$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
					
				$vSorDtPriceTTC      = 0;
				$vSorDtPriceTTCBase1 = 0;
				$vSorDtPriceTTCBase2 = 0;
							
			}	
					
			
					
			// Calculation For Detail Discount Amount
			if($show_discountAmount == 1) 
				$vSorDtDiscAmt = $txtSorDtDiscountAmt;
			else
			$vSorDtDiscAmt       = ((($vSorDtPrice*$txtSorDtQty) - ($vSorDtPrice*$txtSorDtQty*$txtSorDtDiscount/100))*$vSorDiscount)/100;
			$vSorDtDiscAmtBase1  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt1;
			$vSorDtDiscAmtBase2  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt2;
			
			
			//Edit Item Code/Warehouse Check If Item Is Delivered
			$sub_query = " Select Count(*) From DeliveryDt ".
						 " Where DeliveryDt.RelatedDt_Id = '".$SSorDtId."' ".
						 " And DeliveryDt.Journal_Type = 'DI' ";
			$sub_result = selectData($connection, $sub_query);
			$DeliveryExists = 0;
			$DeliveryExists = $sub_result[0];

			if($sorderdt_clientdiscount=='') $sorderdt_clientdiscount=0;
			if($sorderdt_itemdiscount=='')  $sorderdt_itemdiscount=0;
					
			fbegin();
			$query = " UPDATE temp_sorderdt SET  ".
					 "	sorderdt_clientdiscount=$sorderdt_clientdiscount,sorderdt_itemdiscount=$sorderdt_itemdiscount,".
					 " SorderDt_Quantity = $txtSorDtQty, Item_Unit2Qty = $txtSorDtQty2, SorderDt_Price = $vSorDtPrice, SorderDt_PriceBase1 = $vSorDtPriceBase1, ".
					 " SroderDt_PriceBase2 = $vSorDtPriceBase2, SorderDt_Discount = $txtSorDtDiscount, SorderDt_PriceTTC = $vSorDtPriceTTC, Item_VAT = $item_vat, ".
					 " SorderDt_Remark = '".ereg_replace("'", "\'", trim($txtSorDtRemark))."', SorderDt_oqty = $txtSorDtOQty, SorderDt_cqty = $txtSorDtCQty, ".
					 " SorderDt_cqtydate = if(ifNull($txtSorDtCQty,0) > 0, now(), Null), SorderDt_cqtyuser = if(ifNull($txtSorDtCQty,0) > 0, '".$_SESSION['useraccount']."', Null), ".
					 " SorderDt_DiscountAmount = $vSorDtDiscAmt, SorderDt_DiscountBase1 = $vSorDtDiscAmtBase1, SorderDt_DiscountBase2 = $vSorDtDiscAmtBase2, sorderdt_promotion = $sorderdt_promo,  ".
					 " sorderdt_ProdQty = '$PProdQty', sorderdt_sentProduction = '$PSentProd' ";
					 
					 
			if ($Module_ProjectDt == 1)
				$query = $query.", Project_Code = $ProjectCodeDt ";
			if ($Module_CostCenterDt == 1)	
				$query = $query.", CostCent_Code = $CostCentCodeDt ";
				
			//Edit Item Code/Warehouse If Item Is Not Delivered
			if ($DeliveryExists == 0)
				$query = $query.", Warehouse_Code = '".$lstWarehouse."', Item_Code = '".str_replace('\\','\\\\',$txtItemCode)."' ";
			$query = $query.", sorderdt_quantitybox ='$sorderdt_quantitybox', sorderdt_itemunit = '$sorderdt_itemunit', sorderdt_itempackage = '$sorderdt_itempackage' ";
			$query = $query." Where SorderDt_ID = ".$SSorDtId;		 
						 
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
				
			if ($result){
				fcommit();
				if($SubItem_Production == 1){
					$queryfile = "select item_code from temp_itemsdt 
								where transid=$SSorDtId";
					$resfile = mysql_query($queryfile,$connection);
					$rwfile = mysql_fetch_row($resfile);
					$item_codeold = $rwfile[0];
					if($item_codeold != $txtItemCode ){
						$querydel = "delete from temp_itemsdt where transid=$SSorDtId;";
						$resdel = mysql_query($querydel,$connection);
						$querydt = " insert into temp_itemsdt(Item_Code, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2, transid) ".
									" select Item_Code, ItemParam_Code, itemdt_value, itemdt_sign, itemdt_value2, $SSorDtId ".
									" from itemsdt ".
									" where item_code='$txtItemCode';";
						$resdt = mysql_query($querydt,$connection);	
					}					
				}
				
				
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SSorId, $PSorDate, $PSorVatChkbx, $vSorDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $SalesTTC, 'U', $connection);
				$message  = $message . $CalculateResult;
				
				
			}else{
				$message  = mysql_error(); 
				frollback();
			}  					 
		} else {
			$ErrorExists = 1;
			$message  = "Qty[".abs($txtSorDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")"; 
		}
	}
}
	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	if ($AllowDelete == 0) {
		//Check Each SorderDt If Has RelatedId In DeliveryDt
		$query = " Select Count(SorderDt.SorderDt_id) ".
				 " From SorderDt ".
				 " Inner Join DeliveryDt on SorderDt.SorderDt_id = DeliveryDt.RelatedDt_id ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " Where SorderDt.Sorder_id = ".$SSorId;

		$result = selectData($connection, $query);
		$SorDeliveryExists = $result[0];
		
		if ($SorDeliveryExists > 0 ){
			$message  = 'Delete not allowed, preparation order delivered.';
			$AllowDelete = 1;
		}
	
	}
	
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {

		
		if (!isset($txtCurr))
		   $txtCurr = $base1;

		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
		$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];
		
		
		
			
		/*$sub_query = " Select ifNull(Sorder_VatChckbx,0) As Sorder_VatChckbx ".
					 " From Temp_Sorder As Sorder ".
				     " Where Sorder_ID = ".$SSorId;
		$sub_result = selectData($connection, $sub_query);
		$vChkSorVat = $sub_result[0];*/
		
				
		$querypack = " SELECT SorderDt.Item_CodePacked, SorderDt.Item_code ".
					 " FROM Temp_SorderDt As SorderDt ".
					 " Where SorderDt.SorderDt_ID = ".$SSorDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
		
		$resultpack=mysql_query($querypack, $connection) or die(mysql_error());
		$rowspack=mysql_fetch_array($resultpack);
		$vItemCodePacked = $rowspack[0];
		
		fbegin();
		
		// Item Not Packed
		if ($vItemCodePacked == '') {
		
			// Delete From TempSorderDt For Selected Record
			$query = " DELETE FROM Temp_SorderDt ".
					 " WHERE SorderDt_id = ".$SSorDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
			if (!updateData($connection, $query, true)) {
			  $message  = mysql_error();
			  $ErrorExists = 1;
			  frollback();
			}  
			else {
				fcommit();
				
				if($SubItem_Production==1){
					$querydel = "delete from temp_itemsdt where transid=$SSorDtId";
					$resdel = mysql_query($querydel,$connection);
					$querypic = "select item_picture,item_code, item_picture2 from temp_items where trans_id=$SSorDtId";
					$respic  = mysql_query($querypic,$connection);
					$rwpic = mysql_fetch_row($respic);
					$item_picture = $rwpic[0];
					$item_code = $rwpic[1];
					$item_picture2 = $rwpic[1];
					
					$querydel = "delete from temp_items where trans_id=$SSorDtId";
					$resdel = mysql_query($querydel,$connection);
				}
			
			}			
			
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querydt = " Select SorderDt_ID, SorderDt.Item_CodePacked, SorderDt.Item_code  ".
					   " From Temp_SorderDt As SorderDt  ".
					   " Where SorderDt.Sorder_ID = ".$SSorId.
					   " And SorderDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
					   //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						   
			$resultdt=mysql_query($querydt, $connection) or die(mysql_error());
			while($rowsdt=mysql_fetch_array($resultdt)){		   
					
				$vSorDtId =	$rowsdt[0];
						
				// Delete From TempSorderDt For Selected Record
				$query = " DELETE FROM Temp_SorderDt ".
						 " WHERE SorderDt_id = ".$vSorDtId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				} 
				
				if($ErrorExists == 0) {
					if($SubItem_Production==1){
						$querydel = "delete from temp_itemsdt where transid=$vSorDtId";
						$resdel = mysql_query($querydel,$connection);
						$querypic = "select item_picture,item_code, item_picture2 from temp_items where trans_id=$vSorDtId";
						$respic  = mysql_query($querypic,$connection);
						$rwpic = mysql_fetch_row($respic);
						$item_picture = $rwpic[0];
						$item_code = $rwpic[1];
						$item_picture2 = $rwpic[2];
						
						$querydel = "delete from temp_items where trans_id=$vSorDtId";
						$resdel = mysql_query($querydel,$connection);
					}
				}	
			}
			
		
			if ( $ErrorExists == 0 )
				fcommit();
			
		
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 ){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SSorId, $txtDate, $SSorVatChkbx, $txtSorDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $SalesTTC, 'D', $connection);
			$message  = $message . $CalculateResult;
			
		} 
	
	} // End If No Constraints Found On Delete
	
	$txtSorId = $SSorId;
}

//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SSorId != ''){

	$AllowDelete = 0;
	$message  = '';
	
	//Check If SalesOrder Is Posted
	$query = "SELECT ifNull(Sorder_Posted,0) As SorderPosted FROM Sorder WHERE Sorder_id = ".$SSorId;
	$result = selectData($connection, $query);
	$SorPosted = $result[0];
	
	if ($SorPosted == 1 ){
		$message  = 'Delete not allowed, preparation order posted.';
		$AllowDelete = 1;
	}
	
	if ($AllowDelete == 0) {
		//Check Each SorderDt If Has RelatedId In DeliveryDt
		$query = " Select Count(SorderDt.SorderDt_id) ".
				 " From SorderDt ".
				 " Inner Join DeliveryDt on SorderDt.SorderDt_id = DeliveryDt.RelatedDt_id ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " Where SorderDt.Sorder_id = ".$SSorId;

		$result = selectData($connection, $query);
		$SorDeliveryExists = $result[0];
		
		if ($SorDeliveryExists > 0 ){
			$message  = 'Delete not allowed, preparation order delivered.';
			$AllowDelete = 1;
		}
	
	}
	
		
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
		if($SubItem_Production==1){
			$query = "select sorderdt_id from Temp_SorderDt where Sorder_id = ".$SSorId;
			$res = mysql_query($query,$connection);
			while($rw = mysql_fetch_row($res)){
				$SSorDtId =$rw[0];
				$querydel = "delete from temp_itemsdt where transid=$SSorDtId";
				$resdel = mysql_query($querydel,$connection);
				$querypic = "select item_picture,item_code, item_picture2 from temp_items where trans_id=$SSorDtId";
				$respic  = mysql_query($querypic,$connection);
				$rwpic = mysql_fetch_row($respic);
				$item_picture = $rwpic[0];
				$item_code = $rwpic[1];
				$item_picture2 = $rwpic[2];
				
				$querydel = "delete from temp_items where trans_id=$SSorDtId";
				$resdel = mysql_query($querydel,$connection);
			}
		}
		$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
					if($config['log_file'] == 1){
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SSorId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'sales_order', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		// Delete From SorderDt For Selected Record
		$query = " DELETE FROM SorderDt ".
				 " WHERE Sorder_id = ".$SSorId;
					 
		if (updateData($connection, $query, true)) {
			// Delete From Sorder For Selected Record
			$query = " DELETE FROM Sorder ".
					 " WHERE Sorder_id = ".$SSorId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

//Delete Record Mode From Temp Tables
else if (($mode == "cancel" || $mainmode == "deletepending") && $SSorId != ''){
	$query = "select sorder_type from Temp_Sorder where Sorder_id = ".$SSorId;
	$res = mysql_query($query,$connection);
	$rw = mysql_fetch_row($query,$res);
	$sorder_type = $rw[0];
	if($SubItem_Production==1 && $sorder_type == 'SO'){
		$query = "select sorderdt_id from Temp_SorderDt where Sorder_id = ".$SSorId;
		$res = mysql_query($query,$connection);
		while($rw = mysql_fetch_row($res)){
			$SSorDtId =$rw[0];
			$querydel = "delete from temp_itemsdt where transid=$SSorDtId";
			$resdel = mysql_query($querydel,$connection);
			$querypic = "select item_picture,item_code, item_picture2 from temp_items where trans_id=$SSorDtId";
			$respic  = mysql_query($querypic,$connection);
			$rwpic = mysql_fetch_row($respic);
			$item_picture = $rwpic[0];
			$item_code = $rwpic[1];
			$item_picture2 = $rwpic[2];
			
			$querydel = "delete from temp_items where trans_id=$SSorDtId";
			$resdel = mysql_query($querydel,$connection);
		}
	}		 
	// Delete From TempSorderDt For Selected Record
	$query = " DELETE FROM Temp_SorderDt ".
			 " WHERE Sorder_id = ".$SSorId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
	if (updateData($connection, $query, true)) {
		// Delete From TempSorder For Selected Record
		$query = " DELETE FROM Temp_Sorder ".
				 " WHERE Sorder_id = ".$SSorId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if($mainmode == "search" && $SSorId != ''){

	$AllowEdit = 1;
	$message  = '';
	
	if ($AllowEdit == 1 && $FI_AllowEditIfDelivered == 0) {
		//Check Each SorderDt If Has RelatedId In DeliveryDt
		$query = " Select Count(SorderDt.SorderDt_id) ".
				 " From SorderDt ".
				 " Inner Join DeliveryDt on SorderDt.SorderDt_id = DeliveryDt.RelatedDt_id ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " Where SorderDt.Sorder_id = ".$SSorId;

		$result = selectData($connection, $query);
		$DeliveryExists = $result[0];
		
		if ($DeliveryExists > 0 ){
			$message  = 'Edit not allowed, preparation order delivered.';
			$AllowEdit = 0;
		}
	
	}

	if ($AllowEdit == 1) {
		
		
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_sorder (Sorder_id, Sorder_Reference, Sorder_Date, Sorder_RequestDate, Sorder_MaturityDate, Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryPlace, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Sorder_Posted, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, ".
				 " Sorder_DiscountBase2, Sorder_DiscountPer, Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_confirmed, Sorder_disapproved, Sorder_type, Sorder_TotalQuantity, Sorder_TotalQuantityUsed, ".
				 " Sorder_Paymentmode, Journal_Type, Journal_Id, Sorder_tax1, Sorder_tax1base1, Sorder_tax1base2, Sorder_tax2, Sorder_tax2base1, Sorder_tax2base2, Sorder_tax3, Sorder_tax3base1, Sorder_tax3base2, Sorder_tax4, ".
				 " Sorder_tax4base1, Sorder_tax4base2, Sorder_tax5, Sorder_tax5base1, Sorder_tax5base2, Sorder_VatChckbx, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, Sorder_Status, User_Account, Sorder_ConfirmUser, Sorder_DriverName, ".
				 " Sorder_VehicalNo, Sorder_VehicleWeight, Sorder_TransportAccount, Sorder_TransportAmount, Sorder_TransportBase1, Sorder_TransportBase2, Sorder_TransportTTC, Logged_Code,Sorder_Export, Sorder_ClientSorderDate, Sorder_ClientPhone, ".
				 " Sorder_ShippingWay, Sorder_ShipName, assignto_user) ".
				 " SELECT Sorder_id, Sorder_Reference, Sorder_Date, Sorder_RequestDate, Sorder_MaturityDate, Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryPlace, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Sorder_Posted, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, ".
				 " Sorder_DiscountBase2, Sorder_DiscountPer, Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_confirmed, Sorder_disapproved, Sorder_type, Sorder_TotalQuantity, Sorder_TotalQuantityUsed, ".
				 " Sorder_Paymentmode, Journal_Type, Journal_Id, Sorder_tax1, Sorder_tax1base1, Sorder_tax1base2, Sorder_tax2, Sorder_tax2base1, Sorder_tax2base2, Sorder_tax3, Sorder_tax3base1, Sorder_tax3base2, Sorder_tax4, ".
				 " Sorder_tax4base1, Sorder_tax4base2, Sorder_tax5, Sorder_tax5base1, Sorder_tax5base2, Sorder_VatChckbx, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, Sorder_Status, User_Account, Sorder_ConfirmUser, Sorder_DriverName, ".
				 " Sorder_VehicalNo, Sorder_VehicleWeight, Sorder_TransportAccount, Sorder_TransportAmount, Sorder_TransportBase1, Sorder_TransportBase2, Sorder_TransportTTC, '".$_SESSION['useraccount']."',Sorder_Export, Sorder_ClientSorderDate, ".
				 " Sorder_ClientPhone, Sorder_ShippingWay, Sorder_ShipName, assignto_user ".
				 " FROM Sorder ".
				 " WHERE Sorder_id = ".$SSorId;
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 	
		//echo $message.$query; exit;				 
		$query = " INSERT INTO temp_sorderdt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
				 " SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
				 " SorderDt_DirectStkDbt, SorderDt_DirectStkCrd, SorderDt_DirectStkCur, SorderDt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, ".
				 " SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, Sorderdt_promotion, Item_QtyPacked, SorderDt_TransportAmount, SorderDt_TransportBase1, SorderDt_TransportBase2, Logged_Code, sorderdt_quantitybox, sorderdt_itemunit,".
				 " sorderdt_itempackage,sorderdt_clientdiscount,sorderdt_itemdiscount,relateddt_id, sorderdt_desc1, Sorderdt_DirectWasteDbt, Sorderdt_DirectWasteCrd, Sorderdt_exportAccount, Sorderdt_PromoAcc, sorderdt_ProdQty, sorderdt_sentProduction ) ".
				 " SELECT SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
				 " SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
				 " SorderDt_DirectStkDbt, SorderDt_DirectStkCrd, SorderDt_DirectStkCur, SorderDt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, ".
				 " SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, Sorderdt_promotion, Item_QtyPacked, SorderDt_TransportAmount, SorderDt_TransportBase1, SorderDt_TransportBase2, '".$_SESSION['useraccount']."', sorderdt_quantitybox, sorderdt_itemunit, ".
				 " sorderdt_itempackage,sorderdt_clientdiscount,sorderdt_itemdiscount,relateddt_id, sorderdt_desc1,  Sorderdt_DirectWasteDbt, Sorderdt_DirectWasteCrd, Sorderdt_exportAccount, Sorderdt_PromoAcc, sorderdt_ProdQty, sorderdt_sentProduction  ".
				 " FROM Sorderdt ".
				 " WHERE Sorder_id = ".$SSorId;
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 			
		if($message == '') {
			if($SubItem_Production == 1 ){
				$querytype = "select Sorder_type from sorder where sorder_id = $SSorId;";
				$restype = mysql_query($querytype, $connection);
				$rwtype = mysql_fetch_row($restype);
				$Sorder_type = $rwtype[0];
				
				if($Sorder_type != 'PF'){
					$querydel1 = "delete from temp_items where trans_id in (select sorderdt_id from sorderdt where Sorder_id = $SSorId );";
					$resdel1 = mysql_query($querydel1,$connection);
					$querydel2 = "delete from temp_itemsdt where transid in (select sorderdt_id from sorderdt where Sorder_id = $SSorId );";
					$resdel2 = mysql_query($querydel2,$connection);
					
					$queryitemsdt = " insert into temp_itemsdt (Item_Code,ItemParam_Code,itemdt_value, transid)".
									" select itemsdt.item_code, ItemParam_Code, itemdt_value, sorderdt_id ".
									" from itemsdt ".
									" left join sorderdt on sorderdt.item_code = itemsdt.item_code ".
									" where sorder_id = $SSorId";
					$resitemsdt = mysql_query($queryitemsdt,$connection);
					
					$queryitempic = " insert into temp_items (Item_Code,item_picture, item_picture2, trans_id)".
									" select items.item_code, item_picture, item_picture2, sorderdt_id ".
									" from items ".
									" left join sorderdt on sorderdt.item_code = items.item_code ".
									" where sorder_id = $SSorId";//echo $queryitempic;exit;
					$resitemspic = mysql_query($queryitempic,$connection);
				}
			}
		}
	}
	

}


else if($mode == "" && $mainmode == "duplicateSorder" && $SSorId != ''){
	fbegin();	
	$PSorId = get_nextsequence('sorder_id','',$connection);	
	fcommit();
	//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_sorder (Sorder_id, Sorder_Reference, Sorder_Date, Sorder_RequestDate, Sorder_MaturityDate, Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryPlace, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Sorder_Posted, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, ".
				 " Sorder_DiscountBase2, Sorder_DiscountPer, Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_confirmed, Sorder_disapproved, Sorder_type, Sorder_TotalQuantity, Sorder_TotalQuantityUsed, ".
				 " Sorder_Paymentmode, Journal_Type, Journal_Id, Sorder_tax1, Sorder_tax1base1, Sorder_tax1base2, Sorder_tax2, Sorder_tax2base1, Sorder_tax2base2, Sorder_tax3, Sorder_tax3base1, Sorder_tax3base2, Sorder_tax4, ".
				 " Sorder_tax4base1, Sorder_tax4base2, Sorder_tax5, Sorder_tax5base1, Sorder_tax5base2, Sorder_VatChckbx, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, Sorder_Status, User_Account, Sorder_ConfirmUser, Sorder_DriverName, ".
				 " Sorder_VehicalNo, Sorder_VehicleWeight, Sorder_TransportAccount, Sorder_TransportAmount, Sorder_TransportBase1, Sorder_TransportBase2, Sorder_TransportTTC, Logged_Code,Sorder_Export, Sorder_ClientSorderDate, Sorder_ClientPhone, Sorder_ShippingWay, Sorder_ShipName) ".
				 " SELECT $PSorId, NULL, Sorder_Date, Sorder_RequestDate, Sorder_MaturityDate, Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryPlace, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Sorder_Posted, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, ".
				 " Sorder_DiscountBase2, Sorder_DiscountPer, Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_confirmed, Sorder_disapproved, 'PF', Sorder_TotalQuantity, Sorder_TotalQuantityUsed, ".
				 " Sorder_Paymentmode, Journal_Type, Journal_Id, Sorder_tax1, Sorder_tax1base1, Sorder_tax1base2, Sorder_tax2, Sorder_tax2base1, Sorder_tax2base2, Sorder_tax3, Sorder_tax3base1, Sorder_tax3base2, Sorder_tax4, ".
				 " Sorder_tax4base1, Sorder_tax4base2, Sorder_tax5, Sorder_tax5base1, Sorder_tax5base2, Sorder_VatChckbx, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, Sorder_Status, User_Account, Sorder_ConfirmUser, Sorder_DriverName, ".
				 " Sorder_VehicalNo, Sorder_VehicleWeight, Sorder_TransportAccount, Sorder_TransportAmount, Sorder_TransportBase1, Sorder_TransportBase2, Sorder_TransportTTC, '".$_SESSION['useraccount']."',Sorder_Export, Sorder_ClientSorderDate, Sorder_ClientPhone, Sorder_ShippingWay, Sorder_ShipName ".
				 " FROM Sorder ".
				 " WHERE Sorder_id = ".$SSorId;
		
		if (!updateData($connection, $query, true))
		  $message  = mysql_error(); 	
	
		$querysel = "select sorderdt_id,item_code from sorderdt where Sorder_id = ".$SSorId; 
		$ressel = mysql_query($querysel,$connection);
		while($rw = mysql_fetch_row($ressel)){
			$item_code = $rw[1];
			fbegin();
			$txtSorDtId = get_nextsequence('sorderdt_id','',$connection);	
			fcommit();
			$query = " INSERT INTO temp_sorderdt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
						 " SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
						 " SorderDt_DirectStkDbt, SorderDt_DirectStkCrd, SorderDt_DirectStkCur, SorderDt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, ".
						 " SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, Sorderdt_promotion, Item_QtyPacked, SorderDt_TransportAmount, SorderDt_TransportBase1, SorderDt_TransportBase2, Logged_Code, sorderdt_quantitybox, sorderdt_itemunit,".
						 " sorderdt_itempackage,sorderdt_clientdiscount,sorderdt_itemdiscount,relateddt_id, sorderdt_desc1 ) ".
						 " SELECT $txtSorDtId, $PSorId, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
						 " SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
						 " SorderDt_DirectStkDbt, SorderDt_DirectStkCrd, SorderDt_DirectStkCur, SorderDt_ItemAccount, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, ".
						 " SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, Sorderdt_promotion, Item_QtyPacked, SorderDt_TransportAmount, SorderDt_TransportBase1, SorderDt_TransportBase2, '".$_SESSION['useraccount']."', sorderdt_quantitybox, sorderdt_itemunit, ".
						 " sorderdt_itempackage,sorderdt_clientdiscount,sorderdt_itemdiscount,relateddt_id, sorderdt_desc1  ".
						 " FROM Sorderdt ".
						 " WHERE Sorderdt_id = ".$rw[0];//echo $query;exit;
				
			if (!updateData($connection, $query, true))
				$message  = mysql_error();
			if($message == '') {
			
				$queryitemsdt = " insert into temp_itemsdt (Item_Code,ItemParam_Code,itemdt_value, transid)".
								" select itemsdt.item_code, ItemParam_Code, itemdt_value, $txtSorDtId ".
								" from itemsdt ".
								" where itemsdt.item_code = '$item_code'";
				$resitemsdt = mysql_query($queryitemsdt,$connection);
				
				$queryitemsdt = " insert into temp_items (Item_Code,item_picture, item_picture2, trans_id)".
								" select item_code, item_picture, item_picture2, $txtSorDtId ".
								" from items ".
								" where items.item_code = '$item_code'";
				$resitemsdt = mysql_query($queryitemsdt,$connection);
			}  
		}
		if($message == '') $message="Sales Order was Duplicated";
}

// Cancel order from preporduction 
else if ($mode == "" && $mainmode == "cancelFromPreproduction" && $SSorId != ''){
	$update = "update sorderdt set sorderdt_sentProduction = 0 where Sorder_id = $SSorId ";
	$result = mysql_query($update, $connection);
	$message  = mysql_error(); 	
}
//Confirm Sales Order
else if(($mode == "confirmorder" || $mainmode == "confirmorder" || $mainmode == "unconfirmorder") && $SSorId != ''){
		
	$confirm_flag     = 0;
	$sorder_nettotal  = 0;
	$sorder_client    = '';
	$sorder_journalid = 0;
	$sorder_date      = '';
	$sorder_confirm   = 0;
	
	$DeliveryExists   = 0;
	$QtyExistExceeded = 0;
	
	$query = " SELECT ifNull((ifNull(Sorder_Taxable,0) + ifNull(Sorder_NoneTaxable,0) + IfNull(Sorder_VAT,0) - IfNull(Sorder_DiscountAmount,0) + IfNull(Sorder_TransportAmount,0)),0) As Sorder_NetTotal, ".
             " Client_Code, ifNull(Journal_Id, -1), Sorder_Date, sorder.currency_code, ifNull(Sorder_confirmed,0), Detail_Code, sorder.Project_Code, ifnull(Sorder_Paymentmode,0)	FROM sorder WHERE sorder_id = '".$SSorId."'";
	//echo "<br><br>".$query;
	$result = selectData($connection, $query);
	$sorder_nettotal  = $result[0];
	$sorder_client    = $result[1];
	$sorder_journalid = $result[2];
	$sorder_date      = $result[3];
	$sorder_currcode  = $result[4];
	$sorder_confirm   = $result[5];
	$sorder_clientdt  = $result[6];
	$sorder_project   = $result[7];
	$sorder_paymode   = $result[8];
	
	$sorder_date      = insertMySQLDate(displayToday());
	
	//Check Each SorderDt If Has RelatedId In DeliveryDt
	$sub_query = " Select Count(SorderDt.SorderDt_id) ".
				 " From SorderDt ".
				 " Inner Join DeliveryDt on SorderDt.SorderDt_id = DeliveryDt.RelatedDt_id ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " Where SorderDt.Sorder_id = ".$SSorId;

	$sub_result = selectData($connection, $sub_query);
	$DeliveryExists = $sub_result[0];
		
		
	//Check For QtyExists For Each Item	Before Confirm
	if ($Module_SorderCheckQtyOnPost != 1 && $sorder_confirm == 0 && ($Module_NegativeQuantity==0 || $Login_negativeQty==0)) {
		$sub_query = " Select SorderDt.Item_Code, SorderDt.Warehouse_Code, ifNull(SorderDt.SorderDt_Quantity,0), SorderDt.Sorder_Date, ifNull(Item_NonStock,0)  ".
					 " From SorderDt ".
					 " Inner Join Items on SorderDt.Item_Code = Items.Item_Code ".
					 " Where SorderDt.Sorder_ID = '".$SSorId."' ";
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());			  
		while($sub_row=mysql_fetch_array($sub_result)){
			//If Item Is None Stock
			if ($sub_row[4] == 0) {
				$sub_query1  = " Select QtyExistsWSorder('".$sub_row[0]."', '".$sub_row[1]."', '".$sub_row[3]."', 0, 'SO', '', '') QtyExists From Dual ";
				$sub_result1 = selectData($connection, $sub_query1);
				$vItemQtyExists = 0;
				$vItemQtyExists = $sub_result1[0];
					
				$sub_query2 = " Select ifNull(Sum(ifNull(TransferDt_Quantity,0)),0) FROM Temp_TransferDt ".
							  " WHERE Item_code = '".$sub_row[0]."'  And  TransferDt_WarehouseFrom = '".$sub_row[1]."' ";
				$sub_result2 = selectData($connection, $sub_query2);
				if (empty($sub_result2[0])) $sub_result2[0] = 0;
				$vItemQtyExists = $vItemQtyExists - $sub_result2[0];
					
			
				if (abs($sub_row[2]) > $vItemQtyExists && abs($sub_row[2]) > 0) {
					$QtyExistExceeded = 1;
					$message  = "Confirmation not allowed. Qty[".abs($sub_row[2])."] exceeds Existing Qty[$vItemQtyExists] for Item (".$sub_row[0].")"; 
					break;
				}	
			}
		
		}
	
	}
	
	if ($QtyExistExceeded == 0) {
	
		if(empty($sorder_journalid)) $sorder_journalid = -1;

		if ($sorder_confirm == 0) {	
			$query = "SELECT Client_CreditLimit, Client_PaymentTerms, Client_CashMode, Clients.Currency_Code FROM Clients WHERE Ledger_Number = '".$sorder_client."'";
			//echo "<br><br>".$query;
			$result = selectData($connection, $query);
			$vCltCreditLimit = $result[0];
			$vCltPaymentTerm = $result[1];
			$vCltCashMode    = $result[2];
			$vCltCurrCode    = $result[3];
			
			if ($Module_CreditLimitByProj == 1 && $sorder_project != '') {
				$query = "SELECT ifNull(Client_CreditLimit,0) FROM ClientsCreditLimit WHERE Client_Code = '".$sorder_client."' and '".$sorder_project."' like concat(Project_Code,'%') limit 1 ";
				//echo "<br><br>".$query;
				$result = selectData($connection, $query);
				$vCltCreditLimit = $result[0];
			}
			
			
			$vCltCreditLimit   = ConvertCurrency($vCltCurrCode, $sorder_currcode, $sorder_date, $vCltCreditLimit, $connection);
			
			if ($vCltCashMode == "1" || ($FI_SorderAllowConfirmCash == 1 && $sorder_paymode != 0)){
				$confirm_flag = 1;
			}else{
				if ($FA_ClientPaymentTerms == 1 && $FA_ClientCreditLimit == 1) {
					$confirm_flag = 1;
				} else {
					if ($FA_ClientCreditLimit == 0 && $Module_CreditLimit == 1){
						//Check Client Credit Limit
						//Get Current Balance
						if ($Module_CreditLimitByProj == 1 && $sorder_project != '') {
							$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), (-1)*if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1))), 0)) As Balance FROM journaldt ".
											" Left outer Join CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
											" where journaldt.journal_id != ".$sorder_journalid." and journaldt.ledger_number = '".$sorder_client."' ".
											" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".$sorder_date."','%Y%m%d') ".
											" and CstJour.Project_Code like concat('".$sorder_project."', '%') ";
						} else {
							$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', journaldt_amount1, (-1)*journaldt_amount1)), 0)) As Balance FROM journaldt ".
											" where journaldt.journal_id != ".$sorder_journalid." and ledger_number = '".$sorder_client."' ".
											" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".$sorder_date."','%Y%m%d') ";
						}	
										
						if ($sorder_clientdt != '')				
							$querybalance = $querybalance. " and journaldt.detail_code = '".$sorder_clientdt."'";
							
						//echo "<br><br>".$querybalance;exit;
						$result = selectData($connection, $querybalance);
						$q1 = $result[0];
						$q1 = ConvertCurrency($base1, $sorder_currcode, $sorder_date, $q1, $connection);
						
						$q2 = $sorder_nettotal;

						//if ($vCltCreditLimit >= ($q1 + $q2)){
						
						if (($vCltCreditLimit - ($q1 + $q2) + ($Perc_CreditLimit / 100 * $vCltCreditLimit)) > -3){
							$confirm_flag = 1;
						} else{
							$confirm_flag = 0;
							$message = "Confirmation not allowed. Exceed credit limit.";
						}
						
					} else
						$confirm_flag = 1;
					
					if ($confirm_flag == 1) {
						if ($FA_ClientPaymentTerms == 0 && $Module_PaymentTerms == 1){
							//Check Client payment Term
							$query = "select InvoiceDays('".$sorder_client."', '".$sorder_date."', 0)";
							//echo "<br><br>".$query;
							$result = selectData($connection, $query);
							
							if ($vCltPaymentTerm > $result[0]){
								$confirm_flag = 1;
							}else{
								$confirm_flag = 0;
								$message = "Confirmation not allowed. Exceed payment terms.";
							}
						} else
							$confirm_flag = 1;
					}
					
				}	
			}		
		} else
			$confirm_flag = 1;
	}		
	//echo $confirm_flag;exit;
	if ($confirm_flag == 1) {
		if ($sorder_confirm == 0 && ($mode == "confirmorder" || $mainmode == "confirmorder")) {	
			$query = "select Sorder_type from sorder where sorder_id=$SSorId;";
			$res = mysql_query($query,$connection);
			$rw = mysql_fetch_row($res);
			$sorderType = $rw[0];
			$query = "UPDATE Sorder SET sorder_confirmed = 1, Sorder_type= 'SO', Sorder_ConfirmUser = '".$_SESSION['useraccount']."' WHERE sorder_id = ".$SSorId."";
			//$query = "select 1 ";
//echo $query;exit;
//echo $sorderType;exit;
			if (updateData($connection, $query, true)){
				$message = "Preparation Order Confirmed";
				if($sorderType == 'PF' && $SubItem_Production == 1){
					SubitemProduction($SSorId, $Project_FromItems, $connection);
					//$querypro = "call sendNotification('Client_salesOrder_Raised','".$_SESSION["useraccount"]."',NULL, NULL, '$SSorId')";
					$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
						where notification_name='PF_Confirmed' and ifnull(view_access,0) = 1 ";
					$resacc = mysql_query($queryacc, $connection);
												
					//echo $queryacc;
					while ($rwacc = mysql_fetch_array($resacc)){
						
					$querynot = "call sendNotification('PF_Confirmed', '$rwacc[0]', $rwacc[1], $rwacc[2], $SSorId , '" .$_SESSION['useraccount'] ."') ";
					 // echo $querynot;exit;
													
					$resnot = mysql_query($querynot, $connection);
					}	
					
					
					
					//echo $querypro;exit;
					$respro = mysql_query($querypro,$connection);
				}
			}
			else
				$message  = mysql_error(); 
		} 
		else if ($sorder_confirm == 1 && $mainmode == "unconfirmorder"){
		
			if ($DeliveryExists > 0 ){
				$message  = 'Unconfirmation not allowed, preparation order delivered.';
			} else {
				$query = "UPDATE Sorder SET sorder_confirmed = 0, Sorder_ConfirmUser = null WHERE sorder_id = ".$SSorId."";

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

					$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
															where notification_name='PF_NotConfirmed' and ifnull(view_access,0) = 1 ";
					$resacc = mysql_query($queryacc, $connection);
												
					//echo $queryacc;
					while ($rwacc = mysql_fetch_array($resacc)){
					$querynot = "call sendNotification('PF_NotConfirmed', '$rwacc[0]', $rwacc[1], $rwacc[2], $SSorId, '" .$_SESSION['useraccount'] ."') ";
					 // echo $querynot;exit;
													
					$resnot = mysql_query($querynot, $connection);
					}		

					
			
			   }
				
				
				
				else
					
				
				
				{$message  = mysql_error();}
				
				
				
			}	
		}	
	} 


} 

//Cancel Sales Order
else if($mode == "" && $mainmode == "cancelorder" && $SSorId != ''){

	$DeliveryExists   = 0;
	
	//Check Each SorderDt If Has RelatedId In DeliveryDt
	$sub_query = " Select Count(SorderDt.SorderDt_id) ".
				 " From SorderDt ".
				 " Inner Join DeliveryDt on SorderDt.SorderDt_id = DeliveryDt.RelatedDt_id ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " Where SorderDt.Sorder_id = ".$SSorId;

	$sub_result = selectData($connection, $sub_query);
	$DeliveryExists = $sub_result[0];
	
	//Check Type of Sorder
	$sub_query = " Select upper(Sorder_Type) as SorderType  ".
				 " From Sorder ".
				 " Where Sorder.Sorder_Id = '".$SSorId."'";

	$sub_result = selectData($connection, $sub_query);
	$SorderType = $sub_result[0];
	
	if ($DeliveryExists > 0 ){
		$message  = 'Order COULD NOT be Cancelled, preparation order delivered.';
	}
	else if ($SorderType != 'SO' ){
		$message  = 'Order COULD NOT be Cancelled, Order Type should be SO.';
	} else {
		$query = "UPDATE Sorderdt SET sorderdt_olddata = 1 WHERE sorder_id = ".$SSorId."";	
		//echo "<br><br>".$query;
		if (updateData($connection, $query, true)){
			//$query = "UPDATE Sorder SET sorder_disapproved = 1, sorder_type = 'CA' WHERE sorder_id = ".$SSorId."";	
			$query = "UPDATE Sorder SET sorder_type = 'CA' WHERE sorder_id = ".$SSorId."";	
			//echo "<br><br>".$query;
			if (updateData($connection, $query, true)){
				$message = "Order Cancelled";
			}else{
				$message = "Order COULD NOT be Cancelled";
			}
		}else{
			$message = "Order COULD NOT be Cancelled";
		}	
	}	
}

//Retrieve Back Cancelled Sales Order
else if($mode == "" && $mainmode == "retrieveorder" && $SSorId != ''){

	$query = "UPDATE Sorderdt SET sorderdt_olddata = 0 WHERE sorder_id = ".$SSorId."";	
	//echo "<br><br>".$query;
	if (updateData($connection, $query, true)){
		$query = "UPDATE Sorder SET sorder_disapproved = 0, sorder_type = 'SO' WHERE sorder_id = ".$SSorId."";	
		//$query = "UPDATE Sorder SET sorder_type = 'SO' WHERE sorder_id = ".$SSorId."";	
		//echo "<br><br>".$query;
		if (updateData($connection, $query, true)){
			$message = "Canceled Order Retrieved Back.";
		}else{
			$message = "Canceled Order COULD NOT be Retrieved Back.";
		}
	}else{
		$message = "Canceled Order COULD NOT be Retrieved Back.";
	}	
		
}

//Disapprove Sales Order
else if($mode == "" && $mainmode == "disapproveorder" && $SSorId != ''){

	$DeliveryExists   = 0;
	
	//Check Each SorderDt If Has RelatedId In DeliveryDt
	$sub_query = " Select Count(SorderDt.SorderDt_id) ".
				 " From SorderDt ".
				 " Inner Join DeliveryDt on SorderDt.SorderDt_id = DeliveryDt.RelatedDt_id ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " Where SorderDt.Sorder_id = ".$SSorId;

	$sub_result = selectData($connection, $sub_query);
	$DeliveryExists = $sub_result[0];
	
	if ($DeliveryExists > 0 ){
		$message  = 'Order COULD NOT be Disapproved, preparation order delivered.';
	} else {
		$query = "UPDATE Sorder SET sorder_disapproved = 1 WHERE sorder_id = ".$SSorId."";	
		//echo "<br><br>".$query;
		if (updateData($connection, $query, true)){
			$message = "Order Disapproved";
			

     //$querynot = "call sendNotification('PF_Created', '$rwacc[0]', $rwacc[1], $rwacc[2], $SSorId) "; 
	// $resnot = mysql_query($querynot, $connection);			
			
	 
			
					$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
															where notification_name='PF_NotApproved' and ifnull(view_access,0) = 1 ";
					$resacc = mysql_query($queryacc, $connection);
												
					//echo $queryacc;
					while ($rwacc = mysql_fetch_array($resacc)){
					$querynot = "call sendNotification('PF_NotApproved', '$rwacc[0]', $rwacc[1], $rwacc[2], $SSorId, '" .$_SESSION['useraccount'] ."') ";
					 // echo $querynot;exit;
													
					$resnot = mysql_query($querynot, $connection);
					}		
					
					
		 
			
			
			
			
			
			
		}else{
			$message = "Order COULD NOT be Disapproved";
		}
		
	}
 
}
//Disapprove Sales Order
else if($mode == "" && $mainmode == "approveorder" && $SSorId != ''){

	$DeliveryExists   = 0;
	
	//Check Each SorderDt If Has RelatedId In DeliveryDt
	$sub_query = " Select Count(SorderDt.SorderDt_id) ".
				 " From SorderDt ".
				 " Inner Join DeliveryDt on SorderDt.SorderDt_id = DeliveryDt.RelatedDt_id ".
				 " And DeliveryDt.Journal_Type = 'DI' ".
				 " Where SorderDt.Sorder_id = ".$SSorId;

	$sub_result = selectData($connection, $sub_query);
	$DeliveryExists = $sub_result[0];
	
	if ($DeliveryExists > 0 ){
		$message  = 'Order COULD NOT be Approved, preparation order delivered.';
	} else {
		$query = "UPDATE Sorder SET sorder_disapproved = 0, sorder_type = 'SO' WHERE sorder_id = ".$SSorId."";	
		//echo "<br><br>".$query;
		if (updateData($connection, $query, true)){
			$message = "Order Approved";
			
			
					$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
															where notification_name='PF_Approved' and ifnull(view_access,0) = 1 ";
					$resacc = mysql_query($queryacc, $connection);
												
					//echo $queryacc;
					while ($rwacc = mysql_fetch_array($resacc)){
					$querynot = "call sendNotification('PF_Approved', '$rwacc[0]', $rwacc[1], $rwacc[2], $SSorId, '" .$_SESSION['useraccount'] ."') ";
					 // echo $querynot;exit;
													
					$resnot = mysql_query($querynot, $connection);
					}		
					
					
					
		}else{
			$message = "Order COULD NOT be Approved";
		}
		
	}	
}

//Post Mode	
else if($mode == "post" && $SSorId != ''){  

	if (!isset($txtCurr))
	   $txtCurr = $base1;
	
	if ($txtAssignedUser == '') $txtAssignedUser = $_SESSION['useraccount'];
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$txtCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$txtCurr."' )";
	$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];
	
	
			
	
	if (empty($txtSorDiscountAmt))	$txtSorDiscountAmt = 0;
	if (empty($txtSorDiscount))		$txtSorDiscount = 0;
	if (empty($txtSorTransportAmt))	$txtSorTransportAmt = 0;	
	if (empty($txtVehicleWeight))   $txtVehicleWeight = 0;
	if (empty($txtPayMode))  		$txtPayMode = 0;
			
	$txtCostCentCode = "".$txtCostCentCode;	
	$txtProjectCode = "".$txtProjectCode;
	if ($txtCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
			
	if ($txtProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
		
	if (empty($txtClientDtCode)) $ClientDtCode = 'Null';
	else	$ClientDtCode = "'".$txtClientDtCode."'";		
		
	$vSorRef = '';
	$vSorTaxable = 0;
	$vSorNoneTaxable = 0;
	$vSorGrossTotal = 0;
	$vSorDiscountAmt = 0;
	$vSorDiscountPer = 0;
	$vSorVat = 0;
	$vSorVatBase1 = 0;
	$vSorVatBase2 = 0;
	$vSorTotalTax = 0;
	$vSorTotal = 0;
	$vSorDisAmt = 0;
	
	$vSorTransportAmt   = 0;
	$vSorTransportAmtB1 = 0;
	$vSorTransportAmtB2 = 0;
	
	$vCltTax1 = 0;
	$vCltTax2 = 0;
	$vCltTax3 = 0;
	$vCltTax4 = 0;
	$vCltTax5 = 0;
	
	
	$vSorDtPriceTTC      = 0;
	$vSorDtPriceTTCBase1 = 0;
	$vSorDtPriceTTCBase2 = 0;					
	$vSorDtPrice      	 = 0;
	$vSorDtPriceBase1	 = 0;
	$vSorDtPriceBase2	 = 0;
	$vSorDtDiscAmt       = 0;
	$vSorDtDiscAmtBase1  = 0;
	$vSorDtDiscAmtBase2  = 0;
	$vSorDtTax1 = 0;
	$vSorDtTax2 = 0;
	$vSorDtTax3 = 0;
	$vSorDtTax4 = 0;
	$vSorDtTax5 = 0;
	
	$vSorDiscountPer = $txtSorDiscount;
	
	$SaveAllowed = 1;
	$ErrorExists = 0;
	

	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_sorderdt ".
				 " Where Sorder_ID = '".$SSorId."' ".
				 " And (Item_CodePacked Is Not Null and Item_CodePacked != '') ";
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$sub_rowcount = mysql_num_rows ($sub_result);
	
	if ($sub_rowcount > 0) {
		while($sub_row=mysql_fetch_array($sub_result)){
			$ItemQty = 0;
			$ItemPackQty = 0;
			
			$CheckQty = 0;
			$PackDtCode = '';
			$PackDtQty  = 0;
			
			$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
						  " From PackDt ".
						  " Where Item_Code = '".$sub_row[0]."' ";
			$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
			while($sub_row1=mysql_fetch_array($sub_result1)){
				// PackDt Items Should Be Different And Have Same Qty
				if ($PackDtCode != '' && $PackDtCode != $sub_row1[1] && $PackDtQty  == $sub_row1[2])
					$CheckQty = 1;
				
				$PackDtCode = $sub_row1[1];
				$PackDtQty  = $sub_row1[2];
			}
			
			// If PackDt Items Are Different And Have Same Qty Then Check For Qty Differences
			if ($CheckQty == 1) {
				$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
							  " From PackDt ".
							  " Where Item_Code = '".$sub_row[0]."' ";
				$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
				while($sub_row1=mysql_fetch_array($sub_result1)){
					$sub_query2 = " Select Item_CodePacked, Item_Code, Sum(ifNull(SorderDt_Quantity,0)) As SorderDtQuantity ".
								  " From temp_sorderdt ".
								  " Where Sorder_ID = '".$SSorId."' ".
								  " And Item_CodePacked = '".$sub_row1[0]."' ".
								  " And Item_Code = '".$sub_row1[1]."' ".
								  " Group by Item_CodePacked, Item_Code ";
								  
					$sub_result2 = selectData($connection, $sub_query2);
					$ItemPackQty = $sub_result2[2] / $sub_row1[2];
					if (empty($sub_result2[2])) $ItemPackQty = -1;
					
					if ($ItemQty == 0) $ItemQty = $ItemPackQty;
					if ($ItemQty != $ItemPackQty) $SaveAllowed = 0;
					
					
				}
			}		  
			
		}
	}
	
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($txtCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Costcenter Code.';
		}
	}
	if ($txtProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Project Code.';
		}
	}
	if ($txtClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$txtClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Client Code.';
		}
	}
	if ($txtSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$txtSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Salesman Code.';
		}
	}
	if ($txtClientDtCode != '') {
		$sub_query = " Select Count(Detail_Code) From ClientsDetail ".
					 " Where Detail_Code = '".$txtClientDtCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Client Detail Code.';
		}
	}
	
	if ($ErrorExists == 0) {
		//Checking For Qty Not To Be Zero
		$sub_query = " Select Count(*) From ( ".
					 " 	Select SorderDt.SorderDt_ID, SorderDt.Item_code, ifNull(SorderDt_Quantity,0) as SorderDt_Quantity ".
					 " 	From Temp_SorderDt As SorderDt ".
					 " 	Where SorderDt.Sorder_ID = ".$SSorId.
					 " 	And ifNull(SorderDt_Quantity,0) = 0 ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item(s) Quantity [Qty cannot be zero].';
		}		 
	}
	
	//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);
	}	
	
	$ExceedLockPeriod = 0;
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($txtDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	//echo $sub_query;exit;
	
	
	
	if ($SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
		
		$sub_query = " Select SorderDt_id, Currency_Code, ifNull(SorderDt_Price,0), ifNull(SorderDt_PriceBase1,0), ifNull(SroderDt_PriceBase2,0), ".
					 " ifNull(SorderDt_PriceTTC,0), ifNull(SorderDt_DiscountAmount,0), ifNull(SorderDt_DiscountBase1,0), ifNull(SorderDt_DiscountBase2,0), Item_code ".
					 " From temp_sorderdt ".
					 " Where Sorder_ID = ".$SSorId;	
			 
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
					
			$vSorDtPrice         = $sub_row[2];
			$vSorDtPriceBase1    = $sub_row[3];
			$vSorDtPriceBase2    = $sub_row[4];
			$vSorDtPriceTTC      = $sub_row[5];
			//$vSorDtPriceTTCBase1 = $sub_row[6];
			//$vSorDtPriceTTCBase2 = $sub_row[7];
			$vSorDtDiscAmt       = $sub_row[6];
			$vSorDtDiscAmtBase1  = $sub_row[7];
			$vSorDtDiscAmtBase2  = $sub_row[8];
			$txtItemCode = $sub_row[9];
					
			if ($sub_row[1] != $txtCurr) {
				$vSorDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSorDtPrice, $connection);
				$vSorDtPriceTTC = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSorDtPriceTTC, $connection);
				$vSorDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vSorDtDiscAmt, $connection);
						
				$vSaDtPriceBase1    = ($vSorDtPrice*$rate_dt)/$rate_dt1;
				$vSaDtPriceBase2    = ($vSorDtPrice*$rate_dt)/$rate_dt2;
				$vSaDtPriceTTCBase1 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt1;
				$vSaDtPriceTTCBase2 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt2;
				$vSaDtDiscAmtBase1  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt1;
				$vSaDtDiscAmtBase2  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt2;
					
					 
				$sub_query1 = " UPDATE temp_sorderdt SET  ".
							  " Currency_Code = '".$txtCurr."', ".
							  " SorderDt_Price = $vSorDtPrice, SorderDt_PriceBase1 = $vSorDtPriceBase1, SroderDt_PriceBase2 = $vSorDtPriceBase2, ".
							  " SorderDt_PriceTTC = $vSorDtPriceTTC, ".
							  " SorderDt_DiscountAmount = $vSorDtDiscAmt, SorderDt_DiscountBase1 = $vSorDtDiscAmtBase1, SorderDt_DiscountBase2 = $vSorDtDiscAmtBase2 ".
							  " Where SorderDt_ID = ".$sub_row[0];
					
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 
					
			}
			
			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
					" FROM Items WHERE item_Code = '".$txtItemCode."'";
			$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];
			$ItemNonStock  = $result[7];
			//$item_vat = $item_vat/100;
			$tax_flag = 0;
			$notax_flag = 1;
			if ($item_vat > 0){
				$tax_flag = 1;
				$notax_flag = 0;
			}	
			// 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, ".
					 " Trans_wasteDebitAcc, Trans_wasteCreditAcc, Trans_wasteDifferenceAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'SO' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";//echo $query;exit;
			$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]; 
			$vSaDtWasteDbt 			= $result[12]; 
			$vSaDtWasteCrd 			= $result[13]; 
			$vSaDtExportAcc 		= $result[14]; 	
			if ($Module_RawMaterial == 1 || $SubItem_Production == 1) {
				$vSaDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vSaDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vSaDtDirectStkCur = $vTranStpDirectStkCur;
				$vSaDtVatAcc       = $vTranStpVatAcc;
				$vSaDtDiscAcc      = $vTranStpDiscAcc;
				$vSaDtPromoAcc     = $vTranStpPromoAcc;
				
				//if($vSaDtChkGeneralAcc == 0){
					if ($item_vat > 0 && $SSorVatChkbx == 1) {
						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 && $SSorVatChkbx == 1)
					$vSaDtItemAcc = $vSaStpCreditVatAcc;
				else
					$vSaDtItemAcc = $vSaStpCreditAcc;	
						
			}
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtDirectStkDbt."') from dual "; //echo $sub_queryVat;exit;

			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtDirectStkDbt = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtDirectStkCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtDirectStkCrd = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtWasteDbt."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteDbt = $sub_resultVat[0];
			
			$sub_queryVat = " SELECT GetAllVATAccount('".$txtClientCode."','".$vSaDtWasteCrd."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vSaDtWasteCrd = $sub_resultVat[0];
			
			$sub_query1 = " UPDATE temp_sorderdt SET  ".
						  " Sorderdt_ItemAccount = '".$vSaDtItemAcc."', ".
						  " Sorderdt_DirectStkDbt = ".strformat($vSaDtDirectStkDbt).", ".
						  " Sorderdt_DirectStkCrd = ".strformat($vSaDtDirectStkCrd).", ".
						  " Sorderdt_DirectStkCur = ".strformat($vSaDtDirectStkCur).", ".
						  " Sorderdt_DirectWasteDbt = ".strformat($vSaDtWasteDbt).", ".
						  " Sorderdt_DirectWasteCrd = ".strformat($vSaDtWasteCrd).", ".
						  " Sorderdt_exportAccount = ".strformat($vSaDtExportAcc).", ".
						  " Sorderdt_PromoAcc	 = ".strformat($vSaDtPromoAcc)." ".
						  " Where SorderDt_ID = ".$sub_row[0]; 
			$res_query1 = mysql_query($sub_query1,$connection);			  
		}  //End Loop of SorderDt Query
		
		
		//Distribute The Total Discount On Detail Table
		$sub_query3 = " Select Sum((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0)*ifNull(SorderDt_Discount,0))/100)) As Total ".
					  " From Temp_SorderDt ".
					  " Where Sorder_ID = ".$SSorId;
		$sub_result3 = selectData($connection, $sub_query3);
		$vSorTotal   = $sub_result3[0];	
		$vSorDisAmt	 = $txtSorDiscountAmt;
		
		if ($SalesTTC == 1) {
			$vSorDisAmt  = ($txtSorDiscountAmt / (1 + $Setup_VatPercentage/100));
			$vSorTrsAmt  = ($txtSorTransportAmt / (1 + $Setup_VatPercentage/100));
		} else	{
			$vSorDisAmt  = $txtSorDiscountAmt;
			$vSorTrsAmt  = $txtSorTransportAmt;
		}
		
		$sub_query4 = " Select SorderDt_ID,  ".
					  " ((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0)*ifNull(SorderDt_Discount,0))/100)) As Total, ".
					  " ifnull(SorderDt_DiscountAmount,0) as SorderDt_DiscountAmount ".
					  " From Temp_SorderDt As SorderDt  ".
					  " Where SorderDt.Sorder_ID = ".$SSorId;
					  
				   
		//echo $query; 
		$sub_result4=mysql_query($sub_query4,$connection) or die(mysql_error());
		while($sub_rows4=mysql_fetch_array($sub_result4)){
		
			$vSorDtId 	 = $sub_rows4[0];
			$vSorDtTotal = $sub_rows4[1];
			
			
			
			$vSorDtDiscAmt	    = 0;
			if( $show_discountAmount == 1)
			$vSorDtDiscAmt 		=  $sub_rows4[2];
			else 	
			$vSorDtDiscAmt 		= ($vSorDtTotal/$vSorTotal)*$vSorDisAmt;
			$vSorDtDiscAmtBase1 = ($vSorDtDiscAmt*$rate_dt)/$rate_dt1;
			$vSorDtDiscAmtBase2 = ($vSorDtDiscAmt*$rate_dt)/$rate_dt2;
			
			$vSorDtTrsAmt    = 0;
			$vSorDtTrsAmt    = ($vSorDtTotal/$vSorTotal)*$vSorTrsAmt;
			$vSorDtTrsAmtB1  = ($vSorDtTrsAmt*$rate_dt)/$rate_dt1;
			$vSorDtTrsAmtB2  = ($vSorDtTrsAmt*$rate_dt)/$rate_dt2;
			
			$queryupd =  " UPDATE temp_sorderdt SET SorderDt_DiscountAmount = $vSorDtDiscAmt, SorderDt_DiscountBase1 = $vSorDtDiscAmtBase1, SorderDt_DiscountBase2 = $vSorDtDiscAmtBase2,  ".
						 " SorderDt_TransportAmount = $vSorDtTrsAmt, SorderDt_TransportBase1 = $vSorDtTrsAmtB1, SorderDt_TransportBase2 = $vSorDtTrsAmtB2 ".
						 " Where SorderDt_ID = ".$vSorDtId;
						 //" And Logged_Code = '".$PLoggedCode."' ";
			//echo $queryupd; exit;
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 
			

		}
		
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SSorId, $txtDate, $SSorVatChkbx, $vSorDiscountPer, $txtSorDiscountAmt, $txtSorTransportAmt, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $SalesTTC, 'P', $connection);
		$message  = $message . $CalculateResult;
				
		
		$clt_query = " SELECT Client_CreditLimit, Client_PaymentTerms, Client_CashMode, Clients.Currency_Code, Clients.Ledger_Name ".
					 " FROM Clients ".
					 " WHERE Ledger_number = '".$txtClientCode."'";
			
		$clt_result = selectData($connection, $clt_query);
		$vCltCreditLimit = $clt_result[0];
		$vCltPaymentTerm = $clt_result[1];
		$vCltCashMode    = $clt_result[2];
		$vCltCurrCode    = $clt_result[3];
		$vCltName        = $clt_result[4];
		
		if ($Module_CreditLimitByProj == 1 && $txtProjectCode != '') {
			$clt_query = "SELECT ifNull(Client_CreditLimit,0) FROM ClientsCreditLimit WHERE Client_Code = '".$txtClientCode."' and '".$txtProjectCode."' like concat(Project_Code,'%') limit 1 ";
			//echo "<br><br>".$clt_query;
			$clt_result = selectData($connection, $clt_query);
			$vCltCreditLimit = $clt_result[0];
		}
			
		// Checking For Client Credit Limit
		$ExceedCreditLimit = 0;
		$vCltCreditLimit   = ConvertCurrency($vCltCurrCode, $txtCurr, insertMySQLDate($txtDate), $vCltCreditLimit, $connection);
		
		
		//Get Client Current Balance
		$query_sorder  = " Select Journal_ID From Temp_Sorder Where Sorder_id = $SSorId ";
		$result_sorder = selectData($connection, $query_sorder);
		$vSorJournalID = $result_sorder[0];
		if(empty($vSorJournalID)) $vSorJournalID = -1;
					
		if ($Module_CreditLimitByProj == 1 && $txtProjectCode != '') {
			$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1), (-1)*if(CstJour.Cst_increment is null,Journaldt_amount1,Cstjour_amount1))), 0)) As Balance FROM journaldt ".
							" Left outer Join CstJour As CstJour on Journaldt.JournalDt_ID = Cstjour.JournalDt_ID ".
							" where journaldt.journal_id != ".$vSorJournalID." and journaldt.ledger_number = '".$txtClientCode."' ".
							" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate(displayToday())."','%Y%m%d') ".
							" and CstJour.Project_Code like concat('".$txtProjectCode."', '%') ";
		} else {
			$querybalance = " SELECT Round(IFNULL(SUM(if(journaldt_dbcd = 'D', ifNull(journaldt_amount1,0), (-1)*ifNull(journaldt_amount1,0))), 0)) As Balance FROM journaldt ".
							" where journaldt.journal_id != ".$vSorJournalID." and ledger_number = '".$txtClientCode."' ".
							" and date_format(journaldt.journal_date,'%Y%m%d') <= date_format('".insertMySQLDate(displayToday())."','%Y%m%d') ";
		}
		if ($txtClientDtCode != '')				
			$querybalance = $querybalance. " and journaldt.detail_code = '".$txtClientDtCode."'";
								
		//echo "<br>".$vCltCreditLimit."<br>".$querybalance; exit;
		$resultbalance = selectData($connection, $querybalance);
		$q1 = $resultbalance[0];
		$q1 = ConvertCurrency($base1, $txtCurr, insertMySQLDate($txtDate), $q1, $connection);
		
		$sub_query = " Select Round((ifNull(Sorder_Taxable,0) + ifNull(Sorder_NoneTaxable,0) + IfNull(Sorder_VAT,0) + ifNull(Sorder_TransportAmount,0) - IfNull(Sorder_DiscountAmount,0) ), ".$DecimalBase.") As Sorder_NetTotal ".
					 " From Temp_Sorder ".
					 " Where Sorder_ID = ".$SSorId;
		$sub_result = selectData($connection, $sub_query);
		$q2 = $sub_result[0];
		
		$vCltNewBalance = ($q1 + $q2);
		$vCltPreBalance = $q1;
		
		if ($Module_CreditLimitCheckPend == 1) {
			$sub_query = " Select Round(ifNull(Sum(ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_PriceBase1,0)*(1 - ifNull(Sorderdt_discount,0)/100) - IfNull(SorderDt_DiscountBase1,0)),0), ".$DecimalBase.") As Sale_NetTotal ".
						 " From SorderDt Inner Join Sorder on Sorder.Sorder_ID = SorderDt.Sorder_ID ".
						 " Where Sorder.Sorder_ID != ".$SSorId.
						 " And Sorder.Client_Code = '".$txtClientCode."' ".
						 " And Sorder.Sorder_Type = 'SO' ".
						 " And ifNull(SorderDt.Sorderdt_OldData,0) = 0 ".
						 " And SorderDt.SorderDt_ID Not In ( ".
						 "        Select RelatedDt_Id from DeliveryDt ".
                         "        Where RelatedDt_Id Is Not Null and RelatedDt_Id != '' ".
                         "        And DeliveryDt.Client_Code = '".$txtClientCode."' ".
                         "       ) ";
				
			if ($txtClientDtCode != '')				
				$sub_query = $sub_query. " And Sorder.Detail_Code = '".$txtClientDtCode."'";
			
			$sub_result = selectData($connection, $sub_query);
			$q3 = $sub_result[0];
			$q3 = ConvertCurrency($base1, $txtCurr, insertMySQLDate($txtDate), $q3, $connection);
						
			$vCltNewBalance += $q3;
			$vCltPreBalance += $q3;
		}

		if ($vCltCashMode == "1" || $FI_SorderRejectUnconfirmed == 0 || $txtSorType != 'SO' || ($FI_SorderAllowConfirmCash == 1 && $txtPayMode != 0)){
			$ExceedCreditLimit = 0;
		}else{  
			if ($FA_ClientCreditLimit == 1) {
				$ExceedCreditLimit = 0;
			} else { 
			
				if ($FA_ClientCreditLimit == 0 && $Module_CreditLimit == 1){ 
					
					//if ($vCltCreditLimit >= $vCltNewBalance){
					if (($vCltCreditLimit - $vCltNewBalance) > -3){
						$ExceedCreditLimit = 0;
					} else{
						$message = "Save not allowed. Exceed credit limit. Balance (Previous: ".number_format($vCltPreBalance, $DecimalBase)."  Current: ".number_format($q2, $DecimalBase)."  Total: ".number_format($vCltNewBalance, $DecimalBase)." )";
						$ExceedCreditLimit = 1;
					}
							
				} else
					$ExceedCreditLimit = 0;
						
				if ($ExceedCreditLimit == 0	) {
					if ($FA_ClientPaymentTerms == 0 && $Module_PaymentTerms == 1 ){
						//Check Client payment Term
						$query = "select InvoiceDays('".$txtClientCode."', '".insertMySQLDate(displayToday())."', 0)";
						//echo "<br><br>".$query;exit;
						$result = selectData($connection, $query);
							
						if ($vCltPaymentTerm > $result[0]){
							$ExceedCreditLimit = 0;
						}else{
							$ExceedCreditLimit = 1;
							$message = "Save not allowed. Exceed payment terms.";
						}
					} else
						$ExceedCreditLimit = 0;	
				}
					
					
			}
		
		}
			
		if($sorder_date	 == '') $sorder_date = $txtDate;
		$query = " UPDATE temp_sorder SET ".
				 " Sorder_Date = '".insertMySQLDate($txtDate)."', ".
				 " Sorder_RequestDate = '".insertMySQLDate($txtRequestDate)."', ".
				 " Sorder_MaturityDate = '".insertMySQLDate($txtMaturityDate)."', ".
				 " Sorder_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', Client_code = '".ereg_replace("'", "\'", trim($txtClientCode))."', ".
				 " Salesman_Code = '".ereg_replace("'", "\'", trim($txtSalesmanCode))."', Sorder_ClientContact = '".ereg_replace("'", "\'", trim($txtIAddress))."', ".
				 " Sorder_DeliveryPlace = '".ereg_replace("'", "\'", trim($txtDAddress))."', Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, ".
				 " Costcent_code = $CostCentCode, Sorder_type =  '".$txtSorType."', Detail_Code = $ClientDtCode, ".
				 " Sorder_DriverName = '".ereg_replace("'", "\'", trim($txtDriverName))."', Sorder_VehicalNo = '".ereg_replace("'", "\'", trim($txtVehicalNo))."', ".
				 " Sorder_VehicleWeight = $txtVehicleWeight, Sorder_Paymentmode = $txtPayMode, ".
				 " Sorder_ClientSorderDate = '".insertMySQLDate($sorder_date)."', Sorder_ClientPhone = '".$sorder_contactphone."', ".
				 " Sorder_ShippingWay = '".$sorder_card_msg."', Sorder_ShipName = '".$sorder_contact."', assignto_user = '".$txtAssignedUser."' ".
				 " WHERE Sorder_id = $SSorId ";
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			//echo $query; exit;
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
		//exit;
		if ($ExceedCreditLimit == 0) {		
			if ($result){
				//fcommit();
				$querydt = " UPDATE temp_sorderdt SET ".
						   " Currency_Code = '".$txtCurr."', Sorder_Date = '".insertMySQLDate($txtDate)."', ".
						   " Client_Code = '".ereg_replace("\'", "''", trim($txtClientCode))."' ";
						   
				if ($Module_ProjectDt != 1)
					$querydt = $querydt.", Project_Code = $ProjectCode ";
				if ($Module_CostCenterDt != 1)	
					$querydt = $querydt.", CostCent_Code = $CostCentCode ";
					
				$querydt = $querydt." WHERE Sorder_id = $SSorId ";		   
						  
						 
				//echo $querydt."<br>";exit;				
				$resultdt=mysql_query($querydt,$connection);
				
				if ($Module_ProjectDt == 1) {
					$querydt = " UPDATE temp_sorderdt SET Project_Code = $ProjectCode ".
							   " WHERE Sorder_id = $SSorId ".
							   " AND (Project_Code is null or Project_Code = '') ";
							   
					$resultdt=mysql_query($querydt,$connection);
				}
				if ($Module_CostCenterDt == 1) {
					$querydt = " UPDATE temp_sorderdt SET CostCent_Code = $CostCentCode ".
							   " WHERE Sorder_id = $SSorId ".
							   " AND (CostCent_Code is null or CostCent_Code = '') ";
					$resultdt=mysql_query($querydt,$connection);
				}
						
						
				if ($mainmode == 'insert') $SMode = 'I';
				if ($mainmode == 'edit') $SMode = 'U';
				//echo $SMode;exit;
				//$result = Distribute_TotalDiscount($SSorId, $rate_dt, $rate_dt1, $rate_dt2, $connection, $_SESSION['useraccount']);
				//echo $result; exit;
				
				$vSorTypeCode  = '';
				$vOldProjCode  	= '';
				$vOldCostCentCode = '';
				// In Edit Case, Get The Old Values For SorderType, Project and Costcenter For References Issue
				$query   = " SELECT Sorder_Type, Project_Code, Costcent_code  FROM Sorder WHERE Sorder_id = $SSorId ";
				$result  = selectData($connection, $query);
				$vSorTypeCode     = $result[0];
				$vOldProjCode     = $result[1];
				$vOldCostCentCode = $result[2];
				
				
				$query = "Select Count(*) From Temp_Sorder where Sorder_ID = '".$SSorId."'";
				//echo $query; exit;
				$result = selectData($connection, $query);
				$ExistInTemp = $result[0];	
				$query_checkDelivery  = "select count(*) as SalesOrderExist from sorder where sorder_id = '$SSorId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($SalesOrderExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
				//Check If Record Exists In Temp Tables
				if ($ExistInTemp == 1) {
					fbegin();
					$query = "SELECT CopyData_TempSorder('".$SMode."', ".$SSorId.", '".$_SESSION['useraccount']."') FROM Dual ";
					//echo $query;exit;
					$result = selectData($connection, $query);
					$result = $result[0];
					
					if ($result != 0){
						fcommit();
						
						$query   = " SELECT Sorder_Reference, Costcent_code, Project_Code FROM sorder WHERE Sorder_id = $SSorId "; //echo $query;echo "<br>";
						$result  = selectData($connection, $query);
						$vSorRef = $result[0];
						$vCostCentCode = $result[1];
						$vProjectCode  = $result[2];
						$existCode = 0;
						
						if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vSorRef != ''){
							$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
							$reschk = mysql_query($querychk, $connection);
							$rwchk = mysql_fetch_row($reschk);
							$existCode = $rwchk[0];
						}
						if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vSorRef != ''){
							$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
							$reschk = mysql_query($querychk, $connection);
							$rwchk = mysql_fetch_row($reschk);
							$existCode = $rwchk[0];
						}
						
						//if (($vSorRef == '') || ($vSorRef != '' && $vSorTypeCode != $txtSorType)) {
						if ($vSorRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
							($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {
							
							if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
							else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
							else $vProjCostCent = '';
							
							fbegin();
							$vSorRef = get_nextsequence('sorder_reference',$vProjCostCent,$connection);
							//$vSorRef = get_nextsequence_sordertype('Sorder_TypeReference', $txtSorType, $connection);	
							fcommit();
							
							$query = " UPDATE sorder SET ".
									 " Sorder_Reference = $vSorRef ".
									 " WHERE Sorder_id = $SSorId ";
							//echo $query;echo "<br>";exit;
							if (!updateData($connection, $query, true)) 
								$message  = mysql_error(); 
							
							if ( $vSorRef != '' && $txtSorType == 'PF'){
								$queryacc = "SELECT user_code, ifnull(nbrofdays,0), ifnull(view_access,0) FROM ".$_SESSION['dbLabel'].".notification_access
											where notification_name='PF_Created' and ifnull(view_access,0) = 1 ";
								$resacc = mysql_query($queryacc, $connection);
								
							//	echo $queryacc; exit;
								while ($rwacc = mysql_fetch_array($resacc)){
									$querynot = "call sendNotification('PF_Created', '$rwacc[0]', $rwacc[1], $rwacc[2], $SSorId, '') ";
                                    $querycumulation = $querycumulation . $querynot . "\n";
									
									$resnot = mysql_query($querynot, $connection);
								}		
								
							//	echo $querycumulation; exit;
							}
							
							
							
							
							//Send SalesOrder Email	
							if ($Module_SendSorderMail == 1 && $vSorRef != '') {
								$Errors = SendSorderMail($vSorRef, $_SESSION['useraccount'], $vCltName, $vCltNewBalance, $vCltCreditLimit, $txtCurr, $Setup_SorderMailMsg);
							}	
						
						}	
						
						if ($Module_GenerateSorderJV == 1 || $Module_GenerateSorderJV == 2) {
							$message = Create_SalesOrderJv($SSorId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username']); 
						}
						
						if($SubItem_Production == 1 && $txtSorType != 'PF'){
							$querydel = "delete from itemsdt where item_code in (select item_code from sorderdt where sorder_id=$SSorId)";//echo $querydel;echo"<br>";
							$resdel = mysql_query($querydel,$connection);
							$queryitemsdt = " insert into itemsdt (Item_Code,ItemParam_Code,itemdt_value) ".
											" select temp_itemsdt.Item_Code,ItemParam_Code,itemdt_value ".
											" from temp_itemsdt  inner join sorderdt on sorderdt_id = transid where sorder_id=$SSorId ";//echo $queryitemsdt;echo"<br>";
							$res = mysql_query($queryitemsdt,$connection);

							$queryitemsdt = " update items, temp_items, sorderdt ".
											" set items.item_picture = temp_items.item_picture, items.item_picture2 = temp_items.item_picture2  ".
											" where sorderdt_id = trans_id and sorder_id=$SSorId and  items.item_code = temp_items.item_code
											and  sorderdt.item_code = temp_items.item_code";
							$res = mysql_query($queryitemsdt,$connection);		
							$querydel = "delete from temp_itemsdt where transid in (select sorderdt_id from sorderdt where sorder_id=$SSorId) 
											and item_code in (select item_code from sorderdt where sorder_id=$SSorId)";//echo $querydel;echo"<br>";
							$resdel = mysql_query($querydel,$connection);
							$querydel = "delete from temp_items where trans_id in (select sorderdt_id from sorderdt where sorder_id=$SSorId)
										and item_code in (select item_code from sorderdt where sorder_id=$SSorId)";//echo $querydel;echo"<br>";
							$resdel = mysql_query($querydel,$connection);
						}
						if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SSorId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'sales_order', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}					 
					} else{
						$ErrorExists = 1;
						//$message  = mysql_error(); 
						$message  = 'Error In CopyData_TempSorder Function'; 
						frollback();
					}
				
				} 
				
			} else{
				$message  = mysql_error(); 
				frollback();
			}
		} else{
			//$message  = mysql_error(); 
			frollback();
		}	
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllowed == 0) 
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';
			
		frollback();
	}	
}

else if($mode == '' && $mainmode == 'loadtransfer'){

$ErrorExists = 0;
$transfdtIds = explode(",",$transferdtIds);

$querytransfer = "select distinct transferdt.transfer_id,ledger_number from transferdt
				 left join transfer on transfer.transfer_id = transferdt.transfer_id
				 left join clients on warehouse_code = transfer_warehouseto
				 where transferdt.transferdt_id in ($transferdtIds)";
$restransfer = mysql_query($querytransfer,$connection);
$rwtransfer = mysql_fetch_row($restransfer);
$transfer_id = $rwtransfer[0];
$PSorClientCode = $rwtransfer[1];


fbegin();	
$PSorId = get_nextsequence('sorder_id','',$connection);	
fcommit();

$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSorClientCode."'";
$result = selectData($connection, $query);
$PSorVatChkbx = $result[0]; 
	
	if ($ClientCur != '')
		$PSorCurr = $ClientCur;
	else
		$PSorCurr = $base1;
			
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSorCurr."' )";
	$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];


$queryins = "insert into temp_sorder(Sorder_id,Sorder_date,Sorder_RequestDate,Sorder_remark,Client_code,Costcent_code,Sorder_DeliveryDate,Project_Code,
			currency_code,Transfer_ID,Sorder_VatChckbx,User_Account) ".
			"select $PSorId, now(),now(),Transfer_Remark,clients.ledger_number, ToCostcenter_Code,now(),Project_Code2,'$PSorCurr',transfer_id,'$PSorVatChkbx',
			transfer.User_account
			from transfer ".
			"left join clients on clients.warehouse_code = transfer_warehouseto ".
			"where transfer_id = $transfer_id"; 
$result = mysql_query($queryins,$connection);			
if ($result){
			$SSorId = $PSorId;
			fcommit();
		}else{
			$PSorId = "";
			$SSorId = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
		
if($SSorId != '' && $ErrorExists == 0){
	foreach($transfdtIds as $transfdtId){
		
		$vSorDtPriceTTC      = 0;
		$vSorDtPriceTTCBase1 = 0;
		$vSorDtPriceTTCBase2 = 0;					
		$vSorDtPrice      	 = 0;
		$vSorDtPriceBase1	 = 0;
		$vSorDtPriceBase2	 = 0;
		$vSorDtDiscAmt       = 0;
		$vSorDtDiscAmtBase1  = 0;
		$vSorDtDiscAmtBase2  = 0;
		$vItemVat = 0;
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vSorDtTax1 = 0;
		$vSorDtTax2 = 0;
		$vSorDtTax3 = 0;
		$vSorDtTax4 = 0;
		$vSorDtTax5 = 0;
		
		
		$InsertAllow = 1;
		$QtyExistExceeded   = 0;
		
		$query = "select item_code,item_unitcoef,transferdt_warehouseto, date_format(transfer_date,'%d-%m-%Y'),transferdt_quantity,transferdt_price 
				from transferdt where transferdt_id = $transfdtId"; 
		$res = mysql_query($query,$connection);
		$rws = mysql_fetch_row($res);
		$txtItemCode = $rws[0];
		$txtSorDtQty2 = $rws[1];
		$lstWarehouse = $rws[2];
		$PSorDate = $rws[3];
		$txtSorDtQty = $rws[4];
		$txtSorDtOQty = $txtSorDtQty;
		$txtSorDtCQty = 0;
		$txtSorDtPrice = $rws[5];
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		if ($InsertAllow == 1) {
		if ($ItemPack != 1) {
		
		$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0) ".
						" FROM Items WHERE item_Code = '".$txtItemCode."'";
		
		$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];
		$ItemNonStock  = $result[7];
		//$item_vat = $item_vat/100;
		$tax_flag = 0;
		$notax_flag = 1;
		if ($item_vat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
		
		$vItemUnitCoef = 0;
		$vItemUnit2Qty = 0;
		if ($Module_DoubleUnit == 1) {
					
			$vItemUnitCoef = $ItemUnit;
			$vItemUnit2Qty = $txtSorDtQty2;
		}
		
		$QtyExistExceeded = 0;
				if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
					fbegin();
					$txtSorDtId = get_nextsequence('sorderdt_id','',$connection);	
					fcommit();

						
					$txtSorDtQty = $txtSorDtOQty - $txtSorDtCQty;
					//if item promotion the set price to zero
					// if($ItemPromo == 1) $txtSorDtPrice = 0;
					
					if ($SalesTTC == 1) {
						$vSorDtPriceTTC      = $txtSorDtPrice;
						$vSorDtPriceTTCBase1 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt1;
						$vSorDtPriceTTCBase2 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt2;	
					
						$vSorDtPrice      = ($vSorDtPriceTTC / (1 + $item_vat/100));
						$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
						$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
								
					} else	{
						$vSorDtPrice      = $txtSorDtPrice;
						$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
						$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
						
						$vSorDtPriceTTC      = 0;
						$vSorDtPriceTTCBase1 = 0;
						$vSorDtPriceTTCBase2 = 0;
								
					}	
						
					
					// Calculation For Detail Discount Amount
					$vSorDtDiscAmt       = 0;
					$vSorDtDiscAmtBase1  = 0;
					$vSorDtDiscAmtBase2  = 0;

					if ($Module_AdditionalTaxes == 1) {
						
						// Calculation of Item Tax Amounts
						$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
								 " FROM Clients ".
								 " WHERE Ledger_number = '".$PSorClientCode."'";
												 
						$result = selectData($connection, $query);
						$vCltTax1 = $result[0];
						$vCltTax2 = $result[1];
						$vCltTax3 = $result[2];
						$vCltTax4 = $result[3];
						$vCltTax5 = $result[4];
										
						$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
								 " FROM Items ".
								 " WHERE Item_Code = '".$txtItemCode."'";
												 
						$result = selectData($connection, $query);

							
						if ($vCltTax1 != 0)	$vSorDtTax1 = $result[0];
						if ($vCltTax2 != 0)	$vSorDtTax2 = $result[1];
						if ($vCltTax3 != 0)	$vSorDtTax3 = $result[2];
						if ($vCltTax4 != 0)	$vSorDtTax4 = $result[3];
						if ($vCltTax5 != 0)	$vSorDtTax5 = $result[4];
								
					}
					
					
					// 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 = 'SI' ".
							 " 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 && $PSorVatChkbx == 1) {
							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 && $PSorVatChkbx == 1)
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditAcc;	
								
					}
					
							
					if($sorderdt_clientdiscount=='') $sorderdt_clientdiscount=0;
					if($sorderdt_itemdiscount=='')  $sorderdt_itemdiscount=0;

					
					fbegin();
					//here
					$query = " INSERT INTO temp_sorderdt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
							 " SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
							 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, SorderDt_oqty, SorderDt_cqty, Sorderdt_promotion, Sorderdt_ItemAccount, Logged_Code, 
								sorderdt_itemunit, sorderdt_clientdiscount,sorderdt_itemdiscount, relateddt_id) ".
							 " select ".$txtSorDtId.", ".$SSorId.", ifnull(Cur_code,'$PSorCurr'), '".insertMySQLDate($PSorDate)."', '".ereg_replace("\'", "''", trim($PSorClientCode))."',  ".
							 " Project_Code2, ToCostcent_Code, '".$lstWarehouse."', '".$txtItemCode."', Null, $txtSorDtQty, 0, $vSorDtPrice, $vSorDtPriceBase1, $vSorDtPriceBase2, 0, $vSorDtDiscAmt, $vSorDtDiscAmtBase1, $vSorDtDiscAmtBase2, $item_vat, ".
							 " $vSorDtPriceTTC, TRANSFERDT_REMARK,  $vSorDtTax1, $vSorDtTax2, $vSorDtTax3, $vSorDtTax4, $vSorDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $txtSorDtQty, 0,  ".
							 " $ItemPromo, '".$vSaDtItemAcc."', '".$_SESSION['useraccount']."', Item_Unit2Qty, $sorderdt_clientdiscount,$sorderdt_itemdiscount, $transfdtId ".
							 " from transferdt where transferdt_id=$transfdtId";
 
					//echo $query;exit;				
					$result=mysql_query($query,$connection);
								
					if ($result){
						fcommit();
					}else{
						$txtSorDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error($connection); 
						
						frollback();
					}	
				} else {
					$txtSorDtId = "";
					$ErrorExists = 1;
					$message  = "Qty[".abs($txtSorDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")"; 
				}		
		
		}//end of item pack
		else {
			
				$promo_display = true;
				$promo_exhausted = 0;
				
				
				$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
							   " FROM PackDt ".
							   " WHERE Item_Code = '".$txtItemCode."'  ";
									   
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
						
					$vItemCodePacked = $rowspackdt[0];
					$vItemCode = $rowspackdt[1];
					$vPackDtQty = $rowspackdt[2];
					$vPackDtCostPer = $rowspackdt[3];
					$vPackDtPromo = $rowspackdt[4];
					$vPackDtPromoQty = $rowspackdt[5];
					
					$query = " SELECT ifNull(Item_NonStock,0) ".
							 " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$ItemNonStock  = $result[0];
						
					$vSorDtQty = $txtSorDtQty;
					// Check For Each Detail Promo Item If Promotion Exhausted For Date / Qty
					if($vPackDtPromo == 1 && $vPackDtPromoQty > 0){
						
						if (insertParadoxDate(substr($rowspackdt[6], 0, 10)) <= insertToday() && insertParadoxDate(substr($rowspackdt[7], 0, 10)) >= insertToday()){
							//$sub_query = "SELECT sum(stktransaction.QuantityProduceIn - stktransaction.QuantityProduceOut + stktransaction.QuantityEntered - stktransaction.QuantityDelivered) FROM stktransaction WHERE Item_CodePacked = '".$txtItemCode."' AND Transaction_Date >= '".$sub_result[1]."' AND Transaction_Date <= '".$sub_result[2]."'";
							$sub_query = " Select Sum(ifNull(SorderDt_Quantity,0)) ".
										 " From SorderDt ".
										 " Inner Join Sorder on SorderDt.Sorder_ID = Sorder.Sorder_ID ".
										 " Where SorderDt.Item_CodePacked = '".$txtItemCode."' ".
										 " And SorderDt.Item_Code = '".$vItemCode."' ".
										 " And ifNull(Sorder.Sorder_disapproved,0) = 0 ".
										 " And ifNull(SorderDt.Sorderdt_OldData,0) = 0 ".
										 " And Sorder.Sorder_Type = 'SO' ".
										 " And Sorder.Sorder_Date >= '".$rowspackdt[6]."' and Sorder.Sorder_Date <= '".$rowspackdt[7]."' ";

							//echo "<br><br>".$sub_query;exit;
							$sub_result = selectData($connection, $sub_query);

							if ($vPackDtPromoQty <= ($sub_result[0] + $txtSorDtOQty*$vPackDtQty)){
								$promo_exhausted = 1;
							}
						}else{
							$promo_exhausted = 1;
						}
						
					}
					
					//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
					/*if ($ItemNonStock == 0  && $Module_SorderCheckQtyOnPost == 1) {
						$sub_query  = " Select QtyExistsWSorder('".$vItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PSorDate)."', 0, 'SO', '', '') QtyExists From Dual ";
						$sub_result = selectData($connection, $sub_query);
						$vItemQtyExists = 0;
						$vItemQtyExists = $sub_result[0];
							
						$sub_query1 = " Select ifNull(Sum(ifNull(TransferDt_Quantity,0)),0) FROM Temp_TransferDt ".
									  " WHERE Item_code = '".$vItemCode."'  And  TransferDt_WarehouseFrom = '".$lstWarehouse."' ";
						$sub_result1 = selectData($connection, $sub_query1);
						if (empty($sub_result1[0])) $sub_result1[0] = 0;
						
						$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
						$vSorDtQty      = $vSorDtQty*$vPackDtQty;
							
								
						if (abs($vSorDtQty) > $vItemQtyExists && abs($vSorDtQty) > 0)
							$QtyExistExceeded = 1;
					}*/
					
					if ($promo_exhausted == 1) break;
				}

						$QtyExistExceeded = 0;
				
				//echo $promo_exhausted.$querypackdt; exit;			
				if ($promo_exhausted == 0 && ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1))){
					fbegin();
					
					$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage, ifNull(PackDt_Promotion,0), ifNull(Packdt_totalpromotion,0), PackDt_FromDate, PackDt_ToDate ".
								   " FROM PackDt ".
								   " WHERE Item_Code = '".$txtItemCode."'  ";
									   
					$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
					while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
						
						$vItemCodePacked = $rowspackdt[0];
						$vItemCode = $rowspackdt[1];
						$vPackDtQty = $rowspackdt[2];
						$vPackDtCostPer = $rowspackdt[3];
						$vPackDtPromo = $rowspackdt[4];
						$vPackDtPromoQty = $rowspackdt[5];
						
											
						

						fbegin();
						$vSorDtId = get_nextsequence('sorderdt_id','',$connection);
						fcommit();

						$vSorDtOQty = $txtSorDtOQty*$vPackDtQty;
						$vSorDtCQty = $txtSorDtCQty*$vPackDtQty;
						$vSorDtQty  = $vSorDtOQty - $vSorDtCQty;
							
							
								
						$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock,0) ".
								 " FROM Items WHERE item_Code = '".$vItemCode."'";
						$result = selectData($connection, $query);
						$item_vat 	   = $result[0];
						$Item_MaxQty   = $result[1];
						$ItemGroupCode = $result[2];
						$ItemProd	   = $result[3];
						$ItemTTCInc    = $result[4];
						$ItemUnit  	   = $result[5];
						$ItemNonStock  = $result[7];
						
						$tax_flag = 0;
						$notax_flag = 1;
						if ($item_vat > 0){
							$tax_flag = 1;
							$notax_flag = 0;
						}

						$vItemUnitCoef = 0;
						$vItemUnit2Qty = 0;
						if ($Module_DoubleUnit == 1) {
							/*if ($ItemUnit > 0) {
								$vItemUnitCoef = 1/$ItemUnit;
								$vItemUnit2Qty = $vItemUnitCoef * $vSorDtOQty;
							}*/
							
							$vItemUnitCoef = $ItemUnit;
							
							if ($Module_Unit1Method == 1)
								$vItemUnit2Qty = $vSorDtQty*$vItemUnitCoef;
							else	
								$vItemUnit2Qty = $vSorDtQty/$vItemUnitCoef;
						}	
						
						
								
						
							$vSorDtPriceTTC      = 0;
							$vSorDtPriceTTCBase1 = 0;
							$vSorDtPriceTTCBase2 = 0;					
							$vSorDtPrice      	 = 0;
							$vSorDtPriceBase1 	 = 0;
							$vSorDtPriceBase2 	 = 0;
							$vSorDtDiscAmt       = 0;
							$vSorDtDiscAmtBase1  = 0;
							$vSorDtDiscAmtBase2  = 0;
									
							$vCltTax1 = 0;
							$vCltTax2 = 0;
							$vCltTax3 = 0;
							$vCltTax4 = 0;
							$vCltTax5 = 0;
							$vSorDtTax1 = 0;
							$vSorDtTax2 = 0;
							$vSorDtTax3 = 0;
							$vSorDtTax4 = 0;
							$vSorDtTax5 = 0;

									
							if ($SalesTTC == 1) {
								$vSorDtPriceTTC      = (($txtSorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vSorDtPriceTTCBase1 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt1;
								$vSorDtPriceTTCBase2 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt2;

								//Added 2011/10/27
								//if ($PSorVatChkbx == 1)	$vSorDtPrice = ($vSorDtPriceTTC / (1 + $item_vat/100));
								//else $vSorDtPrice = $vSorDtPriceTTC;												
										
								$vSorDtPrice      = ($vSorDtPriceTTC / (1 + $item_vat/100));
								$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
								$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
										
							} else	{
								$vSorDtPrice      = (($txtSorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
								$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
										
								$vSorDtPriceTTC      = 0;
								$vSorDtPriceTTCBase1 = 0;
								$vSorDtPriceTTCBase2 = 0;
										
							}
									
							// Calculation For Detail Discount Amount
							$vSorDtDiscAmt       = 0;
							$vSorDtDiscAmtBase1  = 0;
							$vSorDtDiscAmtBase2  = 0;

							if ($Module_AdditionalTaxes == 1) {
									
								// Calculation of Item Tax Amounts
								$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
										 " FROM Clients ".
										 " WHERE Ledger_number = '".$PSorClientCode."'";
															 
								$result = selectData($connection, $query);
								$vCltTax1 = $result[0];
								$vCltTax2 = $result[1];
								$vCltTax3 = $result[2];
								$vCltTax4 = $result[3];
								$vCltTax5 = $result[4];
													
								$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
										 " FROM Items ".
										 " WHERE Item_Code = '".$vItemCode."'";
															 
								$result = selectData($connection, $query);

										
								if ($vCltTax1 != 0)	$vSorDtTax1 = $result[0];
								if ($vCltTax2 != 0)	$vSorDtTax2 = $result[1];
								if ($vCltTax3 != 0)	$vSorDtTax3 = $result[2];
								if ($vCltTax4 != 0)	$vSorDtTax4 = $result[3];
								if ($vCltTax5 != 0)	$vSorDtTax5 = $result[4];
											
							}
					
							// 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 = 'SI' ".
									 " 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 && $PSorVatChkbx == 1) {
									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 && $PSorVatChkbx == 1)
									$vSaDtItemAcc = $vSaStpCreditVatAcc;
								else
									$vSaDtItemAcc = $vSaStpCreditAcc;	
							}	

							
							$query = " INSERT INTO temp_sorderdt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
									 " Item_QtyPacked, SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
									 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, SorderDt_oqty, SorderDt_cqty, Sorderdt_promotion, Sorderdt_ItemAccount, Logged_Code,relateddt_id ) ".
									 " select ".$vSorDtId.", ".$SSorId.", ifnull(Cur_code,'$PSorCurr'), '".insertMySQLDate($PSorDate)."', '".ereg_replace("\'", "''", trim($PSorClientCode))."',  ".
									 " Project_Code2, ToCostcent_Code, '".$lstWarehouse."', '".$vItemCode."', '".$vItemCodePacked."', $vSorDtQty, 0, $txtSorDtOQty, $vSorDtPrice, $vSorDtPriceBase1, $vSorDtPriceBase2, 0, $vSorDtDiscAmt, $vSorDtDiscAmtBase1, $vSorDtDiscAmtBase2, $item_vat, ".
									 " $vSorDtPriceTTC, TRANSFERDT_REMARK,  $vSorDtTax1, $vSorDtTax2, $vSorDtTax3, $vSorDtTax4, $vSorDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $vSorDtOQty, 0, ".
									 " $vPackDtPromo, '".$vSaDtItemAcc."', '".$_SESSION['useraccount']."', $transfdtId ".
									 " from transferdt where transferdt_id=$transfdtId ";

							$result=mysql_query($query,$connection);
											
							//echo $query;
						
						
					} // End Loop Of Packdt
					
				
					if ($result){
						fcommit();
					}else{
						$txtSorDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error($connection); 
						frollback();
					}	
					
						
				} else{
					$txtSorDtId = "";
					$ErrorExists = 1;
					
					if ($promo_exhausted == 1)
						$message = $message . "<br>Item ".$lstItem." COULD NOT be Added. Promo Qty / Period Exhausted";
					else if ($QtyExistExceeded == 1)
						$message  = "Qty[".abs($vSorDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$vItemCode.")"; 
						
					frollback();
				}
				
			}
		
		if ($ErrorExists == 0) {
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SSorId, $PSorDate, $PSorVatChkbx, 0, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
				$message  = $message . $CalculateResult;
			}
		}//end allow insert
	}//end of foreach

}	
	
	
}
else
//Submit Record Mode
if ($mode == "import"){
	
	$ErrorExists = 0;
	
	if (!isset($PSorCurr))
	   $PSorCurr = $base1;
	   
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PSorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PSorCurr."' )";
	$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];
	
	//Check For Client, Salesman, Project and Costcenter Codes Before Insert
	if ($PSorCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PSorCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PSorProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PSorProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}	
	}
	if ($PSorClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PSorClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Code.';
		}
	}
	if ($PSorSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSorSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Salesman Code.';
		}
	}
	if ($PSorClientDtCode != '') {
		$sub_query = " Select Count(Detail_Code) From ClientsDetail ".
					 " Where Detail_Code = '".$PSorClientDtCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Client Detail Code.';
		}
	}
	
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	$txtProjectCodeDt = $PSorProjectCode;
	$txtCostCentCodeDt = $PSorCostCentCode;
	
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	
	//Insert Master Table
	if ($SSorId == "" && $ErrorExists == 0){
	
		if (empty($PSorDiscountAmt))
			$PSorDiscountAmt = 0;
		if (empty($PSorDiscount))
			$PSorDiscount = 0;
			
		$PSorCostCentCode = "".$PSorCostCentCode;
		$PSorProjectCode = "".$PSorProjectCode;
		if ($PSorCostCentCode == '')
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSorCostCentCode."'";
			
		if ($PSorProjectCode == '')
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSorProjectCode."'";
			
		if (empty($PSorClientDtCode)) $ClientDtCode = 'Null';
		else	$ClientDtCode = "'".$PSorClientDtCode."'";	
		
		if (empty($PVehicleWeight)) $PVehicleWeight = 0;
		if (empty($PPayMode)) $PPayMode = 0;
			
		fbegin();	
		$PSorId = get_nextsequence('sorder_id','',$connection);	
		fcommit();
		
		//$query = "SELECT Client_CashMode FROM Clients WHERE Ledger_Number = '".$PSorClientCode."'";
		//echo "<br><br>".$query;
		//$result = selectData($connection, $query);
		//$c_cashmode = $result[0];
		//if ($c_cashmode == 1 && $Module_SorderAutoConfirm == 1) $SorderConfirmed = 1; else $SorderConfirmed = 0; 
		
		if ($Module_SorderAutoConfirm == 1) $SorderConfirmed = 1; else $SorderConfirmed = 0; 
		
		// Get Vat Checkbox From Client
		$query  = "SELECT ifNull(Client_VAT,0) FROM Clients WHERE Ledger_Number = '".$PSorClientCode."'";
		$result = selectData($connection, $query);
		$PSorVatChkbx = $result[0];
		
		fbegin();
		$sorder_date         = $_GET['sorder_date'];
		$sorder_card_msg     = $_GET['sorder_card_msg'];
		$sorder_contact      = $_GET['sorder_contact'];
		$sorder_contactphone = $_GET['sorder_contactphone']; 
		$query = " INSERT INTO temp_sorder (Sorder_id, Sorder_Reference, Sorder_Date, Sorder_RequestDate, Sorder_MaturityDate, Sorder_Remark, Client_code, Sorder_ClientContact, Sorder_DeliveryPlace, Salesman_Code, Currency_Code, ".
				 " Project_Code, Costcent_code, Sorder_Posted, Sorder_Taxable, Sorder_TaxableBase1, Sorder_TaxableBase2, Sorder_NoneTaxable, Sorder_NoneTaxableBase1, Sorder_NoneTaxableBase2, Sorder_DiscountAmount, Sorder_DiscountBase1, ".
				 " Sorder_DiscountBase2, Sorder_DiscountPer, Sorder_VAT, Sorder_VATBase1, Sorder_VATBase2, Sorder_VatChckbx, Sorder_confirmed, Sorder_disapproved, Sorder_type, Sorder_TotalQuantity, Sorder_TotalQuantityUsed, ".
				 " Sorder_Paymentmode, Journal_Type, Journal_Id, Sorder_Hide, Sorder_BelongsToGrp, Detail_Code, Sorder_Status, Sorder_DriverName, Sorder_VehicalNo, Sorder_VehicleWeight, Sorder_TransportAccount, User_Account, Logged_Code, Sorder_ClientSorderDate, Sorder_ClientPhone, Sorder_ShippingWay, Sorder_ShipName) ".
				 " VALUES ( ".$PSorId.", Null,  '".insertMySQLDate($PSorDate)."', '".insertMySQLDate($PSorRequestDate)."', ".
				 "          '".insertMySQLDate($PSorMaturityDate)."', '".ereg_replace("'", "\'", trim($PSorRemark))."', '".ereg_replace("'", "\'", trim($PSorClientCode))."', ".
				 "          '".ereg_replace("'", "\'", trim($PSorIAddress))."', '".ereg_replace("'", "\'", trim($PSorDAddress))."', '".ereg_replace("'", "\'", trim($PSorSalesmanCode))."', '".$PSorCurr."', ".
				 "          $ProjectCode, $CostCentCode, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PSorVatChkbx, $SorderConfirmed, 0, '".$PSorType."', 0, 0, $PPayMode, 'SO', Null, 0, $FI_BelongsToGrp, $ClientDtCode, 0, ".
				 "          '".ereg_replace("'", "\'", trim($PDriverName))."', '".ereg_replace("'", "\'", trim($PVehicalNo))."', $PVehicleWeight, '".$TransportAccount."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."', '".insertMySQLDate($sorder_date)."', '".$sorder_contactphone."', '".$sorder_card_msg."', '".$sorder_contact."')";
					 
			 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SSorId = $PSorId;
			fcommit();
		}else{
			$PSorId = "";
			$SSorId = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SSorId != "" && $SSorDtId == "" && $txtItemCode != ""  && $ErrorExists == 0){
	
	if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 

		$image_name = addslashes($_FILES['image']['name']);
		$image_size = getimagesize($_FILES['image']['tmp_name']);
		$image_type =$_FILES['image']['type'];
		//	echo$_FILES['image']['size'];
			
		if ($image_size == FALSE) {
			$error['image'] = "That's not an image.";
		
		}
		else 
			if ($_FILES['image']['size'] > 204800) {
				$error['image'] = "Image is too large.";
			}
			else {
				$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
			}
	}
	
	$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);



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


	$x=1;
	$arrayemp = array();
	
    while($x<=$excel->sheets[0]['numRows']) { ///rowwwww
            
		$txtItemCode = $excel->sheets[0]['cells'][$x][1];
		$itemdesc = $excel->sheets[0]['cells'][$x][2];
		//$lstWarehouse = $excel->sheets[0]['cells'][$x][3];
		$txtSorDtQty = $excel->sheets[0]['cells'][$x][4];
		$txtSorDtOQty = $excel->sheets[0]['cells'][$x][4];
		$txtSorDtPrice = $excel->sheets[0]['cells'][$x][5];
		
		
		if ($txtItemCode != '') {
			$sub_query = " Select Count(Item_Code) From Items ".
						 " Where Item_Code = '".$txtItemCode."'";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] == 0) {
				$ErrorExists = 1;
				$message = 'Insert not allowed. Please check for Item Code.';
			}
		}
	
		if (empty($PSorDiscountAmt))
			$PSorDiscountAmt = 0;
		if (empty($PSorDiscount))
			$PSorDiscount = 0;
			
		if (empty($txtSorDtPrice))
			$txtSorDtPrice = 0;
		if (empty($txtSorDtDiscount))
		   $txtSorDtDiscount = 0;
		if (empty($txtSorDtOQty))
		   $txtSorDtOQty = 0;      
		if (empty($txtSorDtCQty))
		   $txtSorDtCQty = 0;      
		if (empty($txtSorDtQty))
		   $txtSorDtQty = 0;      	
		if (empty($txtSorDtQty2))
		   $txtSorDtQty2 = 0;      	  
					
			
		if (empty($PSorCostCentCode))
			$CostCentCode = 'Null';
		else
			$CostCentCode = "'".$PSorCostCentCode."'";
			
		if (empty($PSorProjectCode))
			$ProjectCode = 'Null';
		else
			$ProjectCode = "'".$PSorProjectCode."'";	
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}
		
		
		$vSorDtPriceTTC      = 0;
		$vSorDtPriceTTCBase1 = 0;
		$vSorDtPriceTTCBase2 = 0;					
		$vSorDtPrice      	 = 0;
		$vSorDtPriceBase1	 = 0;
		$vSorDtPriceBase2	 = 0;
		$vSorDtDiscAmt       = 0;
		$vSorDtDiscAmtBase1  = 0;
		$vSorDtDiscAmtBase2  = 0;
		$vItemVat = 0;
				
		$vCltTax1 = 0;
		$vCltTax2 = 0;
		$vCltTax3 = 0;
		$vCltTax4 = 0;
		$vCltTax5 = 0;
		$vSorDtTax1 = 0;
		$vSorDtTax2 = 0;
		$vSorDtTax3 = 0;
		$vSorDtTax4 = 0;
		$vSorDtTax5 = 0;
		
		
		$InsertAllow = 1;
		$QtyExistExceeded   = 0;

		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		
		
		if ($InsertAllow == 1) {
		
			// Case Not Pack Item
			//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All") {
			if ($ItemPack != 1) {

				$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_Promotion, 0), ifNull(Item_NonStock,0), ".
						 " Currency_Code, ifNull(Item_SellingPrice1,0), ifNull(Item_SellingPrice1Base1,0), ifNull(Item_SellingPrice1Base2,0), Items.Warehouse_Code ".
						 " FROM Items WHERE item_Code = '".$txtItemCode."'";
				$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];
				$ItemNonStock  = $result[7];
				$ItemCurr      = $result[8];
				$lstWarehouse  = $result[12];
				//$item_vat = $item_vat/100;
				$tax_flag = 0;
				$notax_flag = 1;
				if ($item_vat > 0){
					$tax_flag = 1;
					$notax_flag = 0;
				}	
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					if ($ItemUnit > 0) {
						$vItemUnitCoef = $ItemUnit;
						$vItemUnit2Qty = $vItemUnitCoef * $txtSorDtOQty;
					}
				
				
				}
				
				
				//Getting Item Price From Items Table Selling Price1
				/*if ($PSorCurr == $base1) { 
					$txtSorDtPrice = $result[10];
				}
				else if ($PSorCurr == $base2) {
					$txtSorDtPrice = $result[11];
				}
				else {
					$txtSorDtPrice = ConvertCurrency($ItemCurr, $PSorCurr, insertMySQLDate($PSorDate), $result[9], $connection);
				}	*/
				
				//If Item NonStock Is False And Stock Out Case Then Check On QtyExists For The Item
				if ($ItemNonStock == 0 && $Module_SorderCheckQtyOnPost == 1) {
					$sub_query  = " Select QtyExistsWSorder('".$txtItemCode."', '".$lstWarehouse."', '".insertMySQLDate($PSorDate)."', 0, 'SO', '', '') QtyExists From Dual ";
					$sub_result = selectData($connection, $sub_query);
					$vItemQtyExists = 0;
					$vItemQtyExists = $sub_result[0];
					
					$sub_query1 = " Select ifNull(Sum(ifNull(TransferDt_Quantity,0)),0) FROM Temp_TransferDt ".
								  " WHERE Item_code = '".$txtItemCode."'  And  TransferDt_WarehouseFrom = '".$lstWarehouse."' ";
					$sub_result1 = selectData($connection, $sub_query1);
					if (empty($sub_result1[0])) $sub_result1[0] = 0;
					
					$vItemQtyExists = $vItemQtyExists - $sub_result1[0];
					
						
					if (abs($txtSorDtQty) > $vItemQtyExists && abs($txtSorDtQty) > 0)
						$QtyExistExceeded = 1;
				}
				
				if ($QtyExistExceeded == 0 || ($Module_NegativeQuantity==1 && $Login_negativeQty==1)) {
					fbegin();
					$txtSorDtId = get_nextsequence('sorderdt_id','',$connection);	
					fcommit();

					
					//if item promotion the set price to zero
					if($ItemPromo == 1) $txtSorDtPrice = 0;
					
					if ($SalesTTC == 1) {
						$vSorDtPriceTTC      = $txtSorDtPrice;
						$vSorDtPriceTTCBase1 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt1;
						$vSorDtPriceTTCBase2 = ($vSorDtPriceTTC*$rate_dt)/$rate_dt2;	

						//Added 2011/10/27
						//if ($PSorVatChkbx == 1)	$vSorDtPrice = ($vSorDtPriceTTC / (1 + $item_vat/100));
						//else $vSorDtPrice = $txtSorDtPrice;					
					
						$vSorDtPrice      = ($vSorDtPriceTTC / (1 + $item_vat/100));
						$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
						$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
								
					} else	{
						$vSorDtPrice      = $txtSorDtPrice;
						$vSorDtPriceBase1 = ($vSorDtPrice*$rate_dt)/$rate_dt1;
						$vSorDtPriceBase2 = ($vSorDtPrice*$rate_dt)/$rate_dt2;
						
						$vSorDtPriceTTC      = 0;
						$vSorDtPriceTTCBase1 = 0;
						$vSorDtPriceTTCBase2 = 0;
								
					}	
						
					
					// Calculation For Detail Discount Amount
					$txtSorDtDiscount = 0;
					$vSorDtDiscAmt       = ((($vSorDtPrice*$txtSorDtQty) - ($vSorDtPrice*$txtSorDtQty*$txtSorDtDiscount/100))*$PSorDiscount)/100;
					$vSorDtDiscAmtBase1  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt1;
					$vSorDtDiscAmtBase2  = ($vSorDtDiscAmt*$rate_dt)/$rate_dt2;

					if ($Module_AdditionalTaxes == 1) {
						
						// Calculation of Item Tax Amounts
						$query = " SELECT ifNull(Client_Tax1,0), ifNull(Client_Tax2,0), ifNull(Client_Tax3,0), ifNull(Client_Tax4,0), ifNull(Client_Tax5,0) ".
								 " FROM Clients ".
								 " WHERE Ledger_number = '".$PSorClientCode."'";
												 
						$result = selectData($connection, $query);
						$vCltTax1 = $result[0];
						$vCltTax2 = $result[1];
						$vCltTax3 = $result[2];
						$vCltTax4 = $result[3];
						$vCltTax5 = $result[4];
										
						$query = " SELECT ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
								 " FROM Items ".
								 " WHERE Item_Code = '".$txtItemCode."'";
												 
						$result = selectData($connection, $query);

							
						if ($vCltTax1 != 0)	$vSorDtTax1 = $result[0];
						if ($vCltTax2 != 0)	$vSorDtTax2 = $result[1];
						if ($vCltTax3 != 0)	$vSorDtTax3 = $result[2];
						if ($vCltTax4 != 0)	$vSorDtTax4 = $result[3];
						if ($vCltTax5 != 0)	$vSorDtTax5 = $result[4];
								
					}
					
					
					// 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 = 'SI' ".
							 " 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 && $PSorVatChkbx == 1) {
							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 && $PSorVatChkbx == 1)
							$vSaDtItemAcc = $vSaStpCreditVatAcc;
						else
							$vSaDtItemAcc = $vSaStpCreditAcc;	
								
					}
					if($item_vat=='')		
						$item_vat = 0;
					
//echo $vItemUnit2Qty;
					
					fbegin();
					$query = " INSERT INTO temp_sorderdt (SorderDt_id, Sorder_id, Currency_Code, Sorder_Date, Client_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, SorderDt_Quantity, SorderDt_QuantityUsed, ".
							 " SorderDt_Price, SorderDt_PriceBase1, SroderDt_PriceBase2, SorderDt_Discount, SorderDt_DiscountAmount, SorderDt_DiscountBase1, SorderDt_DiscountBase2, Item_Vat, SorderDt_PriceTTC, SorderDt_Remark, ".
							 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Sorderdt_posted, Sorderdt_OldData, Item_UnitCoef, Item_Unit2Qty, SorderDt_oqty, SorderDt_cqty, SorderDt_cqtydate, SorderDt_cqtyuser, Sorderdt_promotion, Sorderdt_ItemAccount, Logged_Code ) ".
							 " VALUES ( ".$txtSorDtId.", ".$PSorId.", '".$PSorCurr."', '".insertMySQLDate($PSorDate)."', '".ereg_replace("\'", "''", trim($PSorClientCode))."',  ".
							 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$txtItemCode."', Null, $txtSorDtQty, 0, $vSorDtPrice, $vSorDtPriceBase1, $vSorDtPriceBase2, $txtSorDtDiscount, $vSorDtDiscAmt, $vSorDtDiscAmtBase1, $vSorDtDiscAmtBase2, $item_vat, ".
							 "          $vSorDtPriceTTC, '',  $vSorDtTax1, $vSorDtTax2, $vSorDtTax3, $vSorDtTax4, $vSorDtTax5, 0, 0, $vItemUnitCoef, $vItemUnit2Qty, $txtSorDtQty, 0, if(ifNull(0,0) > 0, now(), Null), ".
							 "          if(ifNull(0,0) > 0, '".$_SESSION['useraccount']."', Null), $ItemPromo, '".$vSaDtItemAcc."', '".$_SESSION['useraccount']."' ) ";
					 
				//	echo $query."<br>";				
					$result=mysql_query($query,$connection);
								
					if ($result){
						fcommit();
					}else{
						$txtSorDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error($connection); 
						frollback();
					}	
				} else {
					$txtSorDtId = "";
					$ErrorExists = 1;
					$message  = "Qty[".abs($txtSorDtQty)."] exceeds Existing Qty[$vItemQtyExists] for Item (".$txtItemCode.")"; 
				}	
				
				
			}	// End Case Not Pack Item
			
			
			if ($ErrorExists == 0) {
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SSorId, $PSorDate, $PSorVatChkbx, $PSorDiscount, 0, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $SalesTTC, 'I', $connection);
				$message  = $message . $CalculateResult;
			}
		
		}
	 $x++;  //end of looping in excell	
	} // End Case Insert In Detail Tables
	}

} 
//exit;
$message      = ereg_replace(' ','%20',$message);
$WarningMsg   = ereg_replace(' ','%20',$WarningMsg);
$PSorRemark   = ereg_replace(' ','%20',$PSorRemark);
$PSorIAddress = ereg_replace(' ','%20',$PSorIAddress);
$PSorDAddress = ereg_replace(' ','%20',$PSorDAddress);

$PSorRemark   = ereg_replace('#','%23',$PSorRemark);
$PSorIAddress = ereg_replace('#','%23',$PSorIAddress);
$PSorDAddress = ereg_replace('#','%23',$PSorDAddress);

$PSorRemark   = ereg_replace('&','%26',$PSorRemark);
$PSorIAddress = ereg_replace('&','%26',$PSorIAddress);
$PSorDAddress = ereg_replace('&','%26',$PSorDAddress);

//echo $mode.$message; exit;
//."&txtPurId=".$txtPurId
//if($mode == "post") 
	//header ("Location: ./Form_SalesOrder.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrSorId=".$SSorId);
if($mode == "post") {
	if ($ExceedCreditLimit == 0 && $SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_SalesOrder.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrSorId=".$SSorId);
	else
		header ("Location: ./Form_SalesOrder.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSorId=".$SSorId);
}	
else if($mode == "confirmorder") 
	header ("Location: ./Form_SalesOrder.php?actionmode=".$mode."&mainaction=".$mainmode."&flagconfirm=1&message=".$message."&PrSorId=".$SSorId);	
else if($mode == "" && ($mainmode == "confirmorder" || $mainmode == "unconfirmorder"))
	header ("Location: ./Form_SalesOrderSearch.php?message=".$message."&option=".$SOption);	
else if($mode == "" && ($mainmode == "duplicateSorder" || $mainmode == "cancelFromPreproduction") && $SSorId != '')
	header ("Location: ./Form_SalesOrderSearch.php?message=".$message);	
else if($mode == "" && $mainmode == "cancelorder")
	header ("Location: ./Form_SalesOrderSearch.php?message=".$message."&option=".$SOption);		
else if($mode == "" && $mainmode == "retrieveorder")
	header ("Location: ./Form_SalesOrderSearch.php?message=".$message."&option=".$SOption);
else if($mode == "" && $mainmode == "disapproveorder")
	header ("Location: ./Form_SalesOrderSearch.php?message=".$message."&option=".$SOption);
else if($mode == "" && $mainmode == "approveorder")
	header ("Location: ./Form_SalesOrderSearch.php?message=".$message."&option=".$SOption);
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_SalesOrderSearch.php?message=".$message."&option=".$SOption);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_SalesOrderSearchPending.php");
else if ($mode == "cancel" )		
	header ("Location: ./Form_SalesOrder.php?message=".$message);
else if ($mode == "import")	
	header ("Location: ./Form_SalesOrder.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSorId=".$SSorId);		
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_SalesOrder.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtSorId=".$SSorId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_SalesOrderDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PSorId=".$SSorId."&PSorDate=".$PSorDate."&PSorDtId=".$SSorDtId);		
else if ($mode == "" && $mainmode == "search" )	{	
	if ($AllowEdit == 1)
		header ("Location: ./Form_SalesOrderSearch.php?PMode=1");	
	else
		header ("Location: ./Form_SalesOrderSearch.php?PMode=0&message=".$message);	
	
}	
	//header ("Location: ./Form_SalesOrder.php?actionmode=&mainaction=edit&message=".$message."&txtSorId=".$SSorId);	
else if($mode == "submitrecord") {
    header ("Location: ./Form_SalesOrderDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&WarningMsg=".$WarningMsg."&PSorId=".$PSorId.	
			"&PSorDate=".$PSorDate."&PSorMaturityDate=".$PSorMaturityDate."&PSorRequestDate=".$PSorRequestDate."&PSorClientCode=".$PSorClientCode."&PSorSalesmanCode=".$PSorSalesmanCode.
			"&PSorCurr=".$PSorCurr."&PSorType=".$PSorType."&PSorProjectCode=".$PSorProjectCode."&PSorCostCentCode=".$PSorCostCentCode."&PSorDiscount=".$PSorDiscount."&PSorDiscountAmt=".$PSorDiscountAmt.
			"&PSorVatChkbx=".$PSorVatChkbx."&lstWarehouse=".$lstWarehouse."&PSorRemark=".$PSorRemark."&PDriverName=".$PDriverName."&PVehicalNo=".$PVehicalNo."&PVehicleWeight=".$PVehicleWeight.
			"&PPayMode=".$PPayMode."&PSorIAddress=".$PSorIAddress."&PSorDAddress=".$PSorDAddress	);
}else if ($mode == "" && $mainmode == "loadtransfer" )		
	header ("Location: ./Form_sorder_loadtransfer.php?PMode=1&GeneratedId=".$PSorId."&message=".$message);


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


function Calculate_MasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PTransportAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PModuleAdditionalTaxes, $PSalesTTC, $PMode, $connection) {

	$vSorDtTotal = 0;
	$vItemVat    = 0;
	
	$vSorTaxable 		 = 0;
	$vSorNoneTaxable 	 = 0;
	$vSorGrossTotal 	 = 0;
	$vSorDiscountAmt 	 = 0;
	$vSorDiscountPer 	 = 0;
	$vSorTransportAmt    = 0;
	$vSorTransportAmtB1  = 0;
	$vSorTransportAmtB2  = 0;
	$vSorTransportAmtTTC = 0;
	$vSorVat 	  = 0;
	$vSorVatBase1 = 0;
	$vSorVatBase2 = 0;
		
	$vSorTax1 = 0;
	$vSorTax2 = 0;
	$vSorTax3 = 0;
	$vSorTax4 = 0;
	$vSorTax5 = 0;
	$vSorTax1B1 = 0;
	$vSorTax2B1 = 0;
	$vSorTax3B1 = 0;
	$vSorTax4B1 = 0;
	$vSorTax5B1 = 0;
	$vSorTax1B2 = 0;
	$vSorTax2B2 = 0;
	$vSorTax3B2 = 0;
	$vSorTax4B2 = 0;
	$vSorTax5B2 = 0;

	$vSorDiscountPer = $PDiscPer;
	
	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(Sorder_VATChckbx, 0) From Temp_Sorder Where Sorder_ID = '".$PId."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$PVatChk    = $sub_result[0];
	
	}
	
	if ($PSalesTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE Temp_SorderDt SET  ".
				 " SorderDt_Price = SorderDt_PriceTTC, ".
				 " SorderDt_PriceBase1 = ((SorderDt_PriceTTC*$PRate)/$PRate1), ".
				 " SroderDt_PriceBase2 = ((SorderDt_PriceTTC*$PRate)/$PRate2) ".
				 " Where Sorder_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}
	else if ($PSalesTTC ==1 && $PVatChk == 1 && $PMode == 'P') {

		$query = " UPDATE Temp_SorderDt SET  ".
				 " SorderDt_Price      = (SorderDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " SorderDt_PriceBase1 = (((SorderDt_PriceTTC*$PRate)/$PRate1) / (1 + Item_Vat/100)), ".
				 " SroderDt_PriceBase2 = (((SorderDt_PriceTTC*$PRate)/$PRate2) / (1 + Item_Vat/100)) ".
				 " Where Sorder_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
	}
	
	
		
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_Price,0)*ifNull(SorderDt_Discount,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " SorderDt_Quantity, (ifNull(SorderDt_DiscountAmount,0) - ifNull(SorderDt_TransportAmount,0)), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0), ".
				 " ((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_PriceTTC,0))-((ifNull(SorderDt_Quantity,0)*ifNull(SorderDt_PriceTTC,0)*ifNull(SorderDt_Discount,0))/100)) As TotalTTC ".
				 " From Temp_SorderDt ".
				 " Where Sorder_ID = ".$PId;
										 
	//echo $sub_query; exit;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vSorDtTotal    = $sub_rows[1];
		$vItemVat       = $sub_rows[2];
		$vSorDtTotalTTC = $sub_rows[10];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0 && $PVatChk == 1){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
		//if ($PSalesTTC ==1 && $PVatChk == 0) {					
			//$vSorTaxable     = $vSorTaxable     + ($vSorDtTotalTTC*$tax_flag);
			//$vSorNoneTaxable = $vSorNoneTaxable + ($vSorDtTotalTTC*$notax_flag);
		//} else {
			$vSorTaxable     = $vSorTaxable     + ($vSorDtTotal*$tax_flag);
			$vSorNoneTaxable = $vSorNoneTaxable + ($vSorDtTotal*$notax_flag);
		//}
						
		
		// Calculation of Vat Amount
		if (((insertDate($PDate) > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vSorDtTotal > 0)
			$vSorVat = $vSorVat + (($vSorDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vSorDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vSorTax1 = $vSorTax1 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vSorTax2 = $vSorTax2 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vSorTax3 = $vSorTax3 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vSorTax4 = $vSorTax4 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vSorTax5 = $vSorTax5 + (($vSorDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vSorGrossTotal = $vSorTaxable + $vSorNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PMode == 'P') {
		$vSorDiscountAmt = $PDiscAmt;
	}
	else {
		if ($vSorDiscountPer > 0)
			$vSorDiscountAmt = (($vSorGrossTotal * $vSorDiscountPer) / 100);
	}	

	if ($PSalesTTC == 1) {
		$vSorTransportAmtTTC = $PTransportAmt;					
		$vSorTransportAmt    = ($vSorTransportAmtTTC / (1 + $PSetupVatPercentage/100));	
	} else {
		$vSorTransportAmt    = $PTransportAmt;
		$vSorTransportAmtTTC = 0;
	}
				
					
	$vSorNetTotal         = $vSorGrossTotal + $vSorVat - $vSorDiscountAmt;
	$vSorTaxableBase1     = ($vSorTaxable*$PRate)/$PRate1;
	$vSorTaxableBase2     = ($vSorTaxable*$PRate)/$PRate2;
	$vSorNoneTaxableBase1 = ($vSorNoneTaxable*$PRate)/$PRate1;
	$vSorNoneTaxableBase2 = ($vSorNoneTaxable*$PRate)/$PRate2;
	$vSorDiscountAmtBase1 = ($vSorDiscountAmt*$PRate)/$PRate1;
	$vSorDiscountAmtBase2 = ($vSorDiscountAmt*$PRate)/$PRate2;
	$vSorGrossTotalBase1  = ($vSorGrossTotal*$PRate)/$PRate1;
	$vSorGrossTotalBase2  = ($vSorGrossTotal*$PRate)/$PRate2;
	$vSorVatBase1 		  = ($vSorVat*$PRate)/$PRate1;
	$vSorVatBase2 		  = ($vSorVat*$PRate)/$PRate2;
	$vSorTransportAmtB1   = ($vSorTransportAmt*$PRate)/$PRate1;
	$vSorTransportAmtB2   = ($vSorTransportAmt*$PRate)/$PRate2;	
					

	$vSorTax1B1  = ($vSorTax1*$PRate)/$PRate1;
	$vSorTax1B2  = ($vSorTax1*$PRate)/$PRate2;		
	$vSorTax2B1  = ($vSorTax2*$PRate)/$PRate1;
	$vSorTax2B2  = ($vSorTax2*$PRate)/$PRate2;		
	$vSorTax3B1  = ($vSorTax3*$PRate)/$PRate1;
	$vSorTax3B2  = ($vSorTax3*$PRate)/$PRate2;		
	$vSorTax4B1  = ($vSorTax4*$PRate)/$PRate1;
	$vSorTax4B2  = ($vSorTax4*$PRate)/$PRate2;		
	$vSorTax5B1  = ($vSorTax5*$PRate)/$PRate1;
	$vSorTax5B2  = ($vSorTax5*$PRate)/$PRate2;	
	
	fbegin();
	
	$sub_query1 = " UPDATE temp_sorder SET ".
				  " Sorder_Taxable = $vSorTaxable, Sorder_TaxableBase1 = $vSorTaxableBase1, Sorder_TaxableBase2 = $vSorTaxableBase2, ".
				  " Sorder_NoneTaxable = $vSorNoneTaxable, Sorder_NoneTaxableBase1 = $vSorNoneTaxableBase1, Sorder_NoneTaxableBase2 = $vSorNoneTaxableBase2, ".
				  " Sorder_DiscountAmount = $vSorDiscountAmt, Sorder_DiscountBase1 = $vSorDiscountAmtBase1, Sorder_DiscountBase2 = $vSorDiscountAmtBase2, ".
				  " Sorder_DiscountPer = $vSorDiscountPer, Sorder_VAT = $vSorVat, Sorder_VATBase1 = $vSorVatBase1, Sorder_VATBase2 = $vSorVatBase2, ".
				  " Sorder_VATChckbx = $PVatChk, ".
				  " Sorder_tax1 = $vSorTax1, Sorder_tax1base1 = $vSorTax1B1, Sorder_tax1base2 = $vSorTax1B2,  ".
				  " Sorder_tax2 = $vSorTax2, Sorder_tax2base1 = $vSorTax2B1, Sorder_tax2base2 = $vSorTax2B2,  ".
				  " Sorder_tax3 = $vSorTax3, Sorder_tax3base1 = $vSorTax3B1, Sorder_tax3base2 = $vSorTax3B2,  ".
				  " Sorder_tax4 = $vSorTax4, Sorder_tax4base1 = $vSorTax4B1, Sorder_tax4base2 = $vSorTax4B2,  ".
				  " Sorder_tax5 = $vSorTax5, Sorder_tax5base1 = $vSorTax5B1, Sorder_tax5base2 = $vSorTax5B2  ";
				  
	//if ($PTransportAmt > 0)			  
		$sub_query1 = $sub_query1.", Sorder_TransportAmount = $vSorTransportAmt, Sorder_TransportBase1 = $vSorTransportAmtB1, Sorder_TransportBase2 = $vSorTransportAmtB2, Sorder_TransportTTC = $vSorTransportAmtTTC ";
		
	$sub_query1 = $sub_query1." WHERE Sorder_id = ".$PId ;
		
					 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}

function Distribute_TotalDiscount($PSorId, $PRate, $PRate1, $PRate2, $connection, $PLoggedCode) {
	
	
	$querytotal = " Select Sorder_ID, Sorder.Currency_code, (ifNull(Sorder_Taxable,0) + ifNull(Sorder_NoneTaxable,0)) As Sorder_Total, Sorder_DiscountAmount ".
				  " From Temp_Sorder As Sorder  ".
				  " Where Sorder_ID = ".$PSorId;
				  //" And Logged_Code = '".$PLoggedCode."' ";
		
	
	$resulttotal=mysql_query($querytotal,$connection) or die(mysql_error());
	$rowstotal=mysql_fetch_array($resulttotal);
	
	$vSorTotal   = $rowstotal[2];
	$vSorDisAmt  = $rowstotal[3];
	
	$query = " Select SorderDt_ID,  ".
             " ((SorderDt_Quantity*SorderDt_Price)-((SorderDt_Quantity*SorderDt_Price*ifNull(SorderDt_Discount,0))/100)) As Total ".
         	 " From Temp_SorderDt As SorderDt  ".
			 " Where SorderDt.Sorder_ID = ".$PSorId;
			 //" And SorderDt.Logged_Code = '".$PLoggedCode."' ";
			   
	//echo $query; 
	$result=mysql_query($query,$connection) or die(mysql_error());
	while($rows=mysql_fetch_array($result)){
	
		$vSorDtId    = $rows[0];
		$vSorDtTotal = $rows[1];
		
		$vSorDtDiscountAmt = 0;
		$vSorDtDiscountAmt      = ($vSorDtTotal/$vSorTotal)*$vSorDisAmt;
		$vSorDtDiscountAmtBase1 = ($vSorDtDiscountAmt*$PRate)/$PRate1;
		$vSorDtDiscountAmtBase2 = ($vSorDtDiscountAmt*$PRate)/$PRate2;
		
		$queryupd =  " UPDATE temp_sorderdt SET SorderDt_DiscountAmount = $vSorDtDiscountAmt, ".
					 " SorderDt_DiscountBase1 = $vSorDtDiscountAmtBase1, SorderDt_DiscountBase2 = $vSorDtDiscountAmtBase2  ".
					 " Where SorderDt_ID = ".$vSorDtId;
					 //" And Logged_Code = '".$PLoggedCode."' ";
		
		if (!updateData($connection, $queryupd, true))
			$error  = mysql_error(); 
		

	}
	
	if ($error != '')
	   $error = 'Error In Function Distribute_TotalDiscount: '.$error;
	   
	Return $error;
}

function Create_SalesOrderJv($PSaId, $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_SalesOrderAutoJv(".$PSaId.", 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_SalesOrderAutoJv: '.$error;
	else if  ($cur1[0] == -1)  
	   $error = 'Error In Procedure Create_Jv: '.$error;
	else if  ($error != '')  
		$error = 'Error In Function Create_SalesOrderJv: '.$error;

	Return $error;
	

}


function SubitemProduction($SSorId, $Project_FromItems, $connection){
	$query = "select SorderDt_id, sorderdt.item_code,Item_SubSequence
			from sorderdt
			inner join items on items.item_code = sorderdt.item_code
			where Sorder_id = $SSorId;";
	$result = mysql_query($query,$connection);
	while($row = mysql_fetch_row($result)){
		$AddedSeq = '';
		$SorderDt_id = $row[0];
		$item_code = $row[1];
		$Item_SubSequence = $row[2];

	if($Item_SubSequence != '')	{
		$queryseq = "select last_SubItemSeq from items where item_code = '$item_code';";
		$resseq = mysql_query($queryseq,$connection);
		$rwseq = mysql_fetch_row($resseq);
		$last_SubItemSeq = $rwseq[0]; //echo $last_SubItemSeq;echo "<br><br>";
		//if first sequence created
		if($last_SubItemSeq == ''){
			$seqs = str_split($Item_SubSequence,1);
			$seqlen = strlen($Item_SubSequence);
			$i=1;
			foreach($seqs as $seq){
				if($seq == '#' && $i != $seqlen) $addedseq = '0';
				else if($seq == '#' && $i == $seqlen) $addedseq = '1';
				else if($seq == '*') $addedseq = 'A';
				else if($seq == '-') $addedseq = '-';
				$AddedSeq=$AddedSeq.$addedseq;	
				$i++;
			}
		} else {
			$last_SubItemSeq = "&".$last_SubItemSeq;
			$last_SubItemSeq++;
			$seqs = explode('&',$last_SubItemSeq);
			$last_SubItemSeq = $seqs[1];
			$AddedSeq = $last_SubItemSeq;
		}  
		//insert new item into items
		$new_itemcode=$item_code.$AddedSeq;//echo $new_itemcode;echo "<br><br>";
		fbegin();
		$item_id = get_nextsequence('Item_Increment','',$connection);
		fcommit();
		$queryitem = " insert into items (Item_Code, Item_Description, Item_Barcode, Currency_code, CostCent_Code, Group_code, SubGroup_Code, Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, Category_code, Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, Item_Weight, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, item_id, BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, Item_NetWeight, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist, item_picture2 ) ".
					 " select '$new_itemcode', concat(Item_Description,'','$AddedSeq'), Item_Barcode, Currency_code, CostCent_Code, Group_code, SubGroup_Code, Item_Remark, ITEM_MAXQTY, ITEM_MINQTY, Item_UnitPurchaseDesc, Item_Unit, Item_UnitSalesDesc, Item_SellingPrice1, Item_SellingPrice1Base1, Item_SellingPrice1Base2, Item_SellingPrice2, Item_SellingPrice2Base1, Item_SellingPrice2Base2, Item_SellingPrice3, Item_SellingPrice3Base1, Item_SellingPrice3Base2, Item_SellingPrice4, Item_SellingPrice4Base1, Item_SellingPrice4Base2, Item_SellingPrice5, Item_SellingPrice5Base1, Item_SellingPrice5Base2, Category_code, Item_QuantityInitiate, Item_ValueInitiate, Item_ValueInitiateBase1, Item_ValueInitiateBase2, Item_QuantityPurchase, Item_ValuePurchase, Item_ValuePurchaseBase1, Item_ValuePurchaseBase2, Item_QuantityProdIn, Item_ValueProdIn, Item_ValueProdInBase1, Item_ValueProdInBase2, Item_QuantityDelivered, Item_QuantitySales, Item_ValueSales, Item_ValueSalesBase1, Item_ValueSalesBase2, Item_QuantityProdOUT, Item_ValueProdOut, Item_ValueProdOutBase1, Item_ValueProdOutBase2, Item_Picture, Item_Production, Item_LastDatePurchase, Item_LastPricePurchase, Ledger_Number, Item_NonStock, item_Transfer, Item_Pack, Expire_Date, Item_Weight, Item_posted, item_printed, Item_Package, Item_Vat, Size_Code, Item_Barcode2, Item_Barcode3, Item_Category, item_active, item_lastfobprice, Item_RMAQty, Item_PorderQty, Item_QtyTransferedToRMA, Itemselling1TTcBase1, ItemSelling2TTCBase2, ItemSelling3TTCBase2, ItemSelling4TTCBase1, item_TargetDays, Item_SellingPrice6, Item_SellingPrice6Base1, Item_SellingPrice6Base2, Item_TTCInclude, SendReceive_Reference, item_BelongsToGroup, Item_tax, ItemSelling2TTCBase1, ItemSelling3TTCBase1, ItemSelling1TTCBase2, ItemSelling4TTCBase2, Item_SemiFinished, Item_CostMethod, Item_FixedAsset, Item_tax1, Item_tax2, Item_tax3, Item_tax4, Item_tax5, Item_Assetseq, Itemjour_ledger, Synchronized, item_discountpercent, Item_QtyToBeProduced, item_grammage, Item_ReverseProduction, Item_SysDateTime, Project_Code, EvaluateQtyUnit, item_inactivedate, item_longdescription, item_lastcostprice, item_lastcostpricebase1, item_lastcostpricebase2, item_ratio, item_promotion, item_withserialno, item_specialproduction, item_height, item_length, item_width, items_type, item_policy, Item_Visible, item_discount, Item_ModifySellingPrice, Item_Volume, Item_Color, Item_Size, item_zeroPrice, '$item_id', BRANCH_CODE, Item_MinimumPrice, Item_Expire, item_fixedCost, Owner_Branch, Item_WarehouseCode, Item_RebateBy, item_descriptionf1, item_descriptionf2, Item_NetWeight, Item_unknownStock, Item_DispOrder, item_vattype, item_discountper, item_codeexport, item_descriptionexporten, item_descriptionexportar, item_descriptionexportfr, item_location, item_reducer, item_retarder, item_Shade, item_Strength, item_Packing, item_ViscosityDirect, item_ViscosityReduced, item_gloss, item_Adhesion, item_Alkali, item_scuff, Manufacture_code, item_pricelist, item_picture2 ".
					 " from items ".
					 " where item_code = '$item_code';"; 
		$resitem = mysql_query($queryitem,$connection);
		//add item parameters
		$queryparam = "	insert into itemsdt (Item_Code, ItemParam_Code, itemdt_value)
						select '".$new_itemcode."',ItemParam_Code, itemdt_value
						from temp_itemsdt
						where Item_Code = '".$item_code."' and transid = $SorderDt_id ";
		$resparam = mysql_query($queryparam,$connection);		
		
		$querypic = "select item_picture, item_picture2 from temp_items where item_code='$item_code' and trans_id = $SorderDt_id;";//echo $querypic;echo "<br><br>"; 
		$respic = mysql_query($querypic, $connection);
		$rowpic = mysql_fetch_row($respic);
		$item_picture = $rowpic[0];
		$item_picture2 = $rowpic[1];
		if($item_picture != ''){
			$querydel = "delete from temp_items where Item_Code = '".$item_code."' and trans_id = $SorderDt_id ";
			$resdel = mysql_query($querydel,$connection);
			$item_picture = "'".$item_picture."'";
		} else $item_picture = "NULL";
		
		if($item_picture2 != ''){
			$querydel = "delete from temp_items where Item_Code = '".$item_code."' and trans_id = $SorderDt_id ";
			$resdel = mysql_query($querydel,$connection);
			$item_picture2 = "'".$item_picture2."'";
		} else $item_picture2 = "NULL";
		
		$updatenitem = "update items set item_picture = $item_picture, item_picture2 = $item_picture2 where item_code = '$new_itemcode';"; //echo $updatenitem;echo "<br><br>"; 
		$resnitem = mysql_query($updatenitem,$connection);
		
		$updateitem = "update items set last_SubItemSeq = '$AddedSeq' where item_code = '$item_code';"; //echo $updateitem;echo "<br><br>"; 
		$resitem = mysql_query($updateitem,$connection);
		//update sorderdt with new item
		$updatedt = "update sorderdt set item_code='$new_itemcode' where sorderdt_id=$SorderDt_id;";
		$resdt = mysql_query($updatedt,$connection);
		
		$querydel = "delete from temp_itemsdt where Item_Code = '".$item_code."' and transid = $SorderDt_id ";
		$resdel = mysql_query($querydel,$connection);
		
		if($Project_FromItems == 1){	
		$maxproj = "select ifnull(max(project_id),0)+1 from project";
		$resmax = mysql_query($maxproj,$connection);
		$rwmax = mysql_fetch_row($resmax);
		$project_id = $rwmax[0];
		
		$queryChk = "select 1 from project where Project_Code = '$new_itemcode'";
		$resChk = mysql_query($queryChk, $connection);
		$nmChk = mysql_num_rows($resChk);
		
		if ($nmChk == 0){
			$query_project = "insert into project (Project_Code, Project_Name, Project_Deactivate, Project_date, Project_BelongsToGroup, Synchronized,Project_posted, project_id)
							select  item_code, Item_Description, 0,now(),0,0,0,$project_id
							from items where item_code = '$new_itemcode' limit 1;"; //echo $query_project;exit;
			$resproj = mysql_query($query_project, $connection);
		}
		$updatedt = "update sorderdt set Project_code = '$new_itemcode' where sorderdt_id=$SorderDt_id;";
		$resdt = mysql_query($updatedt,$connection);
		
	}
	}
}
	
}
/*
print <<<HERE
</form>
</body>

HERE;*/
$return_arr = array();

$row_array['message'] = $message;
$row_array['transid'] = $SSorId;
		
array_push($return_arr,$row_array);
echo json_encode($return_arr);


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

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