<?php

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

include("config.inc.php");
include("Functions_Purchase.php");
set_time_limit(0);

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

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

$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($config['log_file'] == 1){
$connection_history = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
mysql_select_db($config['dbName_history'],$connection_history) or die("Could not find DB");
}



$query_user = "select User_Name from ".$_SESSION['dbLabel'].".users where User_account = '".$_SESSION['useraccount']."'";
$result_user = mysql_query($query_user, $connection);
$rows_user = mysql_fetch_array($result_user);
extract($rows_user); 

$Login_PorderLimit 	= $_GET["Login_PorderLimit"]; if ($Login_PorderLimit == ""){$Login_PorderLimit = $_POST["Login_PorderLimit"];}
$PPorStatus 		= $_GET["PPorStatus"]; if ($PPorStatus == ""){$PPorStatus = $_POST["PPorStatus"];}
$txtporcost 		= $_GET["txtporcost"]; if ($txtporcost == ""){$txtporcost = $_POST["txtporcost"];}
$txtporfreight 		= $_GET["txtporfreight"]; if ($txtporfreight == ""){$txtporfreight = $_POST["txtporfreight"];}
$shippingmethod 	= $_GET["shippingmethod"]; if ($shippingmethod == ""){$shippingmethod = $_POST["shippingmethod"];}
$approvedby 		= $_GET["approvedby"]; if ($approvedby == ""){$approvedby = $_POST["approvedby"];}
$WarningMsg 		= $_GET["WarningMsg"]; if ($WarningMsg == ""){$WarningMsg = $_POST["WarningMsg"];}

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}

if($_POST['porder_actualdate'] == "")
{
	//echo $_POST['txtDate']."test";exit;
    $_POST['porder_actualdate'] = $_POST['txtDate'];
}
$querylog="select ifNull(login_belongstogrp,0) As FI_BelongsToGrp   ,ifnull(PorderApproved_Level,0) As approved  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);
}

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

//Read From Setup Table
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ".
             " Date_Format(Setup_VatStartDate,'%Y%m%d') As Setup_VatStartDate, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage 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_NegativeQuantity,0) As Module_NegativeQuantity, ".
             " ifNull(Module_rawmaterial,0) As Module_RawMaterial, ifNull(Module_PorderConfirm,0) As Module_PorderConfirm, ".
			 " 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_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ifNull(Module_Grn,0) As Module_Grn,  ".
			 " ifNull(Module_Limit,0) As Module_Limit, ifNull(Module_PorderAutoApprove,0) Module_PorderAutoApprove, ".
			 " ifNull(Module_LimitProject,0) As Module_LimitProject,ifNull(module_purchasezero,0) Module_PurchaseZero   ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}


//Read From PurchaseSetup Table
$queryPurchaseSetup="Select PurchaseTTC From PurchaseSetup";
$resultPurchaseSetup=mysql_query($queryPurchaseSetup,$connection) or die(mysql_error());
while($rowPurchaseSetup=mysql_fetch_array($resultPurchaseSetup)){
	extract($rowPurchaseSetup);
}


$mode 		= $_GET["mode"]; if ($mode == ""){$mode = $_POST["mode"];}   
   
$mainmode   = $_GET["mainmode"]; if ($mainmode == ""){$mainmode = $_POST["mainmode"];}   
$actionmode   = $_GET["actionmode"]; if ($actionmode == ""){$actionmode = $_POST["actionmode"];}   
//echo $mode; echo $actionmode;echo $mainmode; exit;
$SPorId    			= $_GET["SPorId"]; if ($SPorId == ""){$SPorId = $_POST["SPorId"];} 
$SPorDtId			= $_GET["SPorDtId"]; if ($SPorDtId == ""){$SPorDtId = $_POST["SPorDtId"];} 
$SPorVatChkbx 		= $_GET["SPorVatChkbx"]; if ($SPorVatChkbx == ""){$SPorVatChkbx = $_POST["SPorVatChkbx"];} 

$txtPorId    		= $_GET["txtPorId"]; if ($txtPorId == ""){$txtPorId = $_POST["txtPorId"];} 
$txtDate 			= $_GET["txtDate"]; if ($txtDate == ""){$txtDate = $_POST["txtDate"];} 
$txtRequestDate 	= $_GET["txtRequestDate"]; if ($txtRequestDate == ""){$txtRequestDate = $_POST["txtRequestDate"];} 
$txtExpiryDate    	= $_GET["txtExpiryDate"]; if ($txtExpiryDate == ""){$txtExpiryDate = $_POST["txtExpiryDate"];} 
$txtSupplier 	   	= $_GET["txtSupplier"]; if ($txtSupplier == ""){$txtSupplier = $_POST["txtSupplier"];} 
$txtSupplier1 	   	= $_GET["txtSupplier1"]; if ($txtSupplier1 == ""){$txtSupplier1 = $_POST["txtSupplier1"];} 
$txtRequestBy 	   	= $_GET["txtRequestBy"]; if ($txtRequestBy == ""){$txtRequestBy = $_POST["txtRequestBy"];} 
$txtCurr   			= $_GET["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_POST["txtCurr"];} 
$txtSupplierContact	= $_GET["txtSupplierContact"]; if ($txtSupplierContact == ""){$txtSupplierContact = $_POST["txtSupplierContact"];} 
$txtPorCategory   	= $_GET["txtPorCategory"]; if ($txtPorCategory == ""){$txtPorCategory = $_POST["txtPorCategory"];} 
$txtPorStatus   	= $_GET["txtPorStatus"]; if ($txtPorStatus == ""){$txtPorStatus = $_POST["txtPorStatus"];} 
$txtRemark  		= $_GET["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_POST["txtRemark"];} 
$txtPrequestReference	= $_GET["txtPrequestReference"]; if ($txtPrequestReference == ""){$txtPrequestReference = $_POST["txtPrequestReference"];} 
$txtProjectCode 	= $_GET["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_POST["txtProjectCode"];} 
$txtCostCentCode	= $_GET["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_POST["txtCostCentCode"];} 
$txtStatusRemark	= $_GET["txtStatusRemark"]; if ($txtStatusRemark == ""){$txtStatusRemark = $_POST["txtStatusRemark"];} 
$txtDeliveryPlace	= $_GET["txtDeliveryPlace"]; if ($txtDeliveryPlace == ""){$txtDeliveryPlace = $_POST["txtDeliveryPlace"];} 
$txtDeliveryContact	= $_GET["txtDeliveryContact"]; if ($txtDeliveryContact == ""){$txtDeliveryContact = $_POST["txtDeliveryContact"];} 
$txtPorDiscountAmt	= $_GET["txtPorDiscountAmt"]; if ($txtPorDiscountAmt == ""){$txtPorDiscountAmt = $_POST["txtPorDiscountAmt"];} 
$txtPorDiscount		= $_GET["txtPorDiscount"]; if ($txtPorDiscount == ""){$txtPorDiscount = $_POST["txtPorDiscount"];} 
$txtPorder_Othercharges = $_GET["txtPorder_Othercharges"]; if ($txtPorder_Othercharges == ""){$txtPorder_Othercharges = $_POST["txtPorder_Othercharges"];} 
if($txtPorder_Othercharges == '') $txtPorder_Othercharges = 0;

$PPorId    			= $_GET["PPorId"]; if ($PPorId == ""){$PPorId = $_POST["PPorId"];} 
$PPorDate 			= $_GET["PPorDate"]; if ($PPorDate == ""){$PPorDate = $_POST["PPorDate"];} 
$PPorRequestDate 	= $_GET["PPorRequestDate"]; if ($PPorRequestDate == ""){$PPorRequestDate = $_POST["PPorRequestDate"];} 
$PPorExpiryDate    	= $_GET["PPorExpiryDate"]; if ($PPorExpiryDate == ""){$PPorExpiryDate = $_POST["PPorExpiryDate"];} 
$PPorSupplier 	   	= $_GET["PPorSupplier"]; if ($PPorSupplier == ""){$PPorSupplier = $_POST["PPorSupplier"];} 
$PPorSupplier1 	   	= $_GET["PPorSupplier1"]; if ($PPorSupplier1 == ""){$PPorSupplier1 = $_POST["PPorSupplier1"];} 
$PPorRequestBy 	   	= $_GET["PPorRequestBy"]; if ($PPorRequestBy == ""){$PPorRequestBy = $_POST["PPorRequestBy"];} 
$PPorCurr   		= $_GET["PPorCurr"]; if ($PPorCurr == ""){$PPorCurr = $_POST["PPorCurr"];} 
$PPorSupplierContact= $_GET["PPorSupplierContact"]; if ($PPorSupplierContact == ""){$PPorSupplierContact = $_POST["PPorSupplierContact"];} 
$PPorCategory   	= $_GET["PPorCategory"]; if ($PPorCategory == ""){$PPorCategory = $_POST["PPorCategory"];} 
$PPorRemark  		= $_GET["PPorRemark"]; if ($PPorRemark == ""){$PPorRemark = $_POST["PPorRemark"];} 
$PPorProjectCode 		= $_GET["PPorProjectCode"]; if ($PPorProjectCode == ""){$PPorProjectCode = $_POST["PPorProjectCode"];} 
$PPorCostCentCode		= $_GET["PPorCostCentCode"]; if ($PPorCostCentCode == ""){$PPorCostCentCode = $_POST["PPorCostCentCode"];} 
$PPorStatusRemark		= $_GET["PPorStatusRemark"]; if ($PPorStatusRemark == ""){$PPorStatusRemark = $_POST["PPorStatusRemark"];} 
$PPorDeliveryPlace		= $_GET["PPorDeliveryPlace"]; if ($PPorDeliveryPlace == ""){$PPorDeliveryPlace = $_POST["PPorDeliveryPlace"];} 
$PPorDeliveryContact	= $_GET["PPorDeliveryContact"]; if ($PPorDeliveryContact == ""){$PPorDeliveryContact = $_POST["PPorDeliveryContact"];} 

$PPorDiscount 		= $_GET["PPorDiscount"]; if ($PPorDiscount == ""){$PPorDiscount = $_POST["PPorDiscount"];} 
$PPorDiscountAmt	= $_GET["PPorDiscountAmt"]; if ($PPorDiscountAmt == ""){$PPorDiscountAmt = $_POST["PPorDiscountAmt"];} 
$PPorVatChkbx 		= $_GET["PPorVatChkbx"]; if ($PPorVatChkbx == ""){$PPorVatChkbx = $_POST["PPorVatChkbx"];} 

$txtPrqstid = $_GET["txtPrqstid"]; if ($txtPrqstid == ""){$txtPrqstid = $_POST["txtPrqstid"];} 
$PurReqId 	= $_GET["PurReqId"]; if ($PurReqId == ""){$PurReqId = $_POST["PurReqId"];} 
$SSaDtId 	= $_GET["SSaDtId"]; if ($SSaDtId == ""){$SSaDtId = $_POST["SSaDtId"];} 
$PordId 	= $_GET["PordId"]; if ($PordId == ""){$PordId = $_POST["PordId"];} 
$suppcode 	= $_GET["suppcode"]; if ($suppcode == ""){$suppcode = $_POST["suppcode"];} 

$lstWarehouse	= $_GET["lstWarehouse"]; if ($lstWarehouse == ""){$lstWarehouse = $_POST["lstWarehouse"];} 
$txtItemCode	= $_GET["txtItemCode"]; if ($txtItemCode == ""){$txtItemCode = $_POST["txtItemCode"];} 
$txtPorDtRemark	= $_GET["txtPorDtRemark"]; if ($txtPorDtRemark == ""){$txtPorDtRemark = $_POST["txtPorDtRemark"];} 
$txtPorDtQty	= $_GET["txtPorDtQty"]; if ($txtPorDtQty == ""){$txtPorDtQty = $_POST["txtPorDtQty"];} 
$txtPorDtQty2	= $_GET["txtPorDtQty2"]; if ($txtPorDtQty2 == ""){$txtPorDtQty2 = $_POST["txtPorDtQty2"];} 
$txtPorDtPrice	= $_GET["txtPorDtPrice"]; if ($txtPorDtPrice == ""){$txtPorDtPrice = $_POST["txtPorDtPrice"];} 
$txtPorDtDiscount	= $_GET["txtPorDtDiscount"]; if ($txtPorDtDiscount == ""){$txtPorDtDiscount = $_POST["txtPorDtDiscount"];} 
$txtProjectCodeDt	= $_GET["txtProjectCodeDt"]; if ($txtProjectCodeDt == ""){$txtProjectCodeDt = $_POST["txtProjectCodeDt"];} 
$txtCostCentCodeDt	= $_GET["txtCostCentCodeDt"]; if ($txtCostCentCodeDt == ""){$txtCostCentCodeDt = $_POST["txtCostCentCodeDt"];} 

$txtPaymentCondidions	= $_POST["txtPaymentCondidions"]; if ($txtPaymentCondidions == ""){$txtPaymentCondidions = $_GET["txtPaymentCondidions"];} 
$porder_downpayment	= $_POST["porder_downpayment"]; if ($porder_downpayment == ""){$porder_downpayment = $_GET["porder_downpayment"];} 
$porder_downperc	= $_POST["porder_downperc"]; if ($porder_downperc == ""){$porder_downperc = $_GET["porder_downperc"];} 
$porder_downamount	= $_POST["porder_downamount"]; if ($porder_downamount == ""){$porder_downamount = $_GET["porder_downamount"];} 
$porderdt_heatno	= $_POST["porderdt_heatno"]; if ($porderdt_heatno == ""){$porderdt_heatno = $_GET["porderdt_heatno"];} 

/*

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='insertpurchase' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SPorId' value='$SPorId'>
<input type='text' name='SPorDtId' value='$SPorDtId'>
<input type='text' name='SPorVatChkbx' value='$SPorVatChkbx'>

HERE;
*/

$message='';

//Submit Record Mode

//echo"test";
if ($actionmode=='getItemInfo' ){
	$queryinfo = "select Item_WarehouseCode from items where item_code='".trim(strtoupper($item_code))."'";
	//exit;
	$resinfo = mysql_query($queryinfo, $connection);
	$rwinfo = mysql_fetch_row($resinfo);
	
	echo "[BRK]";
	echo $rwinfo[0];
	echo "[BRK]";
	exit;
}
if ($actionmode=='getItemImage' ){
	$queryinfoImg = "select Item_Picture,ifnull(Item_SellingPrice1Base1,0) from items where item_code='".trim(strtoupper($item_code))."'";
	$resinfoImg = mysql_query($queryinfoImg, $connection);
	$rwinfoImg = mysql_fetch_row($resinfoImg);
	
	echo "[BRK]";
	echo $rwinfoImg[0];
	echo "[BRK]"; 
	echo $rwinfoImg[1];
	exit;
}
if ($actionmode=='getItemLocation' ){
	$queryinfoImg = "select CONCAT(item_location.description1, ' - ',item_location.description2, ' - ',item_location.description3) from item_location where  item_code='".trim(strtoupper($item_code))."'";
	$resinfoImg = mysql_query($queryinfoImg, $connection);
	$rwinfoImg = mysql_fetch_row($resinfoImg);
	$queryinfoselprice = "select Item_Picture,ifnull(Item_SellingPrice1Base1,0) from items where item_code='".trim(strtoupper($item_code))."'";
	$resselprice = mysql_query($queryinfoselprice, $connection);
	$rwselprice = mysql_fetch_row($resselprice);
	
	$queryitemQtyExists = "select qtyexists('".trim(strtoupper($item_code))."','',now(),0,'','','') ;";
	$resQtyExists = mysql_query($queryitemQtyExists, $connection);
	$rwQtyExists = mysql_fetch_row($resQtyExists);

	echo "[BRK]";
	echo $rwinfoImg[0];
	echo "[BRK]";
	echo $rwselprice[1];
	echo "[BRK]";
	echo $rwQtyExists[0];
	exit;
}

if ($actionmode=='updateitemstatus' || $actionmode=='updateitemgrn'){

	$PRqstid = $_GET["PRqstid"];
	$PRqstDtid = $_GET["PRqstDtid"];
	$objval = $_GET["objval"];
	$amount = $_GET["amount"];

	if ($_GET["approved"]!='')
		$approved = $_GET["approved"];
		
	if ($_GET["vreason"]!='')
		$vreason = $_GET["vreason"];

	echo "[BRK]";

	if (strtoupper($objval)=='A')
		$userupdate = $_SESSION['username'];
	
	
	if ($actionmode=='updateitemstatus') {
		if($PRqstid!=''){
			$query = " UPDATE porder SET rejectedreason = '$vreason' where porder_id = $PRqstid";
			if (!updateData($connection, $query, true)) 
				$message  = mysql_error();
			else   if ( $config['log_file'] == 1){
				$query_history=" INSERT INTO porder (porder_id, rejectedreason, porder_history_date, porder_history_operator_id, porder_history_schema, porder_history_status) ".
				 " VALUES ( ".$PRqstid.", '$vreason',			 
					,now()
					, '".$User_Name."'
					, '".$_SESSION['dbName']."'
					, 'U')";
					if (!updateData($connection_history, $query_history, true))		 
					$message  = mysql_error($query_history);
			}
		}
		
		if ($objval == 'a' && $Module_Limit == 1 && $amount < $Login_PorderLimit) {
			$approved = 1;
		}
		
		if ($objval == 'a' && $Module_LimitProject == 1 ) {
			$query = "SELECT projectlimit_limit from projectlimit where user_account = '".$_SESSION['useraccount']."' and project_code = '".$porderproject_code."'";
			$result = selectData($connection, $query);
			$projectlimit_limit = $result[0];
			if($amount < $projectlimit_limit)
			$approved = 1;
		}
		
		if($PRqstid!='') {
			if ($objval == 'p') {
				$query = " UPDATE porder SET  porder_approvedstatus = null,porder_approvedlevel = '$approved' ,approvedby = '".$userupdate."',user_name = concat(ifnull(user_name,''),if(user_name='','".$_SESSION['username']."',concat(',','".$_SESSION['username']."')) )
						 ,rejectedreason = null, Approval_date = null WHERE porder_id = $PRqstid ";
				if (!updateData($connection, $query, true)) $message  = mysql_error();		


			if ( $config['log_file'] == 1){
				$query_history=" INSERT INTO porder (porder_approvedstatus,porder_approvedlevel,approvedby,user_name, rejectedreason,Approval_date,porder_id, porder_history_date, porder_history_operator_id, porder_history_schema, porder_history_status) ".
				 " VALUES ( null,'$approved', '".$userupdate."',concat(ifnull(user_name,''),if(user_name='','".$_SESSION['username']."',concat(',','".$_SESSION['username']."')) ),null,null,$PRqstid		 
					,now()
					, '".$User_Name."'
					, '".$_SESSION['dbName']."'
					, 'U')";
					if (!updateData($connection_history, $query_history, true))		 
					$message  = mysql_error($query_history);
			}
				
				
				$query = " UPDATE porderdt SET  porderdt_approvedstatus = null, porderdt_approvedlevel = '$approved', Approval_date = null 
						   WHERE porder_id = $PRqstid ";
				if (!updateData($connection, $query, true)) $message  = mysql_error();	
				
				else 	 if ( $config['log_file'] == 1){
				$query_history=" INSERT INTO porderdt (porderdt_approvedstatus,porderdt_approvedlevel,Approval_date,porder_id, porderdt_history_date, porderdt_history_operator_id, porderdt_history_schema, porderdt_history_status) ".
				 " VALUES ( null,'$approved',null,$PRqstid,now()
					, '".$User_Name."'
					, '".$_SESSION['dbName']."'
					, 'U')";
					if (!updateData($connection_history, $query_history, true))		 
					$message  = mysql_error($query_history);
			}	
			} else {
				
				$query = " UPDATE porder SET  porder_approvedstatus = '$objval',porder_approvedlevel = '$approved' ,approvedby = '".$userupdate."',user_name = concat(ifnull(user_name,''),if(user_name='','".$_SESSION['username']."',concat(',','".$_SESSION['username']."')) )
					 ,rejectedreason = '$vreason', Approval_date = if('$objval' ='r',null,now())    WHERE porder_id = $PRqstid ";
				if (!updateData($connection, $query, true)) $message  = mysql_error();		 
			
			else if ( $config['log_file'] == 1){
				$query_history=" INSERT INTO porder (porder_approvedstatus,porder_approvedlevel,approvedby,user_name, rejectedreason,Approval_date,porder_id, porder_history_date, porder_history_operator_id, porder_history_schema, porder_history_status) ".
				 " VALUES ( '$objval','$approved', '".$userupdate."',concat(ifnull(user_name,''),if(user_name='','".$_SESSION['username']."',concat(',','".$_SESSION['username']."')) ),'$vreason', if('$objval' ='r',null,now()),$PRqstid		 
					,now()
					, '".$User_Name."'
					, '".$_SESSION['dbName']."'
					, 'U')";
					if (!updateData($connection_history, $query_history, true))		 
					$message  = mysql_error($query_history);
			}
				
				$query = " UPDATE porderdt SET  porderdt_approvedstatus = '$objval', porderdt_approvedlevel = '$approved', 
							Approval_date = if('$objval' ='r',null,now())   
						   WHERE porder_id = $PRqstid ";
				if (!updateData($connection, $query, true)) $message  = mysql_error();	
				
				else 	 if ( $config['log_file'] == 1){
				$query_history=" INSERT INTO porderdt (porderdt_approvedstatus,porderdt_approvedlevel,Approval_date,porder_id, porderdt_history_date, porderdt_history_operator_id, porderdt_history_schema, porderdt_history_status) ".
				 " VALUES ( '$objval','$approved',if('$objval' ='r',null,now()) ,$PRqstid,now()
					, '".$User_Name."'
					, '".$_SESSION['dbName']."'
					, 'U')";
					
					if (!updateData($connection_history, $query_history, true))		 
					$message  = mysql_error($query_history);
			}
			}		 
		}
		else {
			if ($objval == 'p') {
				$query = " UPDATE porderdt SET  porderdt_approvedstatus = null, porderdt_approvedlevel = '$approved',Approval_date = null 
						   WHERE porderdt_id = $PRqstDtid ";
						   if ( $config['log_file'] == 1){
							$query_history=" INSERT INTO porderdt (porderdt_approvedstatus,porderdt_approvedlevel,Approval_date,porderdt_id, porderdt_history_date, porderdt_history_operator_id, porderdt_history_schema, porderdt_history_status) ".
							 " VALUES ( null,'$approved',null ,$PRqstDtid
								,now()
								, '".$User_Name."'
								, '".$_SESSION['dbName']."'
								, 'U')";
					
							}
			} else {
				$query = " UPDATE porderdt SET  porderdt_approvedstatus = '$objval', porderdt_approvedlevel = '$approved', 
							Approval_date = if('$objval' ='r',null,now())   
						   WHERE porderdt_id = $PRqstDtid ";
					   
					    if ( $config['log_file'] == 1){
							$query_history=" INSERT INTO porderdt (porderdt_approvedstatus,porderdt_approvedlevel,Approval_date,porderdt_id, porderdt_history_date, porderdt_history_operator_id, porderdt_history_schema, porderdt_history_status) ".
							 " VALUES ( '$objval','$approved',if('$objval' ='r',null,now()) ,$PRqstDtid
								,now()
								, '".$User_Name."'
								, '".$_SESSION['dbName']."'
								, 'U')";
					
							}
			}
			
			if (!updateData($connection, $query, true)) 
				$message  = mysql_error();
			else   if ( $config['log_file'] == 1){
				if(!updateData($connection_history, $query_history, true))		 
					$message  = mysql_error($query_history);
			}
		}
		
		//echo $query;exit;
		
		$emails = '';
		$queryEmails = "select email_address from ".$_SESSION['dbLabel'].".users_emails where user_account = '".$_SESSION['useraccount']."';";
		$resEmails = mysql_query($queryEmails, $connection);
		while ($rw = mysql_fetch_row($resEmails)){
			$emails = $rw[0].";".$emails;
			
		}
		
	if($emails != ''){
		if($PRqstid == ''){
			$q = "select Porder_id from porderdt where PorderDt_id = $PRqstDtid;";
			$res = mysql_query($q,$connection);
			$rw = mysql_fetch_row($res);
			$PRqstid = $rw[0];
		}
		$querybody = "select Porder_reference,Porder_date from porder where Porder_id = $PRqstid";
		$resbody = mysql_query($querybody,$connection);
		$rowbody = mysql_fetch_row($resbody);
	
		$Subject="Purchase Order ".$rowbody[0]." Status ";
		
		$Body="<table><tr><td>Date : ".$rowbody[1]."</td></tr>\n";
		$Body=$Body."<tr><td>Purchase Order with Ref ".$rowbody[0]." is ";
		if($objval == 'p') $Body=$Body." Pending ";
		else if($objval == 'r') $Body=$Body." Rejected ";
		else if($objval == 'a') $Body=$Body." Approved ";
		$Body=$Body."</td></tr>\n";
		$Body=$Body."<tr><td>For The Following Item(s) : <td></tr> \n ";
		
		$queryitem = "select porderdt.item_code, items.item_description from porderdt
						inner join items on items.item_code = porderdt.item_code ";
		if($PRqstDtid != '' )
			$queryitem .= " where PorderDt_id = $PRqstDtid ";
		else $queryitem .= " where Porder_id = $PRqstid ";
		
		$resItem = mysql_query($queryitem,$connection);
		while ($rwItem = mysql_fetch_row($resItem)){
			$Body=$Body."<tr><td> $rwItem[0] - $rwItem[1]  <td></tr> \n ";
		}		
		$Body=$Body." </table> \n";

		$mail=sendmail($Subject,$Body,$emails,$SPreqId,$connection);	
	}
	}	
	else if ($actionmode=='updateitemgrn') {
		$query = " UPDATE porderdt SET  porderdt_grnrejected = $objval WHERE porderdt_id = $PRqstDtid ";
		
		if (!updateData($connection, $query, true)) 
			$message  = mysql_error();
		
		else 
					    if ( $config['log_file'] == 1){
							$query_history=" INSERT INTO porderdt (porderdt_grnrejected,porderdt_id, porderdt_history_date, porderdt_history_operator_id, porderdt_history_schema, porderdt_history_status) ".
							 " VALUES ( $objval,$PRqstDtid
								,now()
								, '".$User_Name."'
								, '".$_SESSION['dbName']."'
								, 'U')";
								if(!updateData($connection_history, $query_history, true))		 
								$message  = mysql_error($query_history);
					
							}
	}
	
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
}


if ($mode == "import"){
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (!isset($PPorCurr))
	   $PPorCurr = $base1;
	   
	if (empty($PPorCategory))
		$PPorCategory = 0;
	if (empty($PPorStatus))
		$PPorStatus = 'A';	
	if (empty($PPorDiscountAmt))
		$PPorDiscountAmt = 0;
	if (empty($PPorDiscount))
		$PPorDiscount = 0;   
	
	$PPorCostCentCode = "".$PPorCostCentCode;
	if ($PPorCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPorCostCentCode."'";
	
	$PPorProjectCode = "".$PPorProjectCode;		
	if ($PPorProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPorProjectCode."'";   
	
		
	if($txtShippingmethod == '') $txtShippingmethod = "NULL";
	$txtPaymentCondidions = $_POST['txtPaymentCondidions'];
	
	//Check For Supplier, Project and Costcenter Codes Before Insert
	if ($PPorCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PPorCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PPorProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PPorProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($PPorSupplier != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$PPorSupplier."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Supplier Code.';
		}
	}
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PPorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PPorCurr."' )";
	$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];
	
	//insert header
	if ($SPorId == "" && $ErrorExists == 0){
		fbegin();	
		$PPorId = get_nextsequence('Porder_Id','',$connection);
		fcommit();
		
		if ($Module_PorderConfirm == 0) $PPorConfirmed = 1; else $PPorConfirmed = 0; 
		
		if($porder_downperc=='')
			$porder_downperc=' null';
			
		if($porder_downamount=='')
			$porder_downamount='null';
		
		fbegin();
		if($_POST['porder_actualdate'] == ""){
		    $porder_actualdate = "00/00/0000";
		}
		else{
			$porder_actualdate = $_POST['porder_actualdate'];
		}
		
		$query = " INSERT INTO temp_porder (Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, Costcent_code, Supplier_code, ".
				 " Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, Porder_Status, Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, ".
				 " Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, Porder_Type, ".
				 " Porder_Confirmed, Porder_BelongsToGroup, Logged_Code, porder_paymentcondition, porder_downpayment, porder_downperc, porder_downamount,shippingmethod_id, user_account, approvedby,
				  porder_actualdate , supplier_code1) ".
				 " VALUES ( ".$PPorId.", Null, '".insertMySQLDate($PPorDate)."', '".insertMySQLDate($PPorRequestDate)."', '".ereg_replace("'", "\'", trim($PPorRequestBy))."', ".
				 "          '".$PPorCurr."', $ProjectCode, $CostCentCode, '".ereg_replace("'", "\'", trim($PPorSupplier))."', '".ereg_replace("'", "\'", trim($PPorSupplierContact))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPorRemark))."', 0, '".insertMySQLDate($PPorExpiryDate)."', '".$PPorCategory."', '".$PPorStatus."', '".ereg_replace("'", "\'", trim($PPorStatusRemark))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPorDeliveryPlace))."', '".ereg_replace("'", "\'", trim($PPorDeliveryContact))."', 0, 0, 0, 0, 0, 0, 0, 0, 0, $PPorDiscount, 0, 0, 0, ".
				 "          0, 0, 0, $PPorVatChkbx, 'PO', $PPorConfirmed, $FI_BelongsToGrp, '".$_SESSION['useraccount']."','".ereg_replace("'", "\'", trim($txtPaymentCondidions))."', ".
				 " 		    $porder_downpayment, $porder_downperc, $porder_downamount, $txtShippingmethod, '".$_SESSION['useraccount']."', '".$approvedby."', '".insertMySQLDate($porder_actualdate)."' , '".ereg_replace("'", "\'", trim($PPorSupplier1))."')";
						 
		
		$result=mysql_query($query,$connection);
		if ($result){
			$SPorId = $PPorId;
			fcommit();			
		}else{
			$PPorId = "";
			$SPorId = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
	} 
	
	//Insert Detail Tables
	if ($SPorId != ""  && $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'];
					
		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];
			$lstWarehouse = $excel->sheets[0]['cells'][$x][2];
			$txtPorDtQty = $excel->sheets[0]['cells'][$x][3];
			$txtPorDtCost = $excel->sheets[0]['cells'][$x][4];
			$txtPorDtFreight = $excel->sheets[0]['cells'][$x][5]; 
						
			if($txtPorDtCost == '') $txtPorDtCost = 0;
			if($txtPorDtFreight == '') $txtPorDtFreight = 0;
			
			$txtPorDtPrice = $txtPorDtCost + $txtPorDtFreight;
			
			if (empty($txtPorDtPrice))
			$txtPorDtPrice = 0;
			$txtPorDtDiscount = 0;
			if (empty($txtPorDtQty))
				$txtPorDtQty = 0;      		
			if (empty($txtPorDtQty2))
				$txtPorDtQty2 = 0;
		
			$vPorDtPriceTTC      = 0;
			$vPorDtPriceTTCBase1 = 0;
			$vPorDtPriceTTCBase2 = 0;					
			$vPorDtPrice      	 = 0;
			$vPorDtPriceBase1 	 = 0;
			$vPorDtPriceBase2 	 = 0;
			$vPorDtDiscAmt       = 0;
			$vPorDtDiscAmtBase1  = 0;
			$vPorDtDiscAmtBase2  = 0;
					
			$vSupTax1 = 0;
			$vSupTax2 = 0;
			$vSupTax3 = 0;
			$vSupTax4 = 0;
			$vSupTax5 = 0;
			$vPorDtTax1 = 0;
			$vPorDtTax2 = 0;
			$vPorDtTax3 = 0;
			$vPorDtTax4 = 0;
			$vPorDtTax5 = 0;
			
			if ($txtItemCode != '') {
				$sub_query = " Select Count(Item_Code) From Items ".
							 " Where Item_Code = '".$txtItemCode."' and ifnull(item_active,0) = 1";
				$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($ErrorExists == 0){
												
				if ($Module_ProjectDt == 1){
					$ProjectCodeDt = $ProjectCode;
				}
				
				$txtCostCentCodeDt = "".$txtCostCentCodeDt;
				if ($Module_CostCenterDt == 1) {
					$CostCentCodeDt = $CostCentCode;
				}		
				$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
				$result   = selectData($connection, $query);
				$ItemPack = $result[0];
					
				//Check If Item Exists In PorderDt, If So Stop User
				$query = " Select Count(*) ".
						 " From Temp_PorderDt As PorderDt ".
						 " Inner Join Items on Items.Item_Code = PorderDt.Item_Code ".
						 " Where Porder_ID = '".$SPorId."' ";
						 
				//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All")
				if ($ItemPack != 1) 
					$query = $query." And PorderDt.Item_Code = '".$txtItemCode."' ".
									" And (PorderDt.Item_CodePacked is null or PorderDt.Item_CodePacked  = '') ";
				else
					$query = $query." And PorderDt.Item_CodePacked = '".$txtItemCode."' ".
									" And (PorderDt.Item_CodePacked is not null and PorderDt.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.";
				} 
				
				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) ".
								" FROM Items WHERE item_Code = '".$txtItemCode."'";
						$result = selectData($connection, $query);
						$ItemVat 	   = $result[0];
						$Item_MaxQty   = $result[1];
						$ItemGroupCode = $result[2];
						$ItemProd	   = $result[3];
						$ItemTTCInc	   = $result[4];
						$ItemUnit      = $result[5];
						//$ItemVat = $ItemVat/100;
						$tax_flag = 0;
						$notax_flag = 1;
						if ($ItemVat > 0){
							$tax_flag = 1;
							$notax_flag = 0;
						}

						$vItemUnitCoef = 0;
						$vItemUnit2Qty = 0;
						if ($Module_DoubleUnit == 1) {
							$vItemUnitCoef = $ItemUnit;
							$vItemUnit2Qty = $txtPorDtQty2;
						}
						
						if ($PurchaseTTC == 1) {
							$vPorDtPriceTTC      = $txtPorDtPrice;
							$vPorDtPriceTTCBase1 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt1;
							$vPorDtPriceTTCBase2 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt2;					
							
							//Added 2011/09/24
							if ($PPorVatChkbx == 1)	$vPorDtPrice = ($vPorDtPriceTTC / (1 + $ItemVat/100));
							else $vPorDtPrice = $txtPorDtPrice;
								
							$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
							$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
									
						} else	{
							$vPorDtPrice      = $txtPorDtPrice;
							$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
							$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
							
							$vPorDtPriceTTC      = 0;
							$vPorDtPriceTTCBase1 = 0;
							$vPorDtPriceTTCBase2 = 0;
									
						}	

						// Calculation For Detail Discount Amount
						$vPorDtDiscAmt       = 0;
						$vPorDtDiscAmtBase1  = 0;
						$vPorDtDiscAmtBase2  = 0;
								
						if ($Module_AdditionalTaxes == 1) {
							// Calculation of Item Tax Amounts
							$query = " SELECT ifNull(Supplier_Tax1,0), ifNull(Supplier_Tax2,0), ifNull(Supplier_Tax3,0), ifNull(Supplier_Tax4,0), ifNull(Supplier_Tax5,0) ".
									 " FROM Suppliers ".
									 " WHERE Ledger_number = '".$PPorSupplier."'";
														 
							$result = selectData($connection, $query);
							$vSupTax1 = $result[0];
							$vSupTax2 = $result[1];
							$vSupTax3 = $result[2];
							$vSupTax4 = $result[3];
							$vSupTax5 = $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 ($vSupTax1 != 0)	$vPorDtTax1 = $result[0];
							if ($vSupTax2 != 0)	$vPorDtTax2 = $result[1];
							if ($vSupTax3 != 0)	$vPorDtTax3 = $result[2];
							if ($vSupTax4 != 0)	$vPorDtTax4 = $result[3];
							if ($vSupTax5 != 0)	$vPorDtTax5 = $result[4];
										
						} //end module taxes
						
						fbegin();
						$txtPorDtId = get_nextsequence('PorderDt_id','',$connection);	
						fcommit();

						
						fbegin();
						$query = " INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
								 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
								 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code ,porderdt_cost,porderdt_freight) ".
								 " VALUES ( ".$txtPorDtId.", ".$PPorId.", '".$PPorCurr."', '".insertMySQLDate($PPorDate)."', '".ereg_replace("'", "\'", trim($PPorSupplier))."', $ProjectCodeDt, $CostCentCodeDt, ".
								 "          '".$lstWarehouse."', '".trim(strtoupper($txtItemCode))."', Null, 0, $txtPorDtQty, $vPorDtPrice, $vPorDtPriceBase1, $vPorDtPriceBase2, $vPorDtPriceTTC, $vPorDtPriceTTCBase1, $vPorDtPriceTTCBase2, ".
								 "          $txtPorDtDiscount, $vPorDtDiscAmt, $vPorDtDiscAmtBase1, $vPorDtDiscAmtBase2, $ItemVat,   ".
								 "          $vPorDtTax1, $vPorDtTax2, $vPorDtTax3, $vPorDtTax4, $vPorDtTax5, 0, $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."','$txtPorDtCost','$txtPorDtFreight') ";
							
						//echo $query."<br>";exit;				
						$result=mysql_query($query,$connection);
						
						if ($result){
							fcommit();							
						} else {
							$txtPorDtId = "";
							$ErrorExists = 1;
							$message  = mysql_error(); 
							frollback();
						}
					} //end if item is not pack
					else {
						$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage ".
									   " 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];
							
							fbegin();
							$vPorDtId = get_nextsequence('PorderDt_id','',$connection);
							fcommit();
							
							$vPorDtQty = $txtPorDtQty*$vPackDtQty;
							
							$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0) ".
									 " FROM Items WHERE item_Code = '".$vItemCode."'";
							$result = selectData($connection, $query);
							$ItemVat 	   = $result[0];
							$Item_MaxQty   = $result[1];
							$ItemGroupCode = $result[2];
							$ItemProd 	   = $result[3];
							$ItemTTCInc	   = $result[4];
							$ItemUnit  	   = $result[5];
							//$ItemVat = $ItemVat/100;
							$tax_flag = 0;
							$notax_flag = 1;
							if ($ItemVat > 0){
								$tax_flag = 1;
								$notax_flag = 0;
							}
					
							$vItemUnitCoef = 0;
							$vItemUnit2Qty = 0;
							if ($Module_DoubleUnit == 1) {
								$vItemUnitCoef = $ItemUnit;
								
								if ($Module_Unit1Method == 1)
									$vItemUnit2Qty = $vPorDtQty*$vItemUnitCoef;
								else	
									$vItemUnit2Qty = $vPorDtQty/$vItemUnitCoef;
							}		
				
							$vPorDtPriceTTC      = 0;
							$vPorDtPriceTTCBase1 = 0;
							$vPorDtPriceTTCBase2 = 0;					
							$vPorDtPrice      	 = 0;
							$vPorDtPriceBase1 	 = 0;
							$vPorDtPriceBase2 	 = 0;
							$vPorDtDiscAmt       = 0;
							$vPorDtDiscAmtBase1  = 0;
							$vPorDtDiscAmtBase2  = 0;
							
							
							$vSupTax1 = 0;
							$vSupTax2 = 0;
							$vSupTax3 = 0;
							$vSupTax4 = 0;
							$vSupTax5 = 0;
							$vPorDtTax1 = 0;
							$vPorDtTax2 = 0;
							$vPorDtTax3 = 0;
							$vPorDtTax4 = 0;
							$vPorDtTax5 = 0;
							
							if ($PurchaseTTC == 1) {
							$vPorDtPriceTTC      = (($txtPorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
							$vPorDtPriceTTCBase1 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt1;
							$vPorDtPriceTTCBase2 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt2;					
							
							//Added 2011/09/24
							if ($PPorVatChkbx == 1)	$vPorDtPrice = ($vPorDtPriceTTC / (1 + $ItemVat/100));
							else $vPorDtPrice = $vPorDtPriceTTC;
					
							$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
							$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
							
							} else	{
								$vPorDtPrice      = (($txtPorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
								$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
								$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
								
								$vPorDtPriceTTC      = 0;
								$vPorDtPriceTTCBase1 = 0;
								$vPorDtPriceTTCBase2 = 0;
								
							}
							// Calculation For Detail Discount Amount
							$vPorDtDiscAmt       = (($vPorDtPrice*$vPorDtQty) - ($vPorDtPrice*$vPorDtQty*$txtPorDtDiscount/100))*$PPorDiscount;
							$vPorDtDiscAmtBase1  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt1;
							$vPorDtDiscAmtBase2  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt2;		
							
							if ($Module_AdditionalTaxes == 1) {
								// Calculation of Item Tax Amounts
								$query = " SELECT ifNull(Supplier_Tax1,0), ifNull(Supplier_Tax2,0), ifNull(Supplier_Tax3,0), ifNull(Supplier_Tax4,0), ifNull(Supplier_Tax5,0) ".
										 " FROM Suppliers ".
										 " WHERE Ledger_number = '".$PPorSupplier."'";
															 
								$result = selectData($connection, $query);
								$vSupTax1 = $result[0];
								$vSupTax2 = $result[1];
								$vSupTax3 = $result[2];
								$vSupTax4 = $result[3];
								$vSupTax5 = $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 ($vSupTax1 != 0)	$vPorDtTax1 = $result[0];
								if ($vSupTax2 != 0)	$vPorDtTax2 = $result[1];
								if ($vSupTax3 != 0)	$vPorDtTax3 = $result[2];
								if ($vSupTax4 != 0)	$vPorDtTax4 = $result[3];
								if ($vSupTax5 != 0)	$vPorDtTax5 = $result[4];
											
							}	// end if module taxes
							$query = " INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
									 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
									 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
									 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code ,porderdt_cost,porderdt_freight) ".
									 " VALUES ( ".$vPorDtId.", ".$PPorId.", '".$PPorCurr."', '".insertMySQLDate($PPorDate)."', '".ereg_replace("'", "\'", trim($PPorSupplier))."', $ProjectCodeDt, $CostCentCodeDt, ".
									 "          '".$lstWarehouse."', '".trim(strtoupper($vItemCode))."', '".$vItemCodePacked."', $vPorDtQty, $vPorDtQty, $vPorDtPrice, $vPorDtPriceBase1, $vPorDtPriceBase2, $vPorDtPriceTTC, ".
									 "          $vPorDtPriceTTCBase1, $vPorDtPriceTTCBase2, 0, $vPorDtDiscAmt, $vPorDtDiscAmtBase1, $vPorDtDiscAmtBase2, $ItemVat, ".
									 "          $vPorDtTax1, $vPorDtTax2, $vPorDtTax3, $vPorDtTax4, $vPorDtTax5, 0, $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."','$txtPorDtCost','$txtPorDtFreight' ) ";
									 
							$result=mysql_query($query,$connection);
							if ($result){
								fcommit();
							} else {
								$txtPorDtId = "";
								$ErrorExists = 1;
								$message  = mysql_error(); 
								frollback();								
							}
						} // end while item pack query						
					} // end if item is pack
					
				} // end if InsertAllow
				
			} // end if ErrorExists
			$x++;
		} // end while excel
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			
			$CalculateResult = Calculate_MasterAmounts($SPorId, $PPorDate, $PPorVatChkbx, $PPorDiscount, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}
	} // end if
}

if ($mode == "submitrecord"  || $mode == "submitrecord-ajax"){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (!isset($PPorCurr))
	   $PPorCurr = $base1;
	   
	if (empty($PPorCategory))
		$PPorCategory = 0;
	if (empty($PPorStatus))
		$PPorStatus = 'A';	
	if (empty($PPorDiscountAmt))
		$PPorDiscountAmt = 0;
	if (empty($PPorDiscount))
		$PPorDiscount = 0;   
	
	$PPorCostCentCode = "".$PPorCostCentCode;
	if ($PPorCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPorCostCentCode."'";
	$PPorProjectCode = "".$PPorProjectCode;		
	if ($PPorProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPorProjectCode."'";   
	
	$txtProjectCodeDt = "".$txtProjectCodeDt;	
	if ($Module_ProjectDt == 1){
		if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
		else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
	} else {
		$ProjectCodeDt = $ProjectCode;
	}
	
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;
	if ($Module_CostCenterDt == 1) {
		if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
		else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
	} else {
		$CostCentCodeDt = $CostCentCode;
	}	
	
	if($txtShippingmethod == '') $txtShippingmethod = "NULL";
	
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PPorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PPorCurr."' )";
	$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 Supplier, Project and Costcenter Codes Before Insert
	if ($PPorCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PPorCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PPorProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PPorProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($PPorSupplier != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$PPorSupplier."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Supplier Code.';
		}
	}
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".trim(strtoupper($txtItemCode))."' and ifnull(item_active,0) = 1";
		$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 ($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 ($SPorId == "" && $ErrorExists == 0){
	
			
		fbegin();	
		$PPorId = get_nextsequence('Porder_Id','',$connection);
		fcommit();
		
		if ($Module_PorderConfirm == 0) $PPorConfirmed = 1; else $PPorConfirmed = 0; 
		
		if($porder_downperc=='')
			$porder_downperc=' null';
			
		if($porder_downamount=='')
			$porder_downamount='null';
		
		fbegin();
		if($_POST['porder_actualdate'] == ""){
		    $porder_actualdate = "00/00/0000";
		}
		else{
			$porder_actualdate = $_POST['porder_actualdate'];
		}
		$query = " INSERT INTO temp_porder (Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, Costcent_code, Supplier_code, ".
				 " Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, Porder_Status, Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, ".
				 " Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, Porder_Type, ".
				 " Porder_Confirmed, Porder_BelongsToGroup, Logged_Code, porder_paymentcondition, porder_downpayment, porder_downperc, porder_downamount,shippingmethod_id, user_account, approvedby,
				  porder_actualdate, supplier_code1) ".
				 " VALUES ( ".$PPorId.", Null, '".insertMySQLDate($PPorDate)."', '".insertMySQLDate($PPorRequestDate)."', '".ereg_replace("'", "\'", trim($PPorRequestBy))."', ".
				 "          '".$PPorCurr."', $ProjectCode, $CostCentCode, '".ereg_replace("'", "\'", trim($PPorSupplier))."', '".ereg_replace("'", "\'", trim($PPorSupplierContact))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPorRemark))."', 0, '".insertMySQLDate($PPorExpiryDate)."', '".$PPorCategory."', '".$PPorStatus."', '".ereg_replace("'", "\'", trim($PPorStatusRemark))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPorDeliveryPlace))."', '".ereg_replace("'", "\'", trim($PPorDeliveryContact))."', 0, 0, 0, 0, 0, 0, 0, 0, 0, $PPorDiscount, 0, 0, 0, ".
				 "          0, 0, 0, $PPorVatChkbx, 'PO', $PPorConfirmed, $FI_BelongsToGrp, '".$_SESSION['useraccount']."','".ereg_replace("'", "\'", trim($txtPaymentCondidions))."', ".
				 " 		    $porder_downpayment, $porder_downperc, $porder_downamount, $txtShippingmethod, '".$_SESSION['useraccount']."', '".$approvedby."', '".insertMySQLDate($porder_actualdate)."', '".ereg_replace("'", "\'", trim($PPorSupplier1))."' )";
						 
		
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
			
		
		if ($result){
			
			 if ( $config['log_file'] == 1){
							$query_history=" INSERT INTO temp_porder (Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, Costcent_code, Supplier_code, ".
				 " Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, Porder_Status, Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, ".
				 " Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, Porder_Type, ".
				 " Porder_Confirmed, Porder_BelongsToGroup, Logged_Code, porder_paymentcondition, porder_downpayment, porder_downperc, porder_downamount,shippingmethod_id, user_account, approvedby, porder_actualdate,
				 temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status) ".
				 " VALUES ( ".$PPorId.", Null, '".insertMySQLDate($PPorDate)."', '".insertMySQLDate($PPorRequestDate)."', '".ereg_replace("'", "\'", trim($PPorRequestBy))."', ".
				 "          '".$PPorCurr."', $ProjectCode, $CostCentCode, '".ereg_replace("'", "\'", trim($PPorSupplier))."', '".ereg_replace("'", "\'", trim($PPorSupplierContact))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPorRemark))."', 0, '".insertMySQLDate($PPorExpiryDate)."', '".$PPorCategory."', '".$PPorStatus."', '".ereg_replace("'", "\'", trim($PPorStatusRemark))."', ".
				 "          '".ereg_replace("'", "\'", trim($PPorDeliveryPlace))."', '".ereg_replace("'", "\'", trim($PPorDeliveryContact))."', 0, 0, 0, 0, 0, 0, 0, 0, 0, $PPorDiscount, 0, 0, 0, ".
				 "          0, 0, 0, $PPorVatChkbx, 'PO', $PPorConfirmed, $FI_BelongsToGrp, '".$_SESSION['useraccount']."','".ereg_replace("'", "\'", trim($txtPaymentCondidions))."', ".
				 " 		    $porder_downpayment, $porder_downperc, $porder_downamount, $txtShippingmethod, '".$_SESSION['useraccount']."', '".$approvedby."', '".insertMySQLDate($porder_actualdate)."' 
								,now()
								, '".$User_Name."'
								, '".$_SESSION['dbName']."'
								, 'I')";
								if(!updateData($connection_history, $query_history, true))		 
								$message  = mysql_error($query_history);
					
							}
			$SPorId = $PPorId;
			fcommit();
		}else{
			$PPorId = "";
			$SPorId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SPorId != "" && $SPorDtId == ""  && $ErrorExists == 0){
	
		if (empty($txtPorDtPrice))
			$txtPorDtPrice = 0;
		if (empty($txtPorDtDiscount))
		    $txtPorDtDiscount = 0;
		if (empty($txtPorDtQty))
		    $txtPorDtQty = 0;      		
		if (empty($txtPorDtQty2))
		    $txtPorDtQty2 = 0;			
		
		
		
		$vPorDtPriceTTC      = 0;
		$vPorDtPriceTTCBase1 = 0;
		$vPorDtPriceTTCBase2 = 0;					
		$vPorDtPrice      	 = 0;
		$vPorDtPriceBase1 	 = 0;
		$vPorDtPriceBase2 	 = 0;
		$vPorDtDiscAmt       = 0;
		$vPorDtDiscAmtBase1  = 0;
		$vPorDtDiscAmtBase2  = 0;
				
		$vSupTax1 = 0;
		$vSupTax2 = 0;
		$vSupTax3 = 0;
		$vSupTax4 = 0;
		$vSupTax5 = 0;
		$vPorDtTax1 = 0;
		$vPorDtTax2 = 0;
		$vPorDtTax3 = 0;
		$vPorDtTax4 = 0;
		$vPorDtTax5 = 0;
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
			
		//Check If Item Exists In PorderDt, If So Stop User
		$query = " Select Count(*) ".
				 " From Temp_PorderDt As PorderDt ".
				 " Inner Join Items on Items.Item_Code = PorderDt.Item_Code ".
				 " Where Porder_ID = '".$SPorId."' ";
				 
		//if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All")
		if ($ItemPack != 1) 
			$query = $query." And PorderDt.Item_Code = '".$txtItemCode."' ".
							" And (PorderDt.Item_CodePacked is null or PorderDt.Item_CodePacked  = '') ";
		else
			$query = $query." And PorderDt.Item_CodePacked = '".$txtItemCode."' ".
							" And (PorderDt.Item_CodePacked is not null and PorderDt.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.";
		} 
		
		
		if ($InsertAllow == 1) {
			// Case Not Pack Item
			//if ($txtItemCodePacked == '') {
			//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) ".
						" FROM Items WHERE item_Code = '".$txtItemCode."'";
				$result = selectData($connection, $query);
				$ItemVat 	   = $result[0];
				$Item_MaxQty   = $result[1];
				$ItemGroupCode = $result[2];
				$ItemProd	   = $result[3];
				$ItemTTCInc	   = $result[4];
				$ItemUnit      = $result[5];
				//$ItemVat = $ItemVat/100;
				$tax_flag = 0;
				$notax_flag = 1;
				if ($ItemVat > 0){
					$tax_flag = 1;
					$notax_flag = 0;
				}	
				
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $ItemUnit;
					$vItemUnit2Qty = $txtPorDtQty2;
				}
				
				if ($PurchaseTTC == 1) {
					$vPorDtPriceTTC      = $txtPorDtPrice;
					$vPorDtPriceTTCBase1 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt1;
					$vPorDtPriceTTCBase2 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt2;					
					
					//Added 2011/09/24
					if ($PPorVatChkbx == 1)	$vPorDtPrice = ($vPorDtPriceTTC / (1 + $ItemVat/100));
					else $vPorDtPrice = $txtPorDtPrice;
						
					$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
					$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
							
				} else	{
					$vPorDtPrice      = $txtPorDtPrice;
					$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
					$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
					
					$vPorDtPriceTTC      = 0;
					$vPorDtPriceTTCBase1 = 0;
					$vPorDtPriceTTCBase2 = 0;
							
				}	
					
						
				
				// Calculation For Detail Discount Amount
				$vPorDtDiscAmt       = (($vPorDtPrice*$txtPorDtQty) - ($vPorDtPrice*$txtPorDtQty*$txtPorDtDiscount/100))*$PPorDiscount;
				$vPorDtDiscAmtBase1  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt1;
				$vPorDtDiscAmtBase2  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt2;
					


				if ($Module_AdditionalTaxes == 1) {
					// Calculation of Item Tax Amounts
					$query = " SELECT ifNull(Supplier_Tax1,0), ifNull(Supplier_Tax2,0), ifNull(Supplier_Tax3,0), ifNull(Supplier_Tax4,0), ifNull(Supplier_Tax5,0) ".
							 " FROM Suppliers ".
							 " WHERE Ledger_number = '".$PPorSupplier."'";
												 
					$result = selectData($connection, $query);
					$vSupTax1 = $result[0];
					$vSupTax2 = $result[1];
					$vSupTax3 = $result[2];
					$vSupTax4 = $result[3];
					$vSupTax5 = $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 ($vSupTax1 != 0)	$vPorDtTax1 = $result[0];
					if ($vSupTax2 != 0)	$vPorDtTax2 = $result[1];
					if ($vSupTax3 != 0)	$vPorDtTax3 = $result[2];
					if ($vSupTax4 != 0)	$vPorDtTax4 = $result[3];
					if ($vSupTax5 != 0)	$vPorDtTax5 = $result[4];
								
				}
					
								
				
				fbegin();
				$txtPorDtId = get_nextsequence('PorderDt_id','',$connection);	
				fcommit();

				
				fbegin();
				$query = " INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
						 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
						 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
						 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code ,PorderDt_heatNo,porderdt_cost,porderdt_freight) ".
						 " VALUES ( ".$txtPorDtId.", ".$PPorId.", '".$PPorCurr."', '".insertMySQLDate($PPorDate)."', '".ereg_replace("'", "\'", trim($PPorSupplier))."', $ProjectCodeDt, $CostCentCodeDt, ".
						 "          '".$lstWarehouse."', '".trim(strtoupper($txtItemCode))."', Null, 0, $txtPorDtQty, $vPorDtPrice, $vPorDtPriceBase1, $vPorDtPriceBase2, $vPorDtPriceTTC, $vPorDtPriceTTCBase1, $vPorDtPriceTTCBase2, ".
						 "          $txtPorDtDiscount, $vPorDtDiscAmt, $vPorDtDiscAmtBase1, $vPorDtDiscAmtBase2, $ItemVat, '".ereg_replace("'", "\'", trim($txtPorDtRemark))."' ,  ".
						 "          $vPorDtTax1, $vPorDtTax2, $vPorDtTax3, $vPorDtTax4, $vPorDtTax5, 0, $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."','$porderdt_heatno','$txtporcost','$txtporfreight') ";
					
				//echo $query."<br>";exit;		
                  // $message  = $query; 
					//frollback();				
				$result=mysql_query($query,$connection);
					
				if ($result){
					
					 if ( $config['log_file'] == 1){
							$query_history= " INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
						 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
						 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
						 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code ,PorderDt_heatNo,porderdt_cost,porderdt_freight,temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status) ".
						 " VALUES ( ".$txtPorDtId.", ".$PPorId.", '".$PPorCurr."', '".insertMySQLDate($PPorDate)."', '".ereg_replace("'", "\'", trim($PPorSupplier))."', $ProjectCodeDt, $CostCentCodeDt, ".
						 "          '".$lstWarehouse."', '".$txtItemCode."', Null, 0, $txtPorDtQty, $vPorDtPrice, $vPorDtPriceBase1, $vPorDtPriceBase2, $vPorDtPriceTTC, $vPorDtPriceTTCBase1, $vPorDtPriceTTCBase2, ".
						 "          $txtPorDtDiscount, $vPorDtDiscAmt, $vPorDtDiscAmtBase1, $vPorDtDiscAmtBase2, $ItemVat, '".ereg_replace("'", "\'", trim($txtPorDtRemark))."' ,  ".
						 "          $vPorDtTax1, $vPorDtTax2, $vPorDtTax3, $vPorDtTax4, $vPorDtTax5, 0, $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."','$porderdt_heatno','$txtporcost','$txtporfreight'
								,now()
								, '".$User_Name."'
								, '".$_SESSION['dbName']."'
								, 'I')";
								$result=mysql_query($query_history,$connection_history);
					
							}
					
					
					fcommit();
						
				}else{
					$txtPorDtId = "";
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}				
				
			}	// End Case Not Pack Item
			else {
				
					fbegin();
					$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage ".
								   " 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];
						
						fbegin();
						$vPorDtId = get_nextsequence('PorderDt_id','',$connection);
						fcommit();
	
						$vPorDtQty = $txtPorDtQty*$vPackDtQty;
						
						$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0) ".
								 " FROM Items WHERE item_Code = '".$vItemCode."'";
						$result = selectData($connection, $query);
						$ItemVat 	   = $result[0];
						$Item_MaxQty   = $result[1];
						$ItemGroupCode = $result[2];
						$ItemProd 	   = $result[3];
						$ItemTTCInc	   = $result[4];
						$ItemUnit  	   = $result[5];
						//$ItemVat = $ItemVat/100;
						$tax_flag = 0;
						$notax_flag = 1;
						if ($ItemVat > 0){
							$tax_flag = 1;
							$notax_flag = 0;
						}

						$vItemUnitCoef = 0;
						$vItemUnit2Qty = 0;
						if ($Module_DoubleUnit == 1) {
							$vItemUnitCoef = $ItemUnit;
							
							if ($Module_Unit1Method == 1)
								$vItemUnit2Qty = $vPorDtQty*$vItemUnitCoef;
							else	
								$vItemUnit2Qty = $vPorDtQty/$vItemUnitCoef;
						}							
						
						$vPorDtPriceTTC      = 0;
						$vPorDtPriceTTCBase1 = 0;
						$vPorDtPriceTTCBase2 = 0;					
						$vPorDtPrice      	 = 0;
						$vPorDtPriceBase1 	 = 0;
						$vPorDtPriceBase2 	 = 0;
						$vPorDtDiscAmt       = 0;
						$vPorDtDiscAmtBase1  = 0;
						$vPorDtDiscAmtBase2  = 0;
						
						
						$vSupTax1 = 0;
						$vSupTax2 = 0;
						$vSupTax3 = 0;
						$vSupTax4 = 0;
						$vSupTax5 = 0;
						$vPorDtTax1 = 0;
						$vPorDtTax2 = 0;
						$vPorDtTax3 = 0;
						$vPorDtTax4 = 0;
						$vPorDtTax5 = 0;

						
						if ($PurchaseTTC == 1) {
							$vPorDtPriceTTC      = (($txtPorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
							$vPorDtPriceTTCBase1 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt1;
							$vPorDtPriceTTCBase2 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt2;					
							
							//Added 2011/09/24
							if ($PPorVatChkbx == 1)	$vPorDtPrice = ($vPorDtPriceTTC / (1 + $ItemVat/100));
							else $vPorDtPrice = $vPorDtPriceTTC;
					
							$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
							$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
							
						} else	{
							$vPorDtPrice      = (($txtPorDtPrice*$vPackDtCostPer/100)/$vPackDtQty);
							$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
							$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
							
							$vPorDtPriceTTC      = 0;
							$vPorDtPriceTTCBase1 = 0;
							$vPorDtPriceTTCBase2 = 0;
							
						}
						
						
						
						// Calculation For Detail Discount Amount
						$vPorDtDiscAmt       = (($vPorDtPrice*$vPorDtQty) - ($vPorDtPrice*$vPorDtQty*$txtPorDtDiscount/100))*$PPorDiscount;
						$vPorDtDiscAmtBase1  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt1;
						$vPorDtDiscAmtBase2  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt2;
						

						
						if ($Module_AdditionalTaxes == 1) {
							// Calculation of Item Tax Amounts
							$query = " SELECT ifNull(Supplier_Tax1,0), ifNull(Supplier_Tax2,0), ifNull(Supplier_Tax3,0), ifNull(Supplier_Tax4,0), ifNull(Supplier_Tax5,0) ".
									 " FROM Suppliers ".
									 " WHERE Ledger_number = '".$PPorSupplier."'";
														 
							$result = selectData($connection, $query);
							$vSupTax1 = $result[0];
							$vSupTax2 = $result[1];
							$vSupTax3 = $result[2];
							$vSupTax4 = $result[3];
							$vSupTax5 = $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 ($vSupTax1 != 0)	$vPorDtTax1 = $result[0];
							if ($vSupTax2 != 0)	$vPorDtTax2 = $result[1];
							if ($vSupTax3 != 0)	$vPorDtTax3 = $result[2];
							if ($vSupTax4 != 0)	$vPorDtTax4 = $result[3];
							if ($vSupTax5 != 0)	$vPorDtTax5 = $result[4];
										
						}
				
											
						$query = " INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
								 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
								 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code ,PorderDt_heatNo,porderdt_cost,porderdt_freight) ".
								 " VALUES ( ".$vPorDtId.", ".$PPorId.", '".$PPorCurr."', '".insertMySQLDate($PPorDate)."', '".ereg_replace("'", "\'", trim($PPorSupplier))."', $ProjectCodeDt, $CostCentCodeDt, ".
								 "          '".$lstWarehouse."', '".trim(strtoupper($vItemCode))."', '".$vItemCodePacked."', $vPorDtQty, $vPorDtQty, $vPorDtPrice, $vPorDtPriceBase1, $vPorDtPriceBase2, $vPorDtPriceTTC, ".
								 "          $vPorDtPriceTTCBase1, $vPorDtPriceTTCBase2, $txtPorDtDiscount, $vPorDtDiscAmt, $vPorDtDiscAmtBase1, $vPorDtDiscAmtBase2, $ItemVat, '".ereg_replace("'", "\'", trim($txtPorDtRemark))."' ,  ".
								 "          $vPorDtTax1, $vPorDtTax2, $vPorDtTax3, $vPorDtTax4, $vPorDtTax5, 0, $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."','$porderdt_heatno','$txtporcost','$txtporfreight' ) ";
								 
						$result=mysql_query($query,$connection);
							
						//echo $query;
					} // End Loop Of Packdt
					
				
					if ($result){
						
							 if ( $config['log_file'] == 1){
							$query_history=" INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
								 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
								 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code ,PorderDt_heatNo,porderdt_cost,porderdt_freight,
								 temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status) ".
								 " VALUES ( ".$vPorDtId.", ".$PPorId.", '".$PPorCurr."', '".insertMySQLDate($PPorDate)."', '".ereg_replace("'", "\'", trim($PPorSupplier))."', $ProjectCodeDt, $CostCentCodeDt, ".
								 "          '".$lstWarehouse."', '".$vItemCode."', '".$vItemCodePacked."', $vPorDtQty, $vPorDtQty, $vPorDtPrice, $vPorDtPriceBase1, $vPorDtPriceBase2, $vPorDtPriceTTC, ".
								 "          $vPorDtPriceTTCBase1, $vPorDtPriceTTCBase2, $txtPorDtDiscount, $vPorDtDiscAmt, $vPorDtDiscAmtBase1, $vPorDtDiscAmtBase2, $ItemVat, '".ereg_replace("'", "\'", trim($txtPorDtRemark))."' ,  ".
								 "          $vPorDtTax1, $vPorDtTax2, $vPorDtTax3, $vPorDtTax4, $vPorDtTax5, 0, $vItemUnitCoef, $vItemUnit2Qty, '".$_SESSION['useraccount']."','$porderdt_heatno','$txtporcost','$txtporfreight'
											,now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'I')";
							$result=mysql_query($query_history,$connection_history);
					
							}
						
						fcommit();
					}else{
						$txtPorDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error(); 
						frollback();
					}	
				
				
			} // End CasePack Item
			
			if ($ErrorExists == 0) {
				//Calculating Master Amounts
				
				$CalculateResult = Calculate_MasterAmounts($SPorId, $PPorDate, $PPorVatChkbx, $PPorDiscount, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, '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 = '".trim(strtoupper($txtItemCode))."' and ifnull(item_active,0) = 1";
		$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.';
		}
	}
	$txtProjectCodeDt = "".$txtProjectCodeDt;
	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.';
		}
	}
	$txtCostCentCodeDt = "".$txtCostCentCodeDt;
	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 ($SPorId != "" && $SPorDtId != "" && $ErrorExists == 0) {
		
		if (empty($PPorDiscountAmt))
			$PPorDiscountAmt = 0;
		if (empty($PPorDiscount))
			$PPorDiscount = 0;
			
		if (empty($txtPorDtPrice))
			$txtPorDtPrice = 0;
		if (empty($txtPorDtDiscount))
		    $txtPorDtDiscount = 0;
		if (empty($txtPorDtQty))
		    $txtPorDtQty = 0;  
    	if (empty($txtPorDtQty2))
			$txtPorDtQty2 = 0;	
		
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}	
		
		if($txtShippingmethod == '') $txtShippingmethod = "NULL";
		
		$query = "SELECT Item_Vat FROM Items WHERE item_Code = '".trim(strtoupper($txtItemCode))."'";
		$result = selectData($connection, $query);
		$ItemVat = $result[0];
		//$ItemVat = $ItemVat/100;
		$tax_flag = 0;
		$notax_flag = 1;
		if ($ItemVat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
			
		$vPorDiscount = 0;
		$vPorDiscountAmt = 0;
		$vPorSuppCode = '';
		
		$vPorDtPriceTTC      = 0;
		$vPorDtPriceTTCBase1 = 0;
		$vPorDtPriceTTCBase2 = 0;					
		$vPorDtPrice      	 = 0;
		$vPorDtPriceBase1 	 = 0;
		$vPorDtPriceBase2 	 = 0;
		$vPorDtDiscAmt       = 0;
		$vPorDtDiscAmtBase1  = 0;
		$vPorDtDiscAmtBase2  = 0;
				
		
		
	
		$query = " Select Currency_code, ifNull(Porder_Taxable,0), ifNull(Porder_NoneTaxable,0), ifNull(Porder_DiscountPer,0), Supplier_code ".
				 " From Temp_Porder As Porder ".
				 " Where Porder_ID = ".$SPorId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";			 
				 
		
		$result=mysql_query($query,$connection) or die(mysql_error());
		$rows=mysql_fetch_array($result);
		
		$vPorCurr        = $rows[0];
		//$vPorTaxable     = $rows[1];
		//$vPorNoneTaxable = $rows[2];
		$vPorDiscount    = $rows[3];
		$vPorSuppCode    = $rows[4];
		
		
		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vPorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vPorCurr."' )";
		$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 ($PurchaseTTC == 1) {
			$vPorDtPriceTTC      = $txtPorDtPrice;
			$vPorDtPriceTTCBase1 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt1;
			$vPorDtPriceTTCBase2 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt2;					
			
			//Added 2011/09/24
			if ($PPorVatChkbx == 1)	$vPorDtPrice = ($vPorDtPriceTTC / (1 + $ItemVat/100));
			else $vPorDtPrice = $txtPorDtPrice;
					
			$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
			$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
			
		} else	{
			$vPorDtPrice      = $txtPorDtPrice;
			$vPorDtPriceBase1 = ($vPorDtPrice*$rate_dt)/$rate_dt1;
			$vPorDtPriceBase2 = ($vPorDtPrice*$rate_dt)/$rate_dt2;
		
			$vPorDtPriceTTC      = 0;
			$vPorDtPriceTTCBase1 = 0;
			$vPorDtPriceTTCBase2 = 0;
			
		}	
		
            
		// Calculation For Detail Discount Amount
		$vPorDtDiscAmt       = (($vPorDtPrice*$txtPorDtQty) - ($vPorDtPrice*$txtPorDtQty*$txtPorDtDiscount/100))*$vPorDiscount;
		$vPorDtDiscAmtBase1  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt1;
		$vPorDtDiscAmtBase2  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt2;
				
			
		//Edit Item Code/Warehouse Check If Item Is Purchased
		if ($Module_Grn != 1) {
			$sub_query = " Select Count(*) From PurchasesDt ".
						 " Where PurchasesDt.RelatedDt_Id = '".$SPorDtId."' ".
						 " And PurchasesDt.Journal_Type = 'PI' ";
		} else {
			$sub_query = " Select Count(*) From GrnPurchasesDt ".
						 " Where GrnPurchasesDt.RelatedDt_Id = '".$SPorDtId."' ".
						 " And GrnPurchasesDt.Journal_Type = 'PI' ";
		}
		$sub_result = selectData($connection, $sub_query);
		$PurchaseExists = 0;
		$PurchaseExists = $sub_result[0];
						
		fbegin();	
				
		$query = " UPDATE temp_porderdt SET ".
		         " PorderDt_Remark = '".ereg_replace("'", "\'", trim($txtPorDtRemark))."', PorderDt_Quantity = $txtPorDtQty, Item_Unit2Qty = $txtPorDtQty2, ".
				 " PorderDt_Price = $vPorDtPrice, PorderDt_PriceBase1 = $vPorDtPriceBase1, ProderDt_PriceBase2 = $vPorDtPriceBase2, PorderDt_Discount = $txtPorDtDiscount, ".
				 " PorderDt_PriceTTC = $vPorDtPriceTTC, PorderDt_PriceTTCBase1 = $vPorDtPriceTTCBase1, PorderDt_PriceTTCBase2 = $vPorDtPriceTTCBase2,  ".
				 " PorderDt_DiscountAmount = $vPorDtDiscAmt, PorderDt_Discountbase1 = $vPorDtDiscAmtBase1, PorderDt_Discountbase2 = $vPorDtDiscAmtBase2, ".
				 " porderdt_cost = '$txtporcost', porderdt_freight = '$txtporfreight'  ";
				 
		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 Purchased
		if ($PurchaseExists == 0)
			$query = $query.", Warehouse_Code = '".$lstWarehouse."', porderdt_heatno = '".$porderdt_heatno."', Item_Code = '".str_replace('\\','\\\\',trim(strtoupper($txtItemCode)))."' ";
		
		$query = $query." Where PorderDt_ID = ".$SPorDtId;		 

			//$message  = 	$query;			 
		//echo $query; exit;
		$result=mysql_query($query,$connection);
		if ($result){
			
			 if ( $config['log_file'] == 1){
							$query_history=" INSERT INTO temp_porderdt (PorderDt_ID,PorderDt_Remark, PorderDt_Quantity, Item_Unit2Qty, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_Discount,
							PorderDt_PriceTTC,PorderDt_PriceTTCBase1,PorderDt_PriceTTCBase2,PorderDt_DiscountAmount,PorderDt_Discountbase1,PorderDt_Discountbase2,porderdt_cost,porderdt_freight";
						
				if ($Module_ProjectDt == 1)
					$query_history = $query_history.", Project_Code  ";
				if ($Module_CostCenterDt == 1)	
					$query_history = $query_history.", CostCent_Code  ";
		
				$query_history= $query_history."temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status) ";
					
				$query_history=$query_history. " VALUES ( '".ereg_replace("'", "\'", trim($txtPorDtRemark))."', $txtPorDtQty, ',$txtPorDtQty2, $vPorDtPrice,$vPorDtPriceBase1,$vPorDtPriceBase2,
				$txtPorDtDiscount,$vPorDtPriceTTC,$vPorDtPriceTTCBase1,$vPorDtDiscAmtBase2,'$txtporcost','$txtporfreight'";
				
				if ($Module_ProjectDt == 1)
				$query_history = $query_history.", $ProjectCodeDt  ";
				if ($Module_CostCenterDt == 1)	
				$query_history = $query_history.", $CostCentCodeDt  ";

				$query_history= query_history.",now()
									, '".$User_Name."'
									, '".$_SESSION['dbName']."'
									, U')";
							$result=mysql_query($query_history,$connection_history);
					
							}
			
			
			fcommit();
			
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPorId, $PPorDate, $PPorVatChkbx, $vPorDiscount, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, 'U', $connection);
			$message  = $message . $CalculateResult;
			
			
		}else{
			$message  = mysql_error(); 
			frollback();
		}				
			
	}
}
	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$DeleteAllow = 0;
	$ErrorExists = 0;
	$message  = '';
	
	
	//Check Each PorderDt If Has RelatedId In PurchasesDt
	$query = " Select Count(PorderDt.PorderDt_id), Purchases.Purchase_reference ".
			 " From PorderDt, PurchasesDt, Purchases ".
			 " Where PorderDt.PorderDt_ID = ".$SPorDtId.
			 " And PurchasesDt.RelatedDt_Id = PorderDt.PorderDt_id ".
			 " And PurchasesDt.Journal_Type = 'PI' ".
			 " And PurchasesDt.Purchase_id = Purchases.Purchase_id ".
			 " Group By Purchases.Purchase_reference ";

	$result = selectData($connection, $query);
	$PurExists = $result[0];
		
	if ($PurExists > 0 ){
		$message  = 'Delete not allowed, purchase exists for this item with reference= '.$result[1];
		$DeleteAllow = 1;
	}
	
	

	//If No Constraints Exists On Delete
	if ($DeleteAllow == 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];
		

				
		$querypack = " SELECT PorderDt.Item_CodePacked, PorderDt.Item_code ".
					 " FROM Temp_PorderDt As PorderDt ".
					 " Where PorderDt.PorderDt_ID = ".$SPorDtId;
					 //" 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 TempPorderDt For Selected Record
			$query = " DELETE FROM Temp_PorderDt ".
					 " WHERE PorderDt_id = ".$SPorDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				
				 if ( $config['log_file'] == 1){
					 
					 
					 $select_history="select  Porder_id, Porder_Date, Item_code, from temp_porderdt where  PorderDt_id = ".$SPorDtId ;
					 $result=mysql_query($query_history,$connection);
					 $row=mysql_fetch_array(result);
					 $Porder_id=$row[0];
					 $Porder_Date=$row[1];
					 $Item_code=$row[2];
					// $PorderDt_id=row['0'];
					 
							$query_history=" INSERT INTO temp_porderdt (PorderDt_ID,Porder_id,Porder_Date, Item_code, 
								 temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status) ".
								 " VALUES ( ".$SPorDtId.",$Porder_id, $Porder_Date, $Item_code, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'D')";
							$result=mysql_query($query_history,$connection_history);
					
							}
						
				
				fcommit();
			}
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querypurdt = " Select PorderDt_ID, PorderDt.Item_CodePacked, PorderDt.Item_code  ".
						  " From Temp_PorderDt As PorderDt  ".
						  " Where PorderDt.Porder_ID = ".$SPorId.
						  " And PorderDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
						  //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						   
			$resultpurdt=mysql_query($querypurdt, $connection) or die(mysql_error());
			while($rowspurdt=mysql_fetch_array($resultpurdt)){		   
					
				$vPorDtId =	$rowspurdt[0];
					
				// Delete From TempPorderDt For Selected Record
				$query = " DELETE FROM Temp_PorderDt ".
						 " WHERE PorderDt_id = ".$vPorDtId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}  
				
				else  if ( $config['log_file'] == 1){
					 
					 
					 $select_history="select  Porder_id, Porder_Date, Item_code, from temp_porderdt where  PorderDt_id = ".$SPorDtId ;
					 $result=mysql_query($query_history,$connection);
					 $row=mysql_fetch_array(result);
					 $Porder_id=$row[0];
					 $Porder_Date=$row[1];
					 $Item_code=$row[2];
					// $PorderDt_id=row[0];
					 
							$query_history=" INSERT INTO temp_porderdt (PorderDt_ID,Porder_id,Porder_Date, Item_code, 
								 temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status) ".
								 " VALUES ( ".$SPorDtId.",$Porder_id, $Porder_Date, $Item_code, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'D')";
							$result=mysql_query($query_history,$connection_history);
					
							}
						
				  
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 ){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SPorId, $txtDate, $SPorVatChkbx, $txtPorDiscount, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, 'D', $connection);
			$message  = $message . $CalculateResult;
			
		} 
		
	
	} // End If No Constraints Found On Delete
	
	$txtPorId = $SPorId;
}

//Confirm Sales Order
else if ($mainmode == "unconfirmorder"){
	
	$query = "UPDATE Porder SET porder_confirmed = 0 ,approvedby='',porder_approvedstatus='P' WHERE Porder_id = '".$SPorId."'";

		$update=updateData($connection, $query, true);
		$message  = mysql_error();

}
else if(($mode == "confirmorder" || $mainmode == "confirmorder" || $mainmode == "confirmrequestitem") && $SPorId != ''){

	$confirm_flag     = 1;
	$porder_confirm   = 0;
	
	
	$query = " SELECT ifNull(Porder_confirmed,0) FROM Porder WHERE Porder_id = '".$SPorId."'";
	//echo "<br><br>".$query;exit;
	$result = selectData($connection, $query);
	$porder_confirm   = $result[0];
	
	
		
	
	if ($confirm_flag == 1 && $porder_confirm == 0) {
		$query = "UPDATE Porder SET porder_confirmed = 1 ,approvedby='".$_SESSION['useraccount']."',porder_approvedstatus='A',porder_approvedlevel=$approved WHERE Porder_id = '".$SPorId."'";

		if (updateData($connection, $query, true))
		{
		if ( $approved == 1 ) {
		    $query = "UPDATE Porderdt SET PorderDt_ApprovedStatus='A',PorderDt_ApprovedLevel=$approved WHERE Porder_id = '".$SPorId."'";
		 updateData($connection, $query, true);
		}
		
			$message = "Purchase Order Confirmed";
				 if ( $config['log_file'] == 1){

							$query_history=" INSERT INTO Porder (Porder_id,porder_confirmed,
								porder_history_date, porder_history_operator_id, porder_history_schema, porder_history_status) ".
								 " VALUES ( ".$SPorId.",1, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							}
							
			$emails = '';
			$queryEmails = "select email_address from ".$_SESSION['dbLabel'].".users_emails where user_account = '".$_SESSION['useraccount']."';";
			$resEmails = mysql_query($queryEmails, $connection);
			while ($rw = mysql_fetch_row($resEmails)){
				$emails = $rw[0].";".$emails;
			}
			
		if($emails != ''){
			$querybody = "select Porder_reference,Porder_date from porder where Porder_id = $SPorId";
			$resbody = mysql_query($querybody,$connection);
			$rowbody = mysql_fetch_row($resbody);
		
			$Subject="Purchase Order ".$rowbody[0]." is Confirmed ";
			
			$Body="<table><tr><td>Date : ".$rowbody[1]."</td></tr>\n";
			$Body=$Body."<tr><td>Purchase Order with Ref ".$rowbody[0]." is Confirmed By '".$_SESSION['useraccount']."'.";
			$Body=$Body."</td></tr>\n";
			$Body=$Body." </table> \n";

			$mail=sendmail($Subject,$Body,$emails,$SPreqId,$connection);	
		}				
		}
		else
			$message  = mysql_error();
		
	}



}
else if(($mode == "cancelorder" || $mainmode == "cancelorder" ) && $SPorId != ''){
	
	if ($Module_Grn != 1) {
			$sub_query = " Select Count(*) From PurchasesDt ".
						 " inner join porderdt on porderdt.porderdt_id = PurchasesDt.RelatedDt_Id ".
						 " Where porderdt.porder_id = '".$SPorId."' ".
						 " And PurchasesDt.Journal_Type = 'PI' ";
		} else {
			$sub_query = " Select Count(*) From GrnPurchasesDt ".
						 " inner join porderdt on porderdt.porderdt_id = GrnPurchasesDt.RelatedDt_Id ".
						 " Where porderdt.porder_id = '".$SPorId."' ".
						 " And GrnPurchasesDt.Journal_Type = 'PI' ";
		} //echo $sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		$PurchaseExists = 0;
		$PurchaseExists = $sub_result[0];
	
	
	if ($PurchaseExists > 0 ){
		$message  = 'Order COULD NOT be Cancelled, order purchased.';
	}
	 else {
		$query = "UPDATE Porderdt SET Porderdt_OldData = 1 WHERE Porder_id = ".$SPorId."";	

		//echo "<br><br>".$query;
		if (updateData($connection, $query, true)){
			
			 if ( $config['log_file'] == 1){

							$query_history=" INSERT INTO Porderdt (Porder_id,Porderdt_OldData,
								porderdt_history_date, porderdt_history_operator_id, porderdt_history_schema, porderdt_history_status) ".
								 " VALUES ( ".$SPorId.",1, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							}
			$query = "UPDATE Porder SET Porder_type = 'CA' WHERE Porder_id = ".$SPorId."";	
			
			if (updateData($connection, $query, true)){
				$message = "Order Cancelled";
				 if ( $config['log_file'] == 1){

							$query_history=" INSERT INTO Porder (Porder_id,Porder_type,
								porder_history_date, porder_history_operator_id, porder_history_schema, porder_history_status) ".
								 " VALUES ( ".$SPorId.",'CA', now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							}
					
				$emails = '';
				$queryEmails = "select email_address from ".$_SESSION['dbLabel'].".users_emails where user_account = '".$_SESSION['useraccount']."';";
				$resEmails = mysql_query($queryEmails, $connection);
				while ($rw = mysql_fetch_row($resEmails)){
					$emails = $rw[0].";".$emails;
				}
					
				if($emails != ''){
					$querybody = "select Porder_reference,Porder_date from porder where Porder_id = $SPorId";
					$resbody = mysql_query($querybody,$connection);
					$rowbody = mysql_fetch_row($resbody);
				
					$Subject="Purchase Order ".$rowbody[0]." is Cancelled ";
					
					$Body="<table><tr><td>Date : ".$rowbody[1]."</td></tr>\n";
					$Body=$Body."<tr><td>Purchase Order with Ref ".$rowbody[0]." is Cancelled By '".$_SESSION['useraccount']."'.";
					$Body=$Body."</td></tr>\n";
					$Body=$Body." </table> \n";

					$mail=sendmail($Subject,$Body,$emails,$SPreqId,$connection);	
				}				
				
			}else{
				$message = "Order COULD NOT be Cancelled";
			}
			
			
		}else{
			$message = "Order COULD NOT be Cancelled";
		}	
	}
	
}
else if ($mode == "" && $mainmode == "hidePorder" && $SPorId != ''){
 	$query = " update Porder set porder_hide = 1  WHERE Porder_id = ".$SPorId;
 	if (!updateData($connection, $query, true))		 
	$message  = mysql_error(); 
}
else if ($mode == "" && $mainmode == "unhidePorder" && $SPorId != ''){
	$query = " update Porder set porder_hide = 0  WHERE Porder_id = ".$SPorId;
 	if (!updateData($connection, $query, true))		 
	$message  = mysql_error();
}

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

	$DeleteAllow = 1;
	$message  = '';
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);
	
	 $sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(Porder_Date,'%d/%m/%Y') FROM Porder WHERE Porder_id = ".$SPorId;
		$result = selectData($connection, $query);
		$txtDate  = $result[0];
 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $DeleteAllow = 0;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $DeleteAllow = 0;
		if($DeleteAllow==0) $message  = 'Delete not allowed, Exceed Lock Period.';
	}
	
	//Check If Porder Is Posted
	$query = "SELECT ifNull(Porder_Posted,0) As PorderPosted FROM Porder WHERE Porder_id = ".$SPorId;
	$result = selectData($connection, $query);
	$PorPosted = $result[0];
	
	if ($PorPosted == 1 ){
		$message  = 'Delete not allowed, purchase order posted.';
		$DeleteAllow = 0;
	}
	
	if ($DeleteAllow == 1) {
		//Check Each PorderDt If Has RelatedId In PurchasesDt
		$query = " Select Count(PorderDt.PorderDt_id) ".
				 " From PorderDt ".
				 " Inner Join PurchasesDt on PorderDt.PorderDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PI' ".
				 " Where PorderDt.Porder_id = ".$SPorId;
				 
		$result = selectData($connection, $query);
		$PurExists = $result[0];
		
		if ($PurExists > 0 ){
			$message  = 'Delete not allowed, purchase exists for this purchase order.';
			$DeleteAllow = 0;
		}
	
	}
	
	if ($DeleteAllow == 1) {
		//Check Porder If Approved
		$query = " Select Count(Porder.Porder_id) ".
				 " From Porder ".
				 " Where Porder.Porder_id = '".$SPorId."' ".
				 " And upper(ifnull(porder_approvedstatus,'x')) = 'A' ";
					 
		$result = selectData($connection, $query);
		$PorApproveExists = $result[0];
			
		if ($PorApproveExists > 0 ){
			$message  = 'Delete not allowed, purchase order approved.';
			$DeleteAllow = 0;
		}
	}

	//If No Constraints Exists On Delete
	if ($DeleteAllow == 1) {
	    if($config['log_file'] == 1){
			$company = explode("_", $_SESSION['dbName']);
			$currCompany = strtoupper($company[0]);
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SPorId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'porder', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		// Delete From PorderDt For Selected Record
		$query = " DELETE FROM PorderDt ".
				 " WHERE Porder_id = ".$SPorId;
				 
				 
				 
				 
					 
		if (updateData($connection, $query, true)) {
			
			
			
			// Delete From Porder For Selected Record
			$query = " DELETE FROM Porder ".
					 " WHERE Porder_id = ".$SPorId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
				 
				else  if ( $config['log_file'] == 1){
					 
					 
					 $select_history="select  Porder_reference from Porder where Porder_id = ".$SPorId;;
					 $result=mysql_query($select_history,$connection_history);
					 $row=mysql_fetch_array(result);
					 $reference=$row[0];
					
					 
							$query_history=" INSERT INTO Porder (Porder_id,Porder_reference, Item_code, 
								 porder_history_date, porder_history_operator_id, porder_history_schema, porder_history_status) ".
								 " VALUES ( ".$SPorId.", $reference, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'D')";
							$result=mysql_query($query_history,$connection_history);
					
							}
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

//Delete Record Mode From Temp Tables
else if (($mode == "cancel" || $mainmode == "deletepending") && $SPorId != ''){

// Delete From TempPucrhaseCharges For Selected Record
	$query = " DELETE FROM Temp_PurchaseOrderCharges ".
			 " WHERE Purchase_id = ".$SPorId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			 
			 
			  if ( $config['log_file'] == 1){
					 
					 
					 $select_history="select  Purchase_id, Ledger_NumberDebit from Temp_PurchaseOrderCharges where Purchase_id = ".$SPorId;
					 $result=mysql_query($select_history,$connection);
					 $row=mysql_fetch_array(result);
					 $Purchase_id=$row[0];
					 $Ledger_NumberDebit=$row[1];
					
					 
							$query_history=" INSERT INTO Temp_PurchaseOrderCharges (Purchase_id,Ledger_NumberDebit,
								 temp_purchaseordercharges_history_date, temp_purchaseordercharges_history_operator_id, temp_purchaseordercharges_history_schema, temp_purchaseordercharges_history_status) ".
								 " VALUES ( ".$SPorId.", $Ledger_NumberDebit, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'D')";
							$result=mysql_query($query_history,$connection_history);
					
							}
			 
	// Delete From TempPorderDt For Selected Record
	$query = " DELETE FROM Temp_PorderDt ".
			 " WHERE Porder_id = ".$SPorId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				
				  
			  if ( $config['log_file'] == 1){
					 
					 
					 $select_history="select  Purchase_id, Ledger_NumberDebit from Temp_PorderDt where Purchase_id = ".$SPorId;
					 $result=mysql_query($select_history,$connection);
					 $row=mysql_fetch_array(result);
					 $Purchase_id=$row[0];
					 $Ledger_NumberDebit=$row[1];
					
					 
							$query_history=" INSERT INTO Temp_PorderDt (Purchase_id,Ledger_NumberDebit,
											 temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status) ".
								 " VALUES ( ".$SPorId.", $Ledger_NumberDebit, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'D')";
							$result=mysql_query($query_history,$connection_history);
					
							}
	if (updateData($connection, $query, true)) {
		// Delete From TempPorder For Selected Record
		$query = " DELETE FROM Temp_Porder ".
				 " WHERE Porder_id = ".$SPorId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		else  if ( $config['log_file'] == 1){
					 
					 
					 $select_history="select  Porder_reference from temp_Porder where Porder_id = ".$SPorId;;
					 $result=mysql_query($query_history,$connection_history);
					 $row=mysql_fetch_array(result);
					 $reference=$row[0];
					
					 
							$query_history=" INSERT INTO temp_Porder (Porder_id,Porder_reference, Item_code, 
								 temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status) ".
								 " VALUES ( ".$SPorId.", $reference, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'D')";
							$result=mysql_query($query_history,$connection_history);
					
							}
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if($mainmode == "search" && $SPorId != ''){
	
	$EditAllow   = 1;
	$ErrorExists = 0;
	$message  = '';
	
	if($Module_PorderAutoApprove ==  1){
		//Check Each PorderDt If Has RelatedId In PurchasesDt
		$query = " Select Count(PorderDt.PorderDt_id) ".
				 " From PorderDt ".
				 " Inner Join PurchasesDt on PorderDt.PorderDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PI' ".
				 " Where PorderDt.Porder_id = ".$SPorId;
					 
			$result = selectData($connection, $query);
			$PurExists = $result[0];
				
			if ($PurExists > 0 ){
				$message  = 'Edit not allowed, purchase exists for this purchase order.';
				$EditAllow = 0;
			}
		}
		
		//Check Porder If Approved
		if($Module_PorderAutoApprove ==  0){
		 $query = " Select Count(Porder.Porder_id) ".
				 " From Porder ".
				 " Where Porder.Porder_id = '".$SPorId."' ".
				 " And upper(ifnull(porder_approvedstatus,'x')) = 'A' ";
					 
			$result = selectData($connection, $query);
			$PorApproveExists = $result[0];
				
			if ($PorApproveExists > 0 ){
				$message  = 'Edit not allowed, purchase order approved.';
				$EditAllow = 0;
			}
		}
	
	  

	//If No Constraints Exists On Edit
	if ($EditAllow == 1) {
	 
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_porder (Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, Costcent_code, Supplier_code, ".
				 " Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, Porder_Status, Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, ".
				 " Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, ".
				 " Porder_Tax1, Porder_Tax1Base1, Porder_Tax1Base2, Porder_Tax2, Porder_Tax2Base1, Porder_Tax2Base2, Porder_Tax3, Porder_Tax3Base1, Porder_Tax3Base2,  ".
				 " Porder_Tax4, Porder_Tax4Base1, Porder_Tax4Base2, Porder_Tax5, Porder_Tax5Base1, Porder_Tax5Base2, Porder_Type, Porder_Confirmed, Porder_BelongsToGroup, Logged_Code, ".
				 " PRqst_id, Prequest_Ref, porder_paymentcondition, porder_downpayment, porder_downperc, porder_downamount, user_account,Porder_Charges,Porder_ChargesBase1,Porder_ChargesBase2,Porder_VatCharges,Porder_VatChargesBase1,Porder_VatChargesBase2 ".
				 " ,porder_othercharges,Confirmed_date,shippingmethod_id, porder_actualdate, approvedby, supplier_code1) ".
				 " SELECT Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, Costcent_code, Supplier_code, ".
				 " Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, Porder_Status, Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, ".
				 " Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, ".
				 " Porder_Tax1, Porder_Tax1Base1, Porder_Tax1Base2, Porder_Tax2, Porder_Tax2Base1, Porder_Tax2Base2, Porder_Tax3, Porder_Tax3Base1, Porder_Tax3Base2,  ".
				 " Porder_Tax4, Porder_Tax4Base1, Porder_Tax4Base2, Porder_Tax5, Porder_Tax5Base1, Porder_Tax5Base2, Porder_Type, Porder_Confirmed, Porder_BelongsToGroup, ".
				 " '".$_SESSION['useraccount']."', PRqst_id, Prequest_Ref, porder_paymentcondition, porder_downpayment, porder_downperc, porder_downamount, user_account ,Porder_Charges,Porder_ChargesBase1,Porder_ChargesBase2,Porder_VatCharges,Porder_VatChargesBase1,Porder_VatChargesBase2".
				 " ,porder_othercharges,Confirmed_date,shippingmethod_id,  porder_actualdate, approvedby, supplier_code1 ".
				 " FROM Porder ".
				 " WHERE Porder_id = ".$SPorId;
		// echo $query; exit;
		if (!updateData($connection, $query, true)) {
			$ErrorExists = 1;
			$message  = mysql_error(); 	
		}
		
		else if ( $config['log_file'] == 1){
					 
					 
					 $query_history = " INSERT INTO temp_porder (Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, Costcent_code, Supplier_code, ".
				 " Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, Porder_Status, Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, ".
				 " Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, ".
				 " Porder_Tax1, Porder_Tax1Base1, Porder_Tax1Base2, Porder_Tax2, Porder_Tax2Base1, Porder_Tax2Base2, Porder_Tax3, Porder_Tax3Base1, Porder_Tax3Base2,  ".
				 " Porder_Tax4, Porder_Tax4Base1, Porder_Tax4Base2, Porder_Tax5, Porder_Tax5Base1, Porder_Tax5Base2, Porder_Type, Porder_Confirmed, Porder_BelongsToGroup, Logged_Code, ".
				 " PRqst_id, Prequest_Ref, porder_paymentcondition, porder_downpayment, porder_downperc, porder_downamount, user_account,Porder_Charges,Porder_ChargesBase1,Porder_ChargesBase2,Porder_VatCharges,Porder_VatChargesBase1,Porder_VatChargesBase2 ".
				 " ,porder_othercharges,Confirmed_date,shippingmethod_id, porder_actualdate, approvedby,temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status) ".
				 " SELECT Porder_ID, Porder_Reference, Porder_Date, Porder_RequestDate, Porder_RequestBy, Currency_Code, Project_Code, Costcent_code, Supplier_code, ".
				 " Porder_SupplierContact, Porder_Remark, Porder_Posted, Expiry_date, Porder_Import, Porder_Status, Status_Remark, Porder_DeliveryPlace, Porder_DeliveryContact,  ".
				 " Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable, Porder_NoneTaxableBase1, Porder_NoneTaxableBase2, Porder_DiscountAmount, Porder_DiscountBase1, ".
				 " Porder_DiscountBase2, Porder_DiscountPer, Porder_Total, Porder_TotalBase1, Porder_TotalBase2, Porder_Vat, Porder_VatBase1, Porder_VatBase2, Porder_VATChckbx, ".
				 " Porder_Tax1, Porder_Tax1Base1, Porder_Tax1Base2, Porder_Tax2, Porder_Tax2Base1, Porder_Tax2Base2, Porder_Tax3, Porder_Tax3Base1, Porder_Tax3Base2,  ".
				 " Porder_Tax4, Porder_Tax4Base1, Porder_Tax4Base2, Porder_Tax5, Porder_Tax5Base1, Porder_Tax5Base2, Porder_Type, Porder_Confirmed, Porder_BelongsToGroup, ".
				 " '".$_SESSION['useraccount']."', PRqst_id, Prequest_Ref, porder_paymentcondition, porder_downpayment, porder_downperc, porder_downamount, user_account ,Porder_Charges,Porder_ChargesBase1,Porder_ChargesBase2,Porder_VatCharges,Porder_VatChargesBase1,Porder_VatChargesBase2".
				 " ,porder_othercharges,Confirmed_date,shippingmethod_id,  porder_actualdate, approvedby, now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'I'".
				 " FROM Porder ".
				 " WHERE Porder_id = ".$SPorId;
					
					 
							
			if (!updateData($connection_history, $query_history, true)) {
				$message  = mysql_error(); 	
		}
		//echo $query_history;
	//	exit;
					
							}
		
				
		//echo $message.$query; exit;				 
			
		if ($ErrorExists == 0) {
			
			$query = " INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
					 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
					 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
					 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code, Prequest_Ref, RelatedDt_ID, PorderDt_ApprovedStatus, PorderDt_ApprovedLevel,PorderDt_VatCharge,PorderDt_VatChargeBase1, ".
					 " PorderDt_VatChargeBase2,PorderDt_Charges,PorderDt_ChargesBase1,PorderDt_ChargesBase2, PorderDt_heatNo,Approval_date,porderdt_cost,porderdt_freight ) ".
					 " SELECT PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
					 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
					 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
					 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, '".$_SESSION['useraccount']."', Prequest_Ref, RelatedDt_ID, PorderDt_ApprovedStatus, PorderDt_ApprovedLevel  ".
					 " ,PorderDt_VatCharge,PorderDt_VatChargeBase1,PorderDt_VatChargeBase2,PorderDt_Charges,PorderDt_ChargesBase1,PorderDt_ChargesBase2,PorderDt_heatNo,Approval_date,porderdt_cost,porderdt_freight ".
					 " FROM PorderDt ".
					 " WHERE Porder_id = ".$SPorId;
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 			
			else if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_porderdt (PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
					 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
					 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
					 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, Logged_Code, Prequest_Ref, RelatedDt_ID, PorderDt_ApprovedStatus, PorderDt_ApprovedLevel,PorderDt_VatCharge,PorderDt_VatChargeBase1, ".
					 " PorderDt_VatChargeBase2,PorderDt_Charges,PorderDt_ChargesBase1,PorderDt_ChargesBase2, PorderDt_heatNo,Approval_date,porderdt_cost,porderdt_freight 
					 ,temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status) ".
					 " SELECT PorderDt_ID, Porder_ID, Currency_Code, Porder_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
					 " Item_QtyPacked, PorderDt_Quantity, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, PorderDt_PriceTTCBase2, ".
					 " PorderDt_Discount, PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2, Item_VAT, PorderDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
					 " Porderdt_OldData, Item_UnitCoef, Item_Unit2Qty, '".$_SESSION['useraccount']."', Prequest_Ref, RelatedDt_ID, PorderDt_ApprovedStatus, PorderDt_ApprovedLevel  ".
					 " ,PorderDt_VatCharge,PorderDt_VatChargeBase1,PorderDt_VatChargeBase2,PorderDt_Charges,PorderDt_ChargesBase1,PorderDt_ChargesBase2,PorderDt_heatNo,Approval_date,porderdt_cost,porderdt_freight,
												now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'I'".
					 " FROM PorderDt ".
					 " WHERE Porder_id = ".$SPorId;
			
					 
							if (!updateData($connection_history, $query_history, true))
							$message  = mysql_error(); 	
				//	echo $query_history;exit;
							
							}
				$query = " INSERT INTO temp_purchaseordercharges (Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, ".
				 " Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, Logged_Code ) ".
				 " SELECT Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, ".
				 " Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, '".$_SESSION['useraccount']."' ".
				 " FROM Purchaseordercharges ".
				 " WHERE Purchase_id = ".$SPorId;
		
			if (!updateData($connection, $query, true))
			$message  = mysql_error(); 
		  else if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_purchaseordercharges (Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, ".
				 " Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, Logged_Code,
				 temp_purchaseordercharges_history_date, temp_purchaseordercharges_history_operator_id, temp_purchaseordercharges_history_schema, temp_purchaseordercharges_history_status ) ".
				 " SELECT Purchase_id, Ledger_NumberDebit, Ledger_NumberCredit, Currency_code, Charges_Amount, Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, ".
				 " Charges_isVat, Charges_GenerateDebit, Charge_Type, Synchronized, Charges_isSubjToCharge, '".$_SESSION['useraccount']."',now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'I' ".
				 " FROM Purchaseordercharges ".
				 " WHERE Purchase_id = ".$SPorId;
			
					 
							
							if (!updateData($connection_history, $query_history, true))
			$message  = mysql_error(); 
					//echo $query_history;
				//	exit;
							} 
		  
		}  
		
	}
}


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

	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];
	
	if (empty($txtPorStatus))
		$txtPorStatus = 'A';	
	if (empty($txtPorCategory))
		$txtPorCategory = 0;
	if (empty($txtPorDiscountAmt))
		$txtPorDiscountAmt = 0;
	if (empty($txtPorDiscount))
		$txtPorDiscount = 0;
	if (empty($txtPorder_Othercharges))
		$txtPorder_Othercharges = 0;
	$txtCostCentCode = "".$txtCostCentCode;		
	if ($txtCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
	
	$txtProjectCode = "".$txtProjectCode;		
	if ($txtProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
		
	if($shippingmethod	== '') $shippingmethod = "NULL";
	
	$vPorTotal = 0;
	$vPorDisAmt = 0;
	
	$vPorDtPriceTTC      = 0;
	$vPorDtPriceTTCBase1 = 0;
	$vPorDtPriceTTCBase2 = 0;					
	$vPorDtPrice      	 = 0;
	$vPorDtPriceBase1 	 = 0;
	$vPorDtPriceBase2 	 = 0;
	$vPorDtDiscAmt       = 0;
	$vPorDtDiscAmtBase1  = 0;
	$vPorDtDiscAmtBase2  = 0;
	
	$SaveAllow   = 1;
	$ErrorExists = 0;
	
	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_porderdt ".
				 " Where Porder_ID = '".$SPorId."' ".
				 " 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($txtPorder_Othercharges != ''){
		$queryothercharges = "update temp_porder set porder_othercharges = $txtPorder_Othercharges where Porder_ID = '".$SPorId."' ";
		$resothercharges = mysql_query($queryothercharges,$connection);
		
		
		
		if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_porder (Porder_ID, porder_othercharges ".
					", temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status)	
					values('".$SPorId."',$txtPorder_Othercharges
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U') ";
				
			
					 
							
							$result=mysql_query($query_history,$connection_history);
					
							} 
	}
	    $queryup = "update temp_porder set shippingmethod_id = $shippingmethod where Porder_ID = '".$SPorId."' ";
		$resup = mysql_query($queryup,$connection);
		
		if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_porder (Porder_ID, shippingmethod_id ".
					", temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status)	
					values('".$SPorId."',$shippingmethod
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U') ";
				
			
					 
							
							$result=mysql_query($query_history,$connection_history);
				//	echo "d";exit;
							}
		
	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(PorderDt_Quantity,0)) As PorderDtQuantity ".
								  " From temp_porderdt ".
								  " Where Porder_ID = '".$SPorId."' ".
								  " 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) $SaveAllow = 0;
					
					
				}
			}		  
			
		}
	}
	
	//Check For Supplier, 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 ($txtSupplier != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$txtSupplier."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Supplier Code.';
		}
	}
			//Check For Price Before Insert
	if($Module_PurchaseZero==1){
		$sub_query = " Select 1  ".
					 " From Temp_PorderDt As PorderDt  ".
					 " Where PorderDt.Porder_ID = ".$SPorId." And PorderDt_Price = 0";
						  
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] != 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item Price 0.';
		}
	}
	
	if ($ErrorExists == 0) {
		//Checking For Qty Not To Be Zero
		$sub_query = " Select Count(*) From ( ".
					 " 	Select PorderDt.PorderDt_ID, PorderDt.Item_code, ifNull(PorderDt_Quantity,0) as PorderDt_Quantity ".
					 " 	From Temp_PorderDt As PorderDt ".
					 " 	Where PorderDt.Porder_ID = ".$SPorId.
					 " 	And ifNull(PorderDt_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 ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
		
		//Update Detail Amount Columns In Case Currency Is Modified
		$sub_query = " Select PorderDt_Id, Currency_Code, ifNull(PorderDt_Price,0), ifNull(PorderDt_PriceBase1,0), ifNull(ProderDt_PriceBase2,0), ".
					 " ifNull(PorderDt_PriceTTC,0), ifNull(PorderDt_PriceTTCBase1,0), ifNull(PorderDt_PriceTTCBase2,0), ifNull(PorderDt_DiscountAmount,0), ".
					 " ifNull(PorderDt_DiscountBase1,0), ifNull(PorderDt_DiscountBase2,0) ".
					 " From temp_porderdt ".
					 " Where Porder_ID = ".$SPorId;	
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
					
			$vPorDtPrice         = $sub_row[2];
			$vPorDtPriceBase1    = $sub_row[3];
			$vPorDtPriceBase2    = $sub_row[4];
			$vPorDtPriceTTC      = $sub_row[5];
			$vPorDtPriceTTCBase1 = $sub_row[6];
			$vPorDtPriceTTCBase2 = $sub_row[7];
			$vPorDtDiscAmt       = $sub_row[8];
			$vPorDtDiscAmtBase1  = $sub_row[9];
			$vPorDtDiscAmtBase2  = $sub_row[10];
			
			if ($sub_row[1] != $txtCurr) {
				$vPorDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPorDtPrice, $connection);
				$vPorDtPriceTTC = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPorDtPriceTTC, $connection);
				$vPorDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vPorDtDiscAmt, $connection);
						
				$vPorDtPriceBase1    = ($vPorDtPrice*$rate_dt)/$rate_dt1;
				$vPorDtPriceBase2    = ($vPorDtPrice*$rate_dt)/$rate_dt2;
				$vPorDtPriceTTCBase1 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt1;
				$vPorDtPriceTTCBase2 = ($vPorDtPriceTTC*$rate_dt)/$rate_dt2;
				$vPorDtDiscAmtBase1  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt1;
				$vPorDtDiscAmtBase2  = ($vPorDtDiscAmt*$rate_dt)/$rate_dt2;
				
					
				$sub_query1 = " UPDATE temp_porderdt SET  ".
							  " Currency_Code = '".$txtCurr."', ".
							  " PorderDt_Price = $vPorDtPrice, PorderDt_PriceBase1 = $vPorDtPriceBase1, ProderDt_PriceBase2 = $vPorDtPriceBase2, ".
							  " PorderDt_PriceTTC = $vPorDtPriceTTC, PorderDt_PriceTTCBase1 = $vPorDtPriceTTCBase1, PorderDt_PriceTTCBase2 = $vPorDtPriceTTCBase2, ".
							  " PorderDt_DiscountAmount = $vPorDtDiscAmt, PorderDt_DiscountBase1 = $vPorDtDiscAmtBase1, PorderDt_DiscountBase2 = $vPorDtDiscAmtBase2 ".
							  " Where PorderDt_ID = ".$sub_row[0];
					
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 
				else if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_porderdt (PorderDt_ID, Currency_Code, ProderDt_PriceBase2, PorderDt_PriceTTC, PorderDt_PriceTTCBase1, 
					 Charges_AmountBase1, Charges_AmountBase2, Charges_distoption, ".
				 " PorderDt_PriceTTCBase2, PorderDt_DiscountAmount, PorderDt_DiscountBase1, PorderDt_DiscountBase2,
					temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status)	
					values(".$sub_row[0].",'".$txtCurr."',$vPorDtPrice,$vPorDtPriceBase1,$vPorDtPriceBase2,$vPorDtPriceTTC,$vPorDtPriceTTCBase1,$vPorDtPriceTTCBase2
					$vPorDtDiscAmt,$vPorDtDiscAmtBase1,$vPorDtDiscAmtBase2
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U') ";
				
			
					 
							
							$result=mysql_query($query_history,$connection_history);
				//	echo $query_history;
				//	exit;
							} 	
			}
					
		}  //End Loop of PorderDt Query
		
		//Distribute The Total Discount On Detail Table
		$sub_query3 = " Select Sum((ifNull(PorderDt_Quantity,0)*ifNull(PorderDt_Price,0))-((ifNull(PorderDt_Quantity,0)*ifNull(PorderDt_Price,0)*ifNull(PorderDt_Discount,0))/100)) As Total ".
					  " From Temp_PorderDt ".
					  " Where Porder_ID = ".$SPorId;
		$sub_result3 = selectData($connection, $sub_query3);
		$vPorTotal   = $sub_result3[0];	
		$vPorDisAmt	 = $txtPorDiscountAmt;
		
		$sub_query4 = " Select PorderDt_ID,  ".
					  " ((ifNull(PorderDt_Quantity,0)*ifNull(PorderDt_Price,0))-((ifNull(PorderDt_Quantity,0)*ifNull(PorderDt_Price,0)*ifNull(PorderDt_Discount,0))/100)) As Total ".
					  " From Temp_PorderDt As PorderDt  ".
					  " Where PorderDt.Porder_ID = ".$SPorId;
					  //" And PorderDt.Logged_Code = '".$PLoggedCode."' ";
				   
		//echo $query; 
		$sub_result4=mysql_query($sub_query4,$connection) or die(mysql_error());
		while($sub_rows4=mysql_fetch_array($sub_result4)){
		
			$vPorDtId 	 = $sub_rows4[0];
			$vPorDtTotal = $sub_rows4[1];
			
			
			
			$vPorDtDiscAmt	    = 0;
			$vPorDtDiscAmt 		= ($vPorDtTotal/$vPorTotal)*$vPorDisAmt;
			$vPorDtDiscAmtBase1 = ($vPorDtDiscAmt*$rate_dt)/$rate_dt1;
			$vPorDtDiscAmtBase2 = ($vPorDtDiscAmt*$rate_dt)/$rate_dt2;
			
			$queryupd =  " UPDATE temp_porderdt SET PorderDt_DiscountAmount = $vPorDtDiscAmt, ".
						 " PorderDt_DiscountBase1 = $vPorDtDiscAmtBase1, PorderDt_DiscountBase2 = $vPorDtDiscAmtBase2  ".
						 " Where PorderDt_ID = ".$vPorDtId;
						 //" And Logged_Code = '".$PLoggedCode."' ";
			//echo $queryupd; exit;
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 
			else if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_porderdt (PorderDt_ID,".
				 "  PorderDt_DiscountAmount, PorderDt_DiscountBase1, PorderDt_DiscountBase2,
					temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status)	
					values(".$sub_row[0].",$vPorDtDiscAmt,$vPorDtDiscAmtBase1,$vPorDtDiscAmtBase2
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U') ";
				
			
					 
							
							$result=mysql_query($query_history,$connection_history);
					
							} 	

		}
				 
										 
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SPorId, $txtDate, $SPorVatChkbx, $txtPorDiscount, $txtPorDiscountAmt, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, 'P', $connection);
		$message  = $message . $CalculateResult;
		
		
		$sub_query2 = " UPDATE temp_porderdt SET ".
					  " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', ".
					  " Porder_Date = '".insertMySQLDate($txtDate)."' ";
					  
		if ($Module_ProjectDt != 1)
			$sub_query2 = $sub_query2.", Project_Code = $ProjectCode ";
		if ($Module_CostCenterDt != 1)	
			$sub_query2 = $sub_query2.", CostCent_Code = $CostCentCode ";
			
		$sub_query2 = $sub_query2." WHERE Porder_id = $SPorId ";
		
		//echo $sub_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
		else if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_porderdt (PorderDt_ID,".
				 "  Supplier_code, Porder_Date";
				 
				 
				 
			if ($Module_ProjectDt != 1)
				$query_history = $query_history.", Project_Code  ";
			if ($Module_CostCenterDt != 1)	
				$query_history = $query_history.", CostCent_Code";
			
			$query_history=$query_history."temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status)
			values('".ereg_replace("'", "\'", trim($txtSupplier))."','".insertMySQLDate($txtDate)."'";
										
			if ($Module_ProjectDt != 1)
				$query_history = $query_history.", $ProjectCode  ";
			if ($Module_CostCenterDt != 1)	
				$query_history = $query_history.", $CostCentCode";
								
			$query_history=$query_history.",now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U') ";
				
			
					 
							
							$result=mysql_query($query_history,$connection_history);
					
							} 

		if (empty($porder_downpayment))	$porder_downpayment = 0;
		if (empty($porder_downperc))	$porder_downperc = 0;
		if (empty($porder_downamount))	$porder_downamount = 0;
						 
		$query = " UPDATE temp_porder SET ".
				 " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', Porder_Date = '".insertMySQLDate($txtDate)."', ".
				 " Supplier_code1 = '".ereg_replace("'", "\'", trim($txtSupplier1))."',Porder_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
				 " Porder_RequestDate = '".insertMySQLDate($txtRequestDate)."'
				 , Porder_RequestBy = '".ereg_replace("'", "\'", trim($txtRequestBy))."', 
				  Porder_SupplierContact = '".ereg_replace("'", "\'", trim($txtSupplierContact))."',  Expiry_date = '".insertMySQLDate($txtExpiryDate)."', ".
				 " Porder_DeliveryPlace = '".ereg_replace("'", "\'", trim($txtDeliveryPlace))."',  Porder_DeliveryContact = '".ereg_replace("'", "\'", trim($txtDeliveryContact))."', ".
				 " Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode, Porder_VATChckbx = $SPorVatChkbx, ".
				 " Porder_Import = '".$txtPorCategory."', Porder_Status =  '".$txtPorStatus."', ".
				 " Status_Remark = '".ereg_replace("'", "\'", trim($txtStatusRemark))."', ".
				 " porder_paymentcondition = '".ereg_replace("'", "\'", trim($txtPaymentCondidions))."', ".
				 " porder_downpayment = $porder_downpayment, porder_downperc = $porder_downperc, porder_downamount = $porder_downamount ".
				 " ,porder_othercharges = $txtPorder_Othercharges ".
				 " ,approvedby = '$approvedby' ".
				 " ,porder_actualdate = '".insertMySQLDate($_POST['porder_actualdate'])."' ".
				 "  WHERE Porder_ID = $SPorId ";
		
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
				
		if ($result){
			
			
			 if ( $config['log_file'] == 1){
					 
					 
					 $query_history =  " INSERT INTO temp_porder (Porder_ID,Supplier_code".
				 "  ,Porder_Date,Porder_Remark,Porder_RequestDate,Porder_RequestBy,Porder_SupplierContact,Expiry_date,Porder_DeliveryPlace,Porder_DeliveryContact
				 ,Currency_Code,Project_Code,Costcent_code,Porder_VATChckbx,Porder_Import,Porder_Status,Status_Remark,porder_paymentcondition,porder_downpayment,
				 porder_downperc,porder_downamount,porder_othercharges,approvedby,porder_actualdate,porder_actualdate,
				 temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status
				 )	
					values($SPorId,'".ereg_replace("'", "\'", trim($txtSupplier))."','".insertMySQLDate($txtDate)."','".ereg_replace("'", "\'", trim($txtRemark))."'
					, '".insertMySQLDate($txtRequestDate)."','".ereg_replace("'", "\'", trim($txtRequestBy))."', '".ereg_replace("'", "\'", trim($txtSupplierContact))."',
					'".insertMySQLDate($txtExpiryDate)."','".ereg_replace("'", "\'", trim($txtDeliveryPlace))."','".ereg_replace("'", "\'", trim($txtDeliveryContact))."', 
					'".$txtCurr."',$ProjectCode,$CostCentCode,$SPorVatChkbx ,'".$txtPorCategory."','".$txtPorStatus."','".ereg_replace("'", "\'", trim($txtStatusRemark))."',
					'".ereg_replace("'", "\'", trim($txtPaymentCondidions))."',$porder_downpayment,$porder_downperc,$porder_downamount,$txtPorder_Othercharges,$approvedby,
					'".insertMySQLDate($_POST['porder_actualdate'])."'
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
				
			
					 
							
							$result=mysql_query($query_history,$connection_history);
					
							} 	
						
					
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcent_code  FROM Porder WHERE Porder_id = $SPorId ";
			$result  = selectData($connection, $query);
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From Temp_Porder where Porder_ID = '".$SPorId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			$query_checkDelivery  = "select count(*) as PurchaseOrderExist from porder where porder_id = '$SPorId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($PurchaseOrderExist > 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_TempPorder('".$SMode."', ".$SPorId.", '".$_SESSION['useraccount']."') FROM Dual ";
				$result = selectData($connection, $query);
				$result = $result[0];
					
				if ($result != 0){
					fcommit();
						
					$query   = " SELECT Porder_Reference, Costcent_code, Project_Code FROM Porder WHERE Porder_id = $SPorId ";
					$result  = selectData($connection, $query);
					$vPorRef = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
					
					$existCode = 0;
					if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vPorRef != ''){
						$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 && $vPorRef != ''){
						$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 ($vPorRef == '' || ($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();
						$vPorRef = get_nextsequence('porder_reference',$vProjCostCent,$connection);	
						fcommit();
							
						$query = " UPDATE Porder SET Porder_Reference = $vPorRef ";
								 
								 
							 
						if ($Module_PorderAutoApprove == 1){
							$query = $query.", porder_approvedlevel = 1, porder_approvedstatus = 'A' ";
						}
						if($txtPorder_Othercharges != ''){
						$query = $query.",porder_othercharges = $txtPorder_Othercharges ";
						}
						$query = $query." WHERE Porder_id = $SPorId ";
						// echo "<br> 3091 - ".$query; 
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						
						else if ( $config['log_file'] == 1){


							$query_history =  " INSERT INTO Porder (Porder_id,Porder_Reference";

							if ($Module_PorderAutoApprove == 1){
								$query_history = $query_history.", porder_approvedlevel , porder_approvedstatus ";
							}
							if($txtPorder_Othercharges != ''){
								$query_history = $query_history.",porder_othercharges ";
							} 

							$query_history=$query_history.",  porder_history_date, porder_history_operator_id, porder_history_schema, porder_history_status)	
							values($SPorId,$vPorRef";
							
							if ($Module_PorderAutoApprove == 1){
								$query_history = $query_history.", 1 , 'A' ";
							}
							if($txtPorder_Othercharges != ''){
								$query_history = $query_history.",$txtPorder_Othercharges ";
							} 
							$query_history=$query_history.",now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							} 	
							
							
						if ($Module_PorderAutoApprove == 1){
							$query = " UPDATE PorderDt SET porderdt_approvedlevel = 1, porderdt_approvedstatus = 'A' WHERE Porder_id = $SPorId ";
								
							if (!updateData($connection, $query, true)) 
								$message  = mysql_error();	
							else  if ( $config['log_file'] == 1){
							
					 $query_history =  " INSERT INTO PorderDt (Porder_id,porderdt_approvedlevel,porderdt_approvedstatus".
									",porderdt_history_date, porderdt_history_operator_id, porderdt_history_schema, porderdt_history_status)	
									values($SPorId,porderdt_approvedlevel,porderdt_approvedstatus
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							} 	
						}
					}
					if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SPorId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'porder', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}	
				
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempPorder Function'; 
					frollback();
				}
			}
			
		} else{
			$message  = mysql_error(); 
			frollback();
		}	
		
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllow == 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($mainmode == "copyrequest" or $mode == "copyrequest"){

	$ErrorExists = 0;
	
	if ($PurReqId !='') {
		$query = "select PRqst_RequestBy,PRqst_remark,Project_Code,Costcent_code,Status_Remark,PRqst_DeliveryPlace,PRqst_DeliveryContact,PRqst_reference
					from prequest where PRqst_id= '".$PurReqId."'";
		$result=mysql_query($query,$connection) or die(mysql_error());			
		while($rows=mysql_fetch_array($result)){
			extract($rows);
		}
	}
	else if($txtPrqstid != '') {
		$PurReqId = $txtPrqstid; 
		
		$query = "select PRqst_RequestBy,PRqst_remark,Project_Code,Costcent_code,Status_Remark,PRqst_DeliveryPlace,PRqst_DeliveryContact,PRqst_reference
					from prequest where PRqst_id= '".$PurReqId."'";
		$result=mysql_query($query,$connection) or die(mysql_error());			
		while($rows=mysql_fetch_array($result)){
			extract($rows);
		}
	}
	else if($SSaDtId != '') {
		$PurReqDtId = explode(',', $SSaDtId);
		$PurReqDtId = $PurReqDtId[0];
		
		$query = "select PRqst_id, PRqst_RequestBy,PRqst_remark,Project_Code,Costcent_code,Status_Remark,PRqst_DeliveryPlace,PRqst_DeliveryContact,PRqst_reference
					from prequest where PRqst_id = (select PRqst_id from prequestdt where PRqstdt_id = '".$PurReqDtId."' limit 1)";
		$result=mysql_query($query,$connection) or die(mysql_error());			
		while($rows=mysql_fetch_array($result)){
			extract($rows);
			
			$PurReqId = $PRqst_id;
		}
	}
	
	if($PorId == ''){

		$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PPorCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PPorCurr."' )";
		$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];

		
		
		fbegin();	
		$vPurId = get_nextsequence('Porder_Id','',$connection);	
		fcommit();
		
		fbegin();	
		$prqstref = get_nextsequence('PRequest_Reference','',$connection);	
		fcommit();
		$PGeneratedId = $vPurId;
		$TransType = 'PO';
		
			$sub_query = " Select ifNull(Supplier_VAT,0) From Suppliers ".
						 " Where Ledger_Number = '".$PPorSupplier."'";

			$sub_result = selectData($connection, $sub_query);
			$SupplierVAT = $sub_result[0];
			if (empty($SupplierVAT)) $SupplierVAT = 0;
		
			if ($PPorRequestBy == '')
					$PPorRequestBy = $PRqst_RequestBy;
			$PPorProjectCode = "".$PPorProjectCode;
			if ($PPorProjectCode == '')
					$PPorProjectCode = $Project_Code;
			$PPorCostCentCode = "".$PPorCostCentCode;	
			if ($PPorCostCentCode == '')
					$PPorCostCentCode = $Costcent_code;
			if ($PPorDeliveryPlace == '')
					$PPorDeliveryPlace = $PRqst_DeliveryPlace;
			if ($PPorDeliveryContact == '')
					$PPorDeliveryContact = $PRqst_DeliveryContact;
			if ($PPorRemark == '')
					$PPorRemark = $PRqst_remark;
			if ($PPorStatusRemark == '')
					$PPorStatusRemark = $Status_Remark;		
		 
			$query = " INSERT INTO Temp_porder(Porder_id, Porder_reference, Porder_date, Porder_RequestDate,Porder_RequestBy, Porder_remark, 
					   supplier_code, Porder_SupplierContact, Currency_code, Project_Code, Costcent_code, logged_code,
					   Porder_Type,PRqst_id,Porder_DeliveryPlace,Porder_DeliveryContact,Status_Remark,Porder_VATChckbx,Prequest_Ref, user_account,	porder_othercharges )
					  values(".$vPurId.", ".$prqstref.", '".explodewordrequest($PPorDate)."',".GetSQLValueString($PPorRequestDate, 'text')."
					, ".GetSQLValueString($PPorRequestBy, 'text')."
					, ".GetSQLValueString($PPorRemark, 'text')."
					, ".GetSQLValueString($PPorSupplier, 'text')."
					, ".GetSQLValueString($PPorSupplierContact, 'text')."
					, ".GetSQLValueString($PPorCurr, 'text')."
					, ".GetSQLValueString($PPorProjectCode, 'text')."
					, ".GetSQLValueString($PPorCostCentCode, 'text')."
					, '".$_SESSION['useraccount']."'
					, '".$TransType."'
					, ".GetSQLValueString($PurReqId, 'double')."
					, ".GetSQLValueString($PPorDeliveryPlace, 'text')."
					, ".GetSQLValueString($PPorDeliveryContact, 'text')."
					, ".GetSQLValueString($PPorStatusRemark, 'text')."
					, ".$SupplierVAT." 
					, ".GetSQLValueString($PRqst_reference, 'text')."
					, '".$_SESSION['useraccount']."', $txtPorder_Othercharges
					) ";
					
		//echo $query."<br>"; 	exit;
		if (!updateData($connection, $query, true)){
			$ErrorExists = 1;
			$message  = mysql_error($connection); 	
		}  
		
		else  if ( $config['log_file'] == 1){

					 $query_history =  " INSERT INTO Temp_porder(Porder_id, Porder_reference, Porder_date, Porder_RequestDate,Porder_RequestBy, Porder_remark, 
					   supplier_code, Porder_SupplierContact, Currency_code, Project_Code, Costcent_code, logged_code,
					   Porder_Type,PRqst_id,Porder_DeliveryPlace,Porder_DeliveryContact,Status_Remark,Porder_VATChckbx,Prequest_Ref, user_account,	porder_othercharges,
						temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status					   )
					  values(".$vPurId.", ".$prqstref.", '".explodewordrequest($PPorDate)."',".GetSQLValueString($PPorRequestDate, 'text')."
					, ".GetSQLValueString($PPorRequestBy, 'text')."
					, ".GetSQLValueString($PPorRemark, 'text')."
					, ".GetSQLValueString($PPorSupplier, 'text')."
					, ".GetSQLValueString($PPorSupplierContact, 'text')."
					, ".GetSQLValueString($PPorCurr, 'text')."
					, ".GetSQLValueString($PPorProjectCode, 'text')."
					, ".GetSQLValueString($PPorCostCentCode, 'text')."
					, '".$_SESSION['useraccount']."'
					, '".$TransType."'
					, ".GetSQLValueString($PurReqId, 'double')."
					, ".GetSQLValueString($PPorDeliveryPlace, 'text')."
					, ".GetSQLValueString($PPorDeliveryContact, 'text')."
					, ".GetSQLValueString($PPorStatusRemark, 'text')."
					, ".$SupplierVAT." 
					, ".GetSQLValueString($PRqst_reference, 'text')."
					, '".$_SESSION['useraccount']."', $txtPorder_Othercharges,
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'I')";
							$result=mysql_query($query_history,$connection_history);
					
							} 	
			 
		$query = 'select date_format(Porder_date,\'%d/%m%Y\'),Porder_VATChckbx,Porder_DiscountPer from temp_porder where Porder_id = '.$vPurId;
		//echo $query;
		
		$result = mysql_query($query,$connection) or die(mysql_error());	
		$row=mysql_fetch_array($result);
		
		//$PPorDate = $row[0];
		$PPorVatChkbx = $row[1];
		$PPorDiscount = $row[2];

	}



	if($ErrorExists == 0) {
	
		$sub_query = " SELECT PRqstDt_id, PRqst_id, PRqst_Date, Item_code, PRqstDt_Quantity, PRqstDt_QuantityUsed, PRqstDt_QuantityEqual
					, PRqstDt_Price, PRqstDt_PriceBase1, PRqstDt_PriceBase2, PRqstDt_Discount, PRqstDt_Remark, Project_code, 	CostCent_code
					, Item_Barcode, Currency_Code, Supplier_code, PRqstDt_PrintRemark, PRqstDt_DiscountAmount
					, PRqstDt_DiscountBase1
					, PRqstDt_DiscountBase2
					, Item_Tax1, Item_Tax2, Item_Tax3
					, Item_Tax4, Item_Tax5
					, Warehouse_Code,Synchronized, item_vat,  Item_ManufacturedCode
					, Item_UnitCoef, Item_Unit2Qty, Item_QtyPacked, Item_CodePacked, PRqstDt_PriceTTC, PRqstDt_PriceTTCBase1
					, PRqstDt_PriceTTCBase2
					 FROM prequestdt ";
					
					if($SSaDtId != '')			 
						$sub_query = $sub_query." WHERE prequestdt.PRqstDt_id In (".$SSaDtId.")";
					else 
						$sub_query = $sub_query." WHERE prequestdt.PRqst_id = '".$PurReqId."'";	
			
					
		$result = mysql_query($sub_query,$connection) or die(mysql_error());	
		while($row=mysql_fetch_array($result)){
			
			fbegin();
			$vPurDtId = get_nextsequence('PorderDt_Id','',$connection);	
			fcommit();
		
		
			
		
			$query = " INSERT INTO Temp_porderDt (PorderDt_id, Porder_id, Porder_Date, Item_code, PorderDt_Quantity, PorderDt_QuantityUsed
					, PorderDt_QuantityEqual, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_Discount, PorderDt_Remark, Project_code
					, CostCent_code, Item_Barcode, Currency_Code, Supplier_code, PorderDt_PrintRemark
					,  PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2
					,  Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Warehouse_code,  Synchronized
					,  Item_VAT,  Item_ManufacturedCode
					,  Item_UnitCoef, Item_Unit2Qty,  Item_QtyPacked, Item_CodePacked, PorderDt_PriceTTC, PorderDt_PriceTTCBase1
					, PorderDt_PriceTTCBase2, Logged_Code,RelatedDt_ID)
					values (".$vPurDtId.",  ".$vPurId."
					, ".GetSQLValueString(explodewordrequest($PPorDate), 'date')."
					, ".GetSQLValueString($row[3], 'text')."
					, ".GetSQLValueString($row[4], 'double')."
					, ".GetSQLValueString($row[5], 'double')."
					, ".GetSQLValueString($row[6], 'double')."
					, ".GetSQLValueString($row[7], 'double')."
					, ".GetSQLValueString($row[8], 'double')."
					, ".GetSQLValueString($row[9], 'double')."
					, ".GetSQLValueString($row[10], 'double')."
					, ".GetSQLValueString($row[11], 'text')."
					, ".GetSQLValueString($row[12], 'text')."
					, ".GetSQLValueString($row[13], 'text')."
					, ".GetSQLValueString($row[14], 'text')."
					, ".GetSQLValueString($row[15], 'text')."
					, ".GetSQLValueString($row[16], 'text')."
					, ".GetSQLValueString($row[17], 'text')."
					, ".GetSQLValueString($row[18], 'text')."
					, ".GetSQLValueString($row[19], 'text')."
					, ".GetSQLValueString($row[20], 'text')."
					, ".GetSQLValueString($row[21], 'text')."
					, ".GetSQLValueString($row[22], 'text')."
					, ".GetSQLValueString($row[23], 'text')."
					, ".GetSQLValueString($row[24], 'text')."
					, ".GetSQLValueString($row[25], 'text')."
					, ".GetSQLValueString($row[26], 'text')."
					, ".GetSQLValueString($row[27], 'text')."
					, ".GetSQLValueString($row[28], 'text')."
					, ".GetSQLValueString($row[29], 'text')."
					, ".GetSQLValueString($row[30], 'text')."
					, ".GetSQLValueString($row[31], 'text')."
					, ifnull(".GetSQLValueString($row[32], 'text').",0)
					, ".GetSQLValueString($row[33], 'text')."
					, ".GetSQLValueString($row[34], 'text')."
					, ".GetSQLValueString($row[35], 'text')."
					, ".GetSQLValueString($row[36], 'text')."
					,'".$_SESSION['useraccount']."'
					, ".GetSQLValueString($row[0], 'text')." )"
					;
					

				//echo $query."<bR>";
				//exit;
				if (!updateData($connection, $query, true))
						$message1  = mysql_error(); 
				
				else if ( $config['log_file'] == 1){

					 $query_history =  " INSERT INTO Temp_porderDt (PorderDt_id, Porder_id, Porder_Date, Item_code, PorderDt_Quantity, PorderDt_QuantityUsed
					, PorderDt_QuantityEqual, PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2, PorderDt_Discount, PorderDt_Remark, Project_code
					, CostCent_code, Item_Barcode, Currency_Code, Supplier_code, PorderDt_PrintRemark
					,  PorderDt_DiscountAmount, PorderDt_Discountbase1, PorderDt_Discountbase2
					,  Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, Warehouse_code,  Synchronized
					,  Item_VAT,  Item_ManufacturedCode
					,  Item_UnitCoef, Item_Unit2Qty,  Item_QtyPacked, Item_CodePacked, PorderDt_PriceTTC, PorderDt_PriceTTCBase1
					, PorderDt_PriceTTCBase2, Logged_Code,RelatedDt_ID
					,temp_porderdt_history_date, temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status)
					values (".$vPurDtId.",  ".$vPurId."
					, ".GetSQLValueString(explodewordrequest($PPorDate), 'date')."
					, ".GetSQLValueString($row[3], 'text')."
					, ".GetSQLValueString($row[4], 'double')."
					, ".GetSQLValueString($row[5], 'double')."
					, ".GetSQLValueString($row[6], 'double')."
					, ".GetSQLValueString($row[7], 'double')."
					, ".GetSQLValueString($row[8], 'double')."
					, ".GetSQLValueString($row[9], 'double')."
					, ".GetSQLValueString($row[10], 'double')."
					, ".GetSQLValueString($row[11], 'text')."
					, ".GetSQLValueString($row[12], 'text')."
					, ".GetSQLValueString($row[13], 'text')."
					, ".GetSQLValueString($row[14], 'text')."
					, ".GetSQLValueString($row[15], 'text')."
					, ".GetSQLValueString($row[16], 'text')."
					, ".GetSQLValueString($row[17], 'text')."
					, ".GetSQLValueString($row[18], 'text')."
					, ".GetSQLValueString($row[19], 'text')."
					, ".GetSQLValueString($row[20], 'text')."
					, ".GetSQLValueString($row[21], 'text')."
					, ".GetSQLValueString($row[22], 'text')."
					, ".GetSQLValueString($row[23], 'text')."
					, ".GetSQLValueString($row[24], 'text')."
					, ".GetSQLValueString($row[25], 'text')."
					, ".GetSQLValueString($row[26], 'text')."
					, ".GetSQLValueString($row[27], 'text')."
					, ".GetSQLValueString($row[28], 'text')."
					, ".GetSQLValueString($row[29], 'text')."
					, ".GetSQLValueString($row[30], 'text')."
					, ".GetSQLValueString($row[31], 'text')."
					, ifnull(".GetSQLValueString($row[32], 'text').",0)
					, ".GetSQLValueString($row[33], 'text')."
					, ".GetSQLValueString($row[34], 'text')."
					, ".GetSQLValueString($row[35], 'text')."
					, ".GetSQLValueString($row[36], 'text')."
					,'".$_SESSION['useraccount']."'
					, ".GetSQLValueString($row[0], 'text')." 
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'I')";
							$result=mysql_query($query_history,$connection_history);
					
							} 	
		}
		
		//echo $message." ".$message1;
		if ($message!='' or $message1!='') {
			frollback();
			$ErrorExists = 1;
		}	
		else {
			fcommit();
			$ErrorExists = 0;
		}
		
		if ($ErrorExists == 0) {
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($vPurId, $PPorDate, $PPorVatChkbx, $PPorDiscount, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, 'I', $connection);
			$message  = $message . $CalculateResult;
		}
	}	
	//exit;
	
}

$message = ereg_replace(' ','%20',$message);
$WarningMsg = ereg_replace(' ','%20',$WarningMsg);

$PPorRemark          = ereg_replace(' ','%20',$PPorRemark);
$PPorRequestBy       = ereg_replace(' ','%20',$PPorRequestBy);
$PPorSupplierContact = ereg_replace(' ','%20',$PPorSupplierContact);
$PPorDeliveryPlace   = ereg_replace(' ','%20',$PPorDeliveryPlace);
$PPorDeliveryContact = ereg_replace(' ','%20',$PPorDeliveryContact);
$PPorStatusRemark    = ereg_replace(' ','%20',$PPorStatusRemark);

$lstWarehouse        = ereg_replace('#','%23',$lstWarehouse);
$PPorRemark          = ereg_replace('#','%23',$PPorRemark);
$PPorRequestBy       = ereg_replace('#','%23',$PPorRequestBy);
$PPorSupplierContact = ereg_replace('#','%23',$PPorSupplierContact);
$PPorDeliveryPlace   = ereg_replace('#','%23',$PPorDeliveryPlace);
$PPorDeliveryContact = ereg_replace('#','%23',$PPorDeliveryContact);
$PPorStatusRemark    = ereg_replace('#','%23',$PPorStatusRemark);

$lstWarehouse        = ereg_replace('&','%26',$lstWarehouse);
$PPorRemark          = ereg_replace('&','%26',$PPorRemark);
$PPorRequestBy       = ereg_replace('&','%26',$PPorRequestBy);
$PPorSupplierContact = ereg_replace('&','%26',$PPorSupplierContact);
$PPorDeliveryPlace   = ereg_replace('&','%26',$PPorDeliveryPlace);
$PPorDeliveryContact = ereg_replace('&','%26',$PPorDeliveryContact);
$PPorStatusRemark    = ereg_replace('&','%26',$PPorStatusRemark);

//."&txtPorId=".$txtPorId
//if($mode == "post")
	//header ("Location: ./Form_Purchase.php?actionmode=post&mainaction=&message=".$message."&PrPorId=".$SPorId."&PrPorRef=".$vPorRef);
if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_PurchaseOrder.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPorId=".$SPorId."&PrPorRef=".$vPorRef."&message=".$message);
	else
		header ("Location: ./Form_PurchaseOrder.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPorId=".$SPorId."&message=".$message);
}
else if ($mode == "import")		
	header ("Location: ./Form_PurchaseOrder.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPorId=".$SPorId."&message=".$message);	
else if($mainmode == "copyrequest" or $mode == "copyrequest") 
    header ("Location: ./Form_PurchaseLoadRequest.php?PMode=1&GeneratedId=".$PGeneratedId."&actionmode=".$mode."&mainaction=".$mainmode."&PPorId=".$PPorId."&PPorDate=".$PPorDate.
	        "&PPorRequestDate=".$PPorRequestDate."&PPorExpiryDate=".$PPorExpiryDate."&PPorSupplier=".$PPorSupplier."&PPorCurr=".$PPorCurr.
			"&PPorProjectCode=".$PPorProjectCode."&PPorCostCentCode=".$PPorCostCentCode."&PPorCategory=".$PPorCategory."&PPorStatus=".$PPorStatus.
			"&PPorDiscount=".$PPorDiscount."&PPorDiscountAmt=".$PPorDiscountAmt."&PPorVatChkbx=".$PPorVatChkbx."&lstWarehouse=".$lstWarehouse."&porderdt_heatno=".$porderdt_heatno.
			"&PPorRemark=".$PPorRemark."&PPorRequestBy=".$PPorRequestBy."&PPorSupplierContact=".$PPorSupplierContact."&PPorDeliveryPlace=".$PPorDeliveryPlace.
			"&PPorDeliveryContact=".$PPorDeliveryContact."&PPorStatusRemark=".$PPorStatusRemark."&message=".$message	);
else if($mode == "confirmorder") 
	header ("Location: ./Form_PurchaseOrder.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPorId=".$SPorId."&message=".$message);	
else if ($mode == "" && $mainmode == "cancelorder")
		header ("Location: ./Form_PurchaseOrderSearch.php?message=".$message);	
else if($mode == "" && ($mainmode == "confirmorder" || $mainmode == "unconfirmorder"))
	header ("Location: ./Form_PurchaseOrderSearch.php?message=".$message);	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_PurchaseOrderSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "hidePorder" )	
	header ("Location: ./Form_PurchaseOrderSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "unhidePorder" )	
	header ("Location: ./Form_PurchaseOrderSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_PurchaseOrderSearchPending.php");
else if ($mode == "cancel" )		
	header ("Location: ./Form_PurchaseOrder.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_PurchaseOrder.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPorId=".$SPorId."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_PurchaseOrderDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPorId=".$SPorId."&PPorDate=".$PPorDate."&PPorDtId=".$SPorDtId."&message=".$message);		
else if ($mode == "" && $mainmode == "search" )	{
	if ($EditAllow == 1)
		header ("Location: ./Form_PurchaseOrderSearch.php?PMode=1");	
	else
		header ("Location: ./Form_PurchaseOrderSearch.php?PMode=0&message=".$message);
}
else if ($mode == "" && $mainmode == "copyrequest" )		
	header ("Location: ./Form_PurchaseLoadRequest.php?PMode=1&GeneratedId=".$PGeneratedId."&message=".$message);
else if($mode == "submitrecord") {
    header ("Location: ./Form_PurchaseOrderDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPorId=".$PPorId."&PPorDate=".$PPorDate.
	        "&PPorRequestDate=".$PPorRequestDate."&PPorExpiryDate=".$PPorExpiryDate."&PPorSupplier=".$PPorSupplier."&PPorCurr=".$PPorCurr.
			"&PPorProjectCode=".$PPorProjectCode."&PPorCostCentCode=".$PPorCostCentCode."&PPorCategory=".$PPorCategory."&PPorStatus=".$PPorStatus.
			"&PPorDiscount=".$PPorDiscount."&PPorDiscountAmt=".$PPorDiscountAmt."&PPorVatChkbx=".$PPorVatChkbx."&lstWarehouse=".$lstWarehouse."&porderdt_heatno=".$porderdt_heatno.
			"&PPorRemark=".$PPorRemark."&PPorRequestBy=".$PPorRequestBy."&PPorSupplierContact=".$PPorSupplierContact."&PPorDeliveryPlace=".$PPorDeliveryPlace.
			"&PPorDeliveryContact=".$PPorDeliveryContact."&PPorStatusRemark=".$PPorStatusRemark."&message=".$message	);
}


$return_arr = array();

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


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

	$vPorDtTotal = 0;
	$vItemVat    = 0;
	
	$vPorTaxable = 0;
	$vPorNoneTaxable = 0;
	$vPorGrossTotal = 0;
	$vPorDiscountAmt = 0;
	$vPorDiscountPer = 0;
	$vPorVat = 0;
	$vPorVatBase1 = 0;
	$vPorVatBase2 = 0;
		
	$vPorTax1 = 0;
	$vPorTax2 = 0;
	$vPorTax3 = 0;
	$vPorTax4 = 0;
	$vPorTax5 = 0;
	$vPorTax1B1 = 0;
	$vPorTax2B1 = 0;
	$vPorTax3B1 = 0;
	$vPorTax4B1 = 0;
	$vPorTax5B1 = 0;
	$vPorTax1B2 = 0;
	$vPorTax2B2 = 0;
	$vPorTax3B2 = 0;
	$vPorTax4B2 = 0;
	$vPorTax5B2 = 0;

	$vPorDiscountPer = $PDiscPer;
	
	//Added 2011/09/24
	if ($PPurchaseTTC ==1 && $PVatChk == 0 && $PMode == 'P') {

		$query = " UPDATE Temp_PorderDt SET  ".
				 " PorderDt_Price = PorderDt_PriceTTC, PorderDt_PriceBase1 = PorderDt_PriceTTCBase1, ProderDt_PriceBase2 = PorderDt_PriceTTCBase2 ".
				 " Where Porder_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
		
		$select_query="select PorderDt_PriceTTC,PorderDt_PriceTTCBase1,PorderDt_PriceTTCBase2 from Temp_PorderDt where Porder_ID=".$PId;
		$result=mysql_query($select_query,$connection);
		$row=mysql_fetch_array($result);
		$PorderDt_PriceTTC=$row[0];
		$PorderDt_PriceTTCBase1=$row[1];
		$PorderDt_PriceTTCBase2=$row[2];
		
				if ( $config['log_file'] == 1){

					 $query_history =  " INSERT INTO Temp_PorderDt (Porder_ID,PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2,temp_porderdt_history_date, 
					 temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status )
					values (".$PId.",$PorderDt_PriceTTC,$PorderDt_PriceTTCBase1,$PorderDt_PriceTTCBase2
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							} 
		
	}
	else if ($PPurchaseTTC ==1 && $PVatChk == 1 && $PMode == 'P') {

		$query = " UPDATE Temp_PorderDt SET  ".
				 " PorderDt_Price      = (PorderDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " PorderDt_PriceBase1 = (PorderDt_PriceTTCBase1 / (1 + Item_Vat/100)), ".
				 " ProderDt_PriceBase2 = (PorderDt_PriceTTCBase2 / (1 + Item_Vat/100)) ".
				 " Where Porder_ID = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
		
		
				if ( $config['log_file'] == 1){
					
					$select_query="select PorderDt_PriceTTC,PorderDt_PriceTTCBase1,PorderDt_PriceTTCBase2,Item_Vat from Temp_PorderDt where Porder_ID=".$PId;
					$result=mysql_query($select_query,$connection);
					$row=mysql_fetch_array($result);
					$PorderDt_PriceTTC=$row[0];
					$PorderDt_PriceTTCBase1=$row[1];
					$PorderDt_PriceTTCBase2=$row[2];
					$Item_Vat=$row[3];
					 $query_history =  " INSERT INTO Temp_PorderDt (Porder_ID,PorderDt_Price, PorderDt_PriceBase1, ProderDt_PriceBase2,temp_porderdt_history_date, 
					 temp_porderdt_history_operator_id, temp_porderdt_history_schema, temp_porderdt_history_status )
					values (".$PId.",($PorderDt_PriceTTC / (1 + $Item_Vat/100)),($PorderDt_PriceTTCBase1 / (1 + $Item_Vat/100)),($PorderDt_PriceTTCBase2 / (1 + $Item_Vat/100))
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							} 
		
	}	
	
	
	
	
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(PorderDt_Quantity,0)*ifNull(PorderDt_Price,0))-((ifNull(PorderDt_Quantity,0)*ifNull(PorderDt_Price,0)*ifNull(PorderDt_Discount,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " PorderDt_Quantity, ifNull(PorderDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From Temp_PorderDt ".
				 " Where Porder_ID = ".$PId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vPorDtTotal = $sub_rows[1];
		$vItemVat    = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vItemVat > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vPorTaxable     = $vPorTaxable     + ($vPorDtTotal*$tax_flag);
		$vPorNoneTaxable = $vPorNoneTaxable + ($vPorDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if (((insertDate($PDate) > $PSetupVatStartDate && $vItemVat > 0) || ($PModuleAdditionalTaxes == 1))  && $PVatChk == 1 && $vPorDtTotal > 0)
			$vPorVat = $vPorVat + (($vPorDtTotal - $sub_rows[4])*$vItemVat/100);
						
		if ($PModuleAdditionalTaxes == 1 && $vPorDtTotal > 0) {
			if ($vItemVat > 0 && $sub_rows[5] != 0)
				$vPorTax1 = $vPorTax1 + (($vPorDtTotal - $sub_rows[4])*$sub_rows[5]/100);
			if ($vItemVat > 0 && $sub_rows[6] != 0)
				$vPorTax2 = $vPorTax2 + (($vPorDtTotal - $sub_rows[4])*$sub_rows[6]/100);
			if ($vItemVat > 0 && $sub_rows[7] != 0)
				$vPorTax3 = $vPorTax3 + (($vPorDtTotal - $sub_rows[4])*$sub_rows[7]/100);
			if ($vItemVat > 0 && $sub_rows[8] != 0)
				$vPorTax4 = $vPorTax4 + (($vPorDtTotal - $sub_rows[4])*$sub_rows[8]/100);
			if ($vItemVat > 0 && $sub_rows[9] != 0)
				$vPorTax5 = $vPorTax5 + (($vPorDtTotal - $sub_rows[4])*$sub_rows[9]/100);	
		}
					
	}			
					
					
	$vPorGrossTotal = $vPorTaxable + $vPorNoneTaxable;
					
	// Calculation of Discount Amount	
	if ($PMode == 'P') {
		$vPorDiscountAmt = $PDiscAmt;
	}
	else {
		if ($vPorDiscountPer > 0)
			$vPorDiscountAmt = (($vPorGrossTotal * $vPorDiscountPer) / 100);
	}				
				
					
	$vPorNetTotal         = $vPorGrossTotal + $vPorVat - $vPorDiscountAmt;
	$vPorTaxableBase1     = ($vPorTaxable*$PRate)/$PRate1;
	$vPorTaxableBase2     = ($vPorTaxable*$PRate)/$PRate2;
	$vPorNoneTaxableBase1 = ($vPorNoneTaxable*$PRate)/$PRate1;
	$vPorNoneTaxableBase2 = ($vPorNoneTaxable*$PRate)/$PRate2;
	$vPorDiscountAmtBase1 = ($vPorDiscountAmt*$PRate)/$PRate1;
	$vPorDiscountAmtBase2 = ($vPorDiscountAmt*$PRate)/$PRate2;
	$vPorGrossTotalBase1  = ($vPorGrossTotal*$PRate)/$PRate1;
	$vPorGrossTotalBase2  = ($vPorGrossTotal*$PRate)/$PRate2;
	$vPorVatBase1 		  = ($vPorVat*$PRate)/$PRate1;
	$vPorVatBase2 		  = ($vPorVat*$PRate)/$PRate2;
					

	$vPorTax1B1  = ($vPorTax1*$PRate)/$PRate1;
	$vPorTax1B2  = ($vPorTax1*$PRate)/$PRate2;		
	$vPorTax2B1  = ($vPorTax2*$PRate)/$PRate1;
	$vPorTax2B2  = ($vPorTax2*$PRate)/$PRate2;		
	$vPorTax3B1  = ($vPorTax3*$PRate)/$PRate1;
	$vPorTax3B2  = ($vPorTax3*$PRate)/$PRate2;		
	$vPorTax4B1  = ($vPorTax4*$PRate)/$PRate1;
	$vPorTax4B2  = ($vPorTax4*$PRate)/$PRate2;		
	$vPorTax5B1  = ($vPorTax5*$PRate)/$PRate1;
	$vPorTax5B2  = ($vPorTax5*$PRate)/$PRate2;	
	
	fbegin();
		if($_POST['porder_actualdate'] == ""){
		    $porder_actualdate = "00/00/0000";
		}
		else{
			$porder_actualdate = $_POST['porder_actualdate'];
		}
	$sub_query1 = " UPDATE temp_porder SET  ".
				  " Porder_Taxable = $vPorTaxable, Porder_TaxableBase1 = $vPorTaxableBase1, Porder_TaxableBase2 = $vPorTaxableBase2, ".
				  " Porder_NoneTaxable = $vPorNoneTaxable, Porder_NoneTaxableBase1 = $vPorNoneTaxableBase1, Porder_NoneTaxableBase2 = $vPorNoneTaxableBase2, ".
				  " Porder_DiscountAmount = $vPorDiscountAmt, Porder_DiscountBase1 = $vPorDiscountAmtBase1, Porder_DiscountBase2 = $vPorDiscountAmtBase2, ".
				  " Porder_DiscountPer = $vPorDiscountPer, Porder_Vat = $vPorVat, Porder_VatBase1 = $vPorVatBase1, Porder_VatBase2 = $vPorVatBase2, ".
				  " Porder_Total = $vPorGrossTotal, Porder_TotalBase1 = $vPorGrossTotalBase1, Porder_TotalBase2 = $vPorGrossTotalBase2, ".
				  " Porder_Tax1 = $vPorTax1, Porder_Tax1Base1 = $vPorTax1B1, Porder_Tax1Base2 = $vPorTax1B2,  ".
				  " Porder_Tax2 = $vPorTax2, Porder_Tax2Base1 = $vPorTax2B1, Porder_Tax2Base2 = $vPorTax2B2,  ".
				  " Porder_Tax3 = $vPorTax3, Porder_Tax3Base1 = $vPorTax3B1, Porder_Tax3Base2 = $vPorTax3B2,  ".
				  " Porder_Tax4 = $vPorTax4, Porder_Tax4Base1 = $vPorTax4B1, Porder_Tax4Base2 = $vPorTax4B2,  ".
				  " Porder_Tax5 = $vPorTax5, Porder_Tax5Base1 = $vPorTax5B1, Porder_Tax5Base2 = $vPorTax5B2  ".
				  " ,Porder_VATChckbx = $PVatChk ".
				  " ,approvedby = '$approvedby' ".
				 " ,porder_actualdate = '".insertMySQLDate($porder_actualdate)."' ".
				  " WHERE Porder_ID = ".$PId;
				  //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					
				 
				//echo $sub_query1;exit; 
					 
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		
		if ( $config['log_file'] == 1){

					 $query_history =  " INSERT INTO temp_porder (Porder_ID,Porder_Taxable, Porder_TaxableBase1, Porder_TaxableBase2, Porder_NoneTaxable,Porder_NoneTaxableBase1,
					 Porder_NoneTaxableBase2,Porder_DiscountAmount,Porder_DiscountBase1,Porder_DiscountBase2,Porder_DiscountPer,Porder_Vat,Porder_VatBase1,Porder_VatBase2,
					 Porder_Total,Porder_TotalBase1,Porder_TotalBase2,Porder_Tax1,Porder_Tax1Base1,Porder_Tax1Base2,Porder_Tax2,Porder_Tax2Base1,Porder_Tax2Base2,
					 Porder_Tax3,Porder_Tax3Base1,Porder_Tax3Base2,Porder_Tax4,Porder_Tax4Base1,Porder_Tax4Base2,Porder_Tax5,Porder_Tax5Base1,Porder_Tax5Base2,
					 Porder_VATChckbx,approvedby,
					 porder_actualdate,temp_porder_history_date, temp_porder_history_operator_id, temp_porder_history_schema, temp_porder_history_status)
					values (".$PId.",$vPorTaxable,$vPorTaxableBase1,$vPorTaxableBase2,$vPorNoneTaxable,$vPorNoneTaxableBase1,$vPorNoneTaxableBase2,$vPorDiscountAmt,$vPorDiscountAmtBase1
					$vPorDiscountAmtBase2,$vPorDiscountPer,$vPorVat,$vPorVatBase1,$vPorVatBase2,$vPorGrossTotal,$vPorGrossTotalBase1,$vPorGrossTotalBase2,$vPorTax1,
					$vPorTax1B1,$vPorTax1B2,$vPorTax2,$vPorTax2B1,$vPorTax2B2,$vPorTax3,$vPorTax3B1,$vPorTax3B2,$vPorTax4,$vPorTax4B1,$vPorTax4B2,$vPorTax5,$vPorTax5B1,$vPorTax5B2,
					$PVatChk,$approvedby,'".$_SESSION['useraccount']."' 
											,now()			
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'U')";
							$result=mysql_query($query_history,$connection_history);
					
							} 	
		
		
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}						  


	function explodewordrequest($date)
	{

		$trim = explode('/',$date);
		$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";

		return $trim;
	}

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

HERE;
*/
function GetSQLValueString($theValue, $theType) 
{
  $theValue = trim($theValue);	
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "Null";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "Null";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;
  }
  return $theValue;
}


function sendmail($Subject,$Body,$emails,$SPreqId,$connection){
 $recipients="";
	error_reporting(E_ALL);
	error_reporting(E_ALL);

	require 'PHPMailer-master/class.phpmailer.php';
	
	//// Configuration
	$query_mailsetup="select hostname,mailagent,port,SenderEmail,ReceiverEmail,password from configurationemail";
	$result_mailsetup = mysql_query($query_mailsetup, $connection);
	$row_setup=mysql_fetch_row($result_mailsetup); 
	$hostname=$row_setup[0];
	$port=$row_setup[2];
	$sender=$row_setup[3];
	$pswd = $row_setup[5];
	
	$mail = new PHPMailer;
	$mail->IsSMTP();                                      // Set mailer to use SMTP
	$mail->Host = $hostname; 							// Specify main and backup server
	$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = $sender;                            // SMTP username
	$mail->Password = $pswd;                           // SMTP password
	$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
	$mail->From = $sender;
	$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
	$mail->Body    =  $Body;
	$mail->IsHTML(true);                                  // Set email format to HTML
	$mail->Subject = $Subject;
	$mail->SMTPDebug = 1;
	$mail->Port = $row_setup[2]; 
	//exit;
	
	
		
		$emailtechs = explode(';',$emails);
		foreach($emailtechs as $emailtech){
		$mail->AddAddress($emailtech, '');  // Add a recipient
		$recipients = $recipients." $emailtech,";
			
		}
	
	if(!$mail->Send()) { 
	  $error = $mail->ErrorInfo;
		return false;	
      	 
	}

	
	return true;
}	
?>