<?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");


$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass']) 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);

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

$querylog="select ifNull(login_belongstogrp,0) As FI_BelongsToGrp   ,ifnull(PrequestApproved_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);
}
 
//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_PRequestConfirm,0) As Module_PRequestConfirm, ".
			 " 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_PrequestAutoApprove,0) As Module_PrequestAutoApprove,module_CheckItem  ".
			 " ,ifnull(PrequestReferenceByProject,0) as PrequestReferenceByProject ".
			 " ,ifnull(module_PRWarehouse,0) as module_PRWarehouse ".
			 " 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"];}  
$vmode 		= $_GET["vmode"]; if ($vmode == ""){$vmode = $_POST["vmode"];}  
//echo "vmode". $vmode."mainmode".$mainmode."actionmode".$actionmode. "mode=".$mode;
//exit;

//exit;

$SMReqId    		= $_GET["SMReqId"]; 		if ($SMReqId == ""){$SMReqId = $_POST["SMReqId"];} 
$SPorDtId			= $_GET["SPorDtId"]; 		if ($SPorDtId == ""){$SPorDtId = $_POST["SPorDtId"];} 
$SPorVatChkbx 		= $_GET["SPorVatChkbx"]; 	if ($SPorVatChkbx == ""){$SPorVatChkbx = $_POST["SPorVatChkbx"];} 
$mreqid    			= $_GET["mreqid"]; 			if ($mreqid == ""){$mreqid = $_POST["mreqid"];} 
$mreqdtid    		= $_GET["mreqdtid"]; 		if ($mreqdtid == ""){$mreqdtid = $_POST["mreqdtid"];} 

$txtMReqId    		= $_GET["txtMReqId"]; if ($txtMReqId == ""){$txtMReqId = $_POST["txtMReqId"];} 
$txtDate 			= $_GET["txtDate"]; if ($txtDate == ""){$txtDate = $_POST["txtDate"];} 
$txtRequestDate 	= $_GET["txtRequestDate"]; if ($txtRequestDate == ""){$txtRequestDate = $_POST["txtRequestDate"];} 
$txtRequestBy 	   	= $_GET["txtRequestBy"]; if ($txtRequestBy == ""){$txtRequestBy = $_POST["txtRequestBy"];} 
$txtPurpose 	   	= $_GET["txtPurpose"]; if ($txtPurpose == ""){$txtPurpose = $_POST["txtPurpose"];} 
$txtLocation 	   	= $_GET["txtLocation"]; if ($txtLocation == ""){$txtLocation = $_POST["txtLocation"];} 
$txtPriority 	   	= $_GET["txtPriority"]; if ($txtPriority == ""){$txtPriority = $_POST["txtPriority"];} 
$txtCurr   			= $_GET["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_POST["txtCurr"];} 
$txtRemark  		= $_GET["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_POST["txtRemark"];} 
$txtProjectCode 	= $_GET["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_POST["txtProjectCode"];} 

$txtCostCentCode	= $_GET["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_POST["txtCostCentCode"];} 
$txtReqStatus		= $_GET["txtReqStatus"]; if ($txtReqStatus == ""){$txtReqStatus = $_POST["txtReqStatus"];} 
$txtStatusRemark	= $_GET["txtStatusRemark"]; if ($txtStatusRemark == ""){$txtStatusRemark = $_POST["txtStatusRemark"];} 
$txtDeliveryPlace	= $_GET["txtDeliveryPlace"]; if ($txtDeliveryPlace == ""){$txtDeliveryPlace = $_POST["txtDeliveryPlace"];} 
$txtDeliveryContact	= $_GET["txtDeliveryContact"]; if ($txtDeliveryContact == ""){$txtDeliveryContact = $_POST["txtDeliveryContact"];} 
$txtReqDiscount		= $_GET["txtReqDiscount"]; if ($txtReqDiscount == ""){$txtReqDiscount = $_POST["txtReqDiscount"];} 
$txtReqDiscountAmt	= $_GET["txtReqDiscountAmt"]; if ($txtReqDiscountAmt == ""){$txtReqDiscountAmt = $_POST["txtReqDiscountAmt"];} 
$vprojectcode		= $_GET["vprojectcode"]; if ($vprojectcode == ""){$vprojectcode = $_POST["vprojectcode"];} 
$PPorSupplier		= $_GET["PPorSupplier"]; if ($PPorSupplier == ""){$PPorSupplier = $_POST["PPorSupplier"];} 

$prequestdt_availableqty	= $_GET["prequestdt_availableqty"]; if ($prequestdt_availableqty == ""){$prequestdt_availableqty = $_POST["prequestdt_availableqty"];} 
$SPrqstDtId					= $_GET["SPrqstDtId"]; if ($SPrqstDtId == ""){$SPrqstDtId = $_POST["SPrqstDtId"];} 
$txtPorDtQty2				= $_GET["txtPorDtQty2"]; if ($txtPorDtQty2 == ""){$txtPorDtQty2 = $_POST["txtPorDtQty2"];} 
$PPorDiscountAmt			= $_GET["PPorDiscountAmt"]; if ($PPorDiscountAmt == ""){$PPorDiscountAmt = $_POST["PPorDiscountAmt"];} 
$txtPorCategory				= $_GET["txtPorCategory"]; if ($txtPorCategory == ""){$txtPorCategory = $_POST["txtPorCategory"];} 
$txtPorStatus				= $_GET["txtPorStatus"]; if ($txtPorStatus == ""){$txtPorStatus = $_POST["txtPorStatus"];} 
$userupdate					= $_GET["userupdate"]; if ($userupdate == ""){$userupdate = $_POST["userupdate"];} 
$approved					= $_GET["approved"]; if ($approved == ""){$approved = $_POST["approved"];} 
$WarningMsg					= $_GET["WarningMsg"]; if ($WarningMsg == ""){$WarningMsg = $_POST["WarningMsg"];} 
$ErrorExists = 0;


$message='';

//Submit Record Mode

if ($actionmode == "updateavailable" ){

$query = " UPDATE materialreqdt SET MReqDt_availableqty = '$MReqDt_availableqty' where MReqDt_id = $MReqDt_id";
//echo $query;
			if (!updateData($connection, $query, true)) 
				$message  = mysql_error();
		/*	else  if ( $config['log_file'] == 1){
				$query_history="insert into materialreqdt ( MReqDt_availableqty ,MReqDt_id,MReqDt_date, MReqDt_operator_id, MReqDt_schema, MReqDt_status)".
				 "  values('$MReqDt_availableqty',$MReqDt_id,now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
					if (!updateData($connection_history, $query_history, true))		 
				$message  = mysql_error($query_history);
			}*/


}
else if ($actionmode == "submitmreqdt" ){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	
	$itemcodepacked 		= $_GET["value1"];
	$txtItemCode 			= $_GET["value2"];
	$itemdescription 		= $_GET["value3"];
	$lstWarehouse 			= $_GET["value4"];
	$txtPorDtQty 			= $_GET["value5"];
	$item_unitpurchasedesc 	= $_GET["value6"];
	$item_unit2qty 			= $_GET["value7"];
	$vPorDtPriceTTC 		= $_GET["value8"];
	$txtPorDtPrice 			= $_GET["value9"];
	$mreqdttotalttc 		= $_GET["value10"];
	$mreqdttotal 			= $_GET["value11"];
	$txtPorDtDiscount 		= $_GET["value12"];
	$txtProjectCodeDt 		= $_GET["value13"];
	$txtCostCentCodeDt 		= $_GET["value14"];
	$PPorDate 				= $_GET["value15"];
	$PPorRequestDate 		= $_GET["value16"];
	$PPorCurr 				= $_GET["value17"];
	$PPorProjectCode 		= $_GET["value18"];
	$PPorCostCentCode 		= $_GET["value19"];
	$PPorRequestBy 			= $_GET["value20"];
	
	$PPorRemark	 			= $_GET["value21"];
	$PPorCategory 			= $_GET["value22"];
	$PPorStatus 			= $_GET["value23"];
	$PPorStatusRemark 		= $_GET["value24"];
	$PPorDeliveryPlace 		= $_GET["value25"];
	$PPorDeliveryContact 	= $_GET["value26"];
	
	$PPorDiscount 			= $_GET["value28"];
	
	$txtPorDtRemark 		= $_GET["value29"];
	$txtmreqdtitemdescription = $_GET["value30"];
	
	$txtPorDtOQty 			= $_GET["value31"];
	$txtPorDtCQty 			= $_GET["value32"];
	

	$txtPurpose 			= $_GET["value33"];
	$txtLocation 			= $_GET["value34"];
	$txtPriority 			= $_GET["value35"];
	$itemunitsalesdesc		= $_GET["value36"];
	$txtheatno 				= $_GET["mreqdtheatno"];
	$txtRequiredDate 		= $_GET['mreqdt_RequiredDate'];
	$txtDeliveryDate 		= $_GET['txtDeliveryDate'];
	
	if ($txtPorDtCQty=='')	
		$txtPorDtCQty 		= 0;
		
	$MReqId 				= $_GET["MReqId"];
	$PPorVatChkbx 			= $_GET["PPorVatChkbx"];
	


	
	if (!isset($PPorCurr))
	   $PPorCurr = $base1;
	   
	if (empty($PPorCategory))
		$PPorCategory = 0;
	if (empty($PPorStatus))
		$PPorStatus = 'P';	
	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;
	}	

	$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;
	}
	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;
	}
	
	
	if ($ErrorExists == 1)
		$message = 'Insert not allowed. Please check for Project/Costcenter Code.';
		
		
	//Insert Master Table
	if ($MReqId == "" && $ErrorExists == 0){
		
	
			
		fbegin();	
		$MReqId = get_nextsequence('MaterialReq_id','',$connection);
		fcommit();
		
	//	if ($Module_PRequestConfirm == 0) $PPorConfirmed = 1; else $PPorConfirmed = 0; 
		if($PPorConfirmed == '') $PPorConfirmed = 0; 


		fbegin();
		$query = " INSERT INTO temp_materialreq (MReq_id, MReq_reference, MReq_date, MReq_RequestDate, MReq_DeliveryDate, MReq_RequestBy, Currency_Code, Project_Code, Costcent_code, ".
				 "  MReq_remark, MReq_Posted,  MReq_Import, MReq_Status, Status_Remark, MReq_DeliveryPlace, MReq_DeliveryContact,  ".
				 " MReq_Taxable, MReq_TaxableBase1, MReq_TaxableBase2, MReq_NoneTaxable, MReq_NoneTaxableBase1, MReq_NoneTaxableBase2, MReq_DiscountAmount
				 , MReq_DiscountBase1, ".
				 " MReq_DiscountBase2, MReq_DiscountPer, MReq_Total, MReq_TotalBase1, MReq_TotalBase2, MReq_Vat, MReq_VatBase1, MReq_VatBase2
				 , MReq_VATChckbx, MReq_Type, ".
				 " MReq_Confirmed, MReq_BelongsToGroup, User_Name, Logged_Code,username,MReq_Purpose,MReq_Location,MReq_Priority) ".
				 " VALUES ( ".$MReqId.", Null, '".insertMySQLDate($PPorDate)."', '".insertMySQLDate($PPorDate)."', '".insertMySQLDate($txtDeliveryDate)."', '".ereg_replace("'", "\'", trim($PPorRequestBy))."', ".
				 "          '".$PPorCurr."', $ProjectCode, $CostCentCode,  ".
				 "          '".ereg_replace("'", "\'", trim($PPorRemark))."', 0, '".$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, 'PQ', $PPorConfirmed, $FI_BelongsToGrp,'".$_SESSION['username']."'
				 , '".$_SESSION['useraccount']."'
				 , '".$_SESSION['username']."' 
				,'".ereg_replace("'", "\'", trim($txtPurpose))."'				 
				,'".ereg_replace("'", "\'", trim($txtLocation))."'				 
				,'".ereg_replace("'", "\'", trim($txtPriority))."'				 
				 )";

				// echo $query."<br>";exit;	
		$result=mysql_query($query,$connection);
		
		
		if ($result){
			$SMReqId = $MReqId;
			
			/*  if ( $config['log_file'] == 1){
				$query_history=" INSERT INTO temp_materialreq (MReq_id, MReq_reference, MReq_date, MReq_RequestDate,  MReq_RequestBy, Currency_Code, Project_Code, Costcent_code, ".
				 "  MReq_remark, MReq_Posted,  MReq_Import, MReq_Status, Status_Remark, MReq_DeliveryPlace, MReq_DeliveryContact,  ".
				 " MReq_Taxable, MReq_TaxableBase1, MReq_TaxableBase2, MReq_NoneTaxable, MReq_NoneTaxableBase1, MReq_NoneTaxableBase2, MReq_DiscountAmount
				 , MReq_DiscountBase1, ".
				 " MReq_DiscountBase2, MReq_DiscountPer, MReq_Total, MReq_TotalBase1, MReq_TotalBase2, MReq_Vat, MReq_VatBase1, MReq_VatBase2
				 , MReq_VATChckbx, MReq_Type, ".
				 " MReq_Confirmed, MReq_BelongsToGroup, User_Name, Logged_Code,username,MReq_Purpose,MReq_Location,MReq_Priority,temp_prequest_date, temp_prequest_operator_id, temp_prequest_schema, temp_prequest_status) ".
				 " VALUES ( ".$MReqId.", Null, '".insertMySQLDate($PPorDate)."', '".insertMySQLDate($PPorDate)."',  '".ereg_replace("'", "\'", trim($PPorRequestBy))."', ".
				 "          '".$PPorCurr."', $ProjectCode, $CostCentCode,  ".
				 "          '".ereg_replace("'", "\'", trim($PPorRemark))."', 0, '".$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, 'PQ', $PPorConfirmed, $FI_BelongsToGrp,'".$_SESSION['username']."'
				 , '".$_SESSION['useraccount']."'
				 , '".$_SESSION['username']."' 
				,'".ereg_replace("'", "\'", trim($txtPurpose))."'				 
				,'".ereg_replace("'", "\'", trim($txtLocation))."'				 
				,'".ereg_replace("'", "\'", trim($txtPriority))."'				 
				,now()
					, '".$User_Name."'
					, '".$_SESSION['dbName']."'
					, 'I')";
					if (!updateData($connection_history, $query_history, true))		 
				$message  = mysql_error($query_history);
			}*/
			fcommit();
		}else{
			$MReqId = "";
			$SMReqId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if (($SMReqId != "" or $MReqId != "")&& $SMReqDtId == ""  && $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;
		
				
		//Check If Item Exists In materialreqdt, If So Stop User
		$query = " Select Count(*) ".
				 " From temp_materialreqdt As materialreqdt ".
				 " Inner Join Items on Items.Item_Code = materialreqdt.Item_Code ".
				 " Where MReq_id = '".$SMReqId."' ";
				 
		if ($lstItemType == "Trading" || $lstItemType == "PromoTrading" || $lstItemType == "Production" || $lstItemType == "NonStock" || $lstItemType == "All")
			$query = $query." And materialreqdt.Item_Code = '".$txtItemCode."' ".
							" And (materialreqdt.Item_CodePacked is null or materialreqdt.Item_CodePacked  = '') ";
		else
			$query = $query." And materialreqdt.Item_CodePacked = '".$txtItemCode."' ".
							" And (materialreqdt.Item_CodePacked is not null and materialreqdt.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) {
		
		$query = " SELECT ifNull(Item_Pack, 0) ".
				 " FROM Items WHERE Item_Code = '".$txtItemCode."'";
		$result   = selectData($connection, $query);
		$ItemPack = $result[0];
		//echo $query;
			// Case Not Pack Item

			
			if ($ItemPack==0){

				$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();
					$vMreqDtId = get_nextsequence('MaterialReqdt_id','',$connection);	
				fcommit();

				
				fbegin();
				if ($vItemUnitCoef=='')
						$vItemUnitCoef = 'null';
				if ($ItemVat=='')		
					$ItemVat = 'null';
					
				$query = " INSERT INTO temp_materialreqdt (MReqDt_id, MReq_id, Currency_Code, MReq_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
								 " Item_QtyPacked, MReqDt_Quantity, MReqDt_Price, MReqDt_PriceBase1, MReqDt_PriceBase2, MReqDt_PriceTTC, MReqDt_PriceTTCBase1, MReqDt_PriceTTCBase2, ".
								 " MReqDt_Discount, MReqDt_DiscountAmount, MReqDt_DiscountBase1, MReqDt_DiscountBase2, Item_VAT, MReqDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Item_UnitCoef, Item_Unit2Qty,item_description,MReqDt_OQuantity,MReqDt_CQuantity, Logged_Code,user_name,MReqdt_unitsalesdesc, MReqDt_heatno, MReqDt_RequiredDate ) ".
						 " VALUES ( ".$vMreqDtId.", ".$MReqId.", '".$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,  $vItemUnitCoef, $vItemUnit2Qty,'".ereg_replace("'", "\'", trim($txtmreqdtitemdescription))."',$txtPorDtOQty, ".
						 " 			$txtPorDtCQty, '".$_SESSION['useraccount']."', '".$_SESSION['username']."','$itemunitsalesdesc',  '".ereg_replace("'", "\'", trim($textheatno))."', ".formatdate($txtRequiredDate)." ) ";
					
				//echo $query;
				$result=mysql_query($query,$connection);
				//	exit;
				if ($result){
					
				/*	  if ( $config['log_file'] == 1){
						$query_history=" INSERT INTO temp_materialreqdt (MReqDt_id, MReq_id, Currency_Code, MReq_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
								 " Item_QtyPacked, MReqDt_Quantity, MReqDt_Price, MReqDt_PriceBase1, MReqDt_PriceBase2, MReqDt_PriceTTC, MReqDt_PriceTTCBase1, MReqDt_PriceTTCBase2, ".
								 " MReqDt_Discount, MReqDt_DiscountAmount, MReqDt_DiscountBase1, MReqDt_DiscountBase2, Item_VAT, MReqDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Item_UnitCoef, Item_Unit2Qty,item_description,MReqDt_OQuantity,MReqDt_CQuantity, Logged_Code,user_name,MReqdt_unitsalesdesc,temp_MReqdt_date, 
								 temp_MReqdt_operator_id, temp_MReqdt_schema, temp_MReqdt_status ) ".
						 " VALUES ( ".$vPreqDtId.", ".$MReqId.", '".$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,  $vItemUnitCoef, $vItemUnit2Qty,'".ereg_replace("'", "\'", trim($txtmreqdtitemdescription))."',$txtPorDtOQty,$txtPorDtCQty,
						 '".$_SESSION['useraccount']."', '".$_SESSION['username']."','$itemunitsalesdesc' ,
									 now()
										, '".$User_Name."'
										, '".$_SESSION['dbName']."'
										, 'I')";
					if (!updateData($connection_history, $query_history, true))		 
					$message  = mysql_error($query_history);
				}*/
					fcommit();
						
				}else{
					$vMreqDtId = "";
					$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();
						$vMreqDtId = get_nextsequence('MaterialReqdt_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_materialreqdt (MReqDt_id, MReq_id, Currency_Code, MReq_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
								 " Item_QtyPacked, MReqDt_Quantity, MReqDt_Price, MReqDt_PriceBase1, MReqDt_PriceBase2, MReqDt_PriceTTC, MReqDt_PriceTTCBase1, MReqDt_PriceTTCBase2, ".
								 " MReqDt_Discount, MReqDt_DiscountAmount, MReqDt_DiscountBase1, MReqDt_DiscountBase2, Item_VAT, MReqDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Item_UnitCoef, Item_Unit2Qty,item_description,MReqDt_OQuantity,MReqDt_CQuantity, Logged_Code,user_name ,MReqdt_unitsalesdesc) ".
								 " VALUES ( ".$vMreqDtId.", ".$MReqId.", '".$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, $vItemUnitCoef, $vItemUnit2Qty,'".$txtmreqdtitemdescription."',$txtPorDtOQty,$txtPorDtCQty, '".$_SESSION['useraccount']."', '".$_SESSION['username']."','$itemunitsalesdesc' ) ";
								 
						$result=mysql_query($query,$connection);
						
						/* if ( $config['log_file'] == 1){
							$query_history="INSERT INTO temp_materialreqdt (MReqDt_id, MReq_id, Currency_Code, MReq_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ".
								 " Item_QtyPacked, MReqDt_Quantity, MReqDt_Price, MReqDt_PriceBase1, MReqDt_PriceBase2, MReqDt_PriceTTC, MReqDt_PriceTTCBase1, MReqDt_PriceTTCBase2, ".
								 " MReqDt_Discount, MReqDt_DiscountAmount, MReqDt_DiscountBase1, MReqDt_DiscountBase2, Item_VAT, MReqDt_Remark, Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, ".
								 " Item_UnitCoef, Item_Unit2Qty,item_description,MReqDt_OQuantity,MReqDt_CQuantity, Logged_Code,user_name ,MReqdt_unitsalesdesc, temp_MReqdt_date, temp_MReqdt_operator_id, temp_MReqdt_schema, temp_MReqdt_status ) ".
								 " VALUES ( ".$vMreqDtId.", ".$MReqId.", '".$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, $vItemUnitCoef, $vItemUnit2Qty,'".$txtmreqdtitemdescription."',$txtPorDtOQty,$txtPorDtCQty, '".$_SESSION['useraccount']."', '".$_SESSION['username']."','$itemunitsalesdesc' ,
											now()
											, '".$User_Name."'
											, '".$_SESSION['dbName']."'
											, 'I')";
							if (!updateData($connection_history, $query_history, true))		 
							$message  = mysql_error($query_history);
						}*/
								
						//echo $query;
						
					} // End Loop Of Packdt
					
					
					if ($result){
						fcommit();
					}else{
						$vMreqDtId = "";
						$ErrorExists = 1;
						$message  = mysql_error(); 
						frollback();
					}	
				
				
			} // End CasePack Item
			
			if ($ErrorExists == 0) {
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($MReqId, $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
echo "[BRK]";
echo $MReqId;
exit;
} 
else if ($actionmode=='checkitemcode'){

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

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

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

$vwarehousecode = $_GET["vwarehousecode"];

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

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

else if ($actionmode=='checkprojectcode'){

$vwarehousecode = $_GET["vwarehousecode"];

$query = " select project_code from project where project_code = '".$vprojectcode ."' ";
$result=mysql_query($query,$connection)  or die(mysql_error());
$row=mysql_fetch_row($result);

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

else if ($actionmode=='checkcostcentercode'){

$vcostcentercode = $_GET["vcostcentercode"];

$query = " select costcent_code from costcent where costcent_code = '".$vcostcentercode ."' ";
$result=mysql_query($query,$connection)  or die(mysql_error());
$row=mysql_fetch_row($result);

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

//Edit Detail Tables
else if ($actionmode == "editdt" ){

if($SMReqId=='')
	$SMReqId 				= $txtMReqId;
		
	$itemcodepacked 		= $_GET["value1"];
	$txtItemCode 			= $_GET["value2"];
	$itemdescription 		= $_GET["value3"];
	$lstWarehouse 			= $_GET["value4"];
	$txtPorDtQty 			= $_GET["value5"];
	$item_unitpurchasedesc	= $_GET["value6"];
	$item_unit2qty 			= $_GET["value7"];
	$vPorDtPriceTTC 		= $_GET["value8"];
	$txtPorDtPrice 			= $_GET["value9"];
	$mreqdttotalttc	 		= $_GET["value10"];
	$mreqdttotal 			= $_GET["value11"];
	$txtPorDtDiscount 		= $_GET["value12"];
	$txtProjectCodeDt 		= $_GET["value13"];
	$txtCostCentCodeDt 		= $_GET["value14"];
	$PPorDate 				= $_GET["value15"];
	$PPorRequestDate 		= $_GET["value16"];
	$PPorCurr 				= $_GET["value17"];
	$PPorProjectCode 		= $_GET["value18"];
	$PPorCostCentCode 		= $_GET["value19"];
	$PPorRequestBy 			= $_GET["value20"];
	$PPorRemark 			= $_GET["value21"];
	$PPorCategory 			= $_GET["value22"];
	$PPorStatus 			= $_GET["value23"];
	$PPorStatusRemark 		= $_GET["value24"];
	$PPorDeliveryPlace 		= $_GET["value25"];
	$PPorDeliveryContact 	= $_GET["value26"];
	$PPorDiscount 			= $_GET["value28"];
	$txtPorDtRemark 		= $_GET["value29"];
	$txtheatno 				= $_GET['prqstdtheatno'];
	$txtPorDtOQty 			= $_GET["value31"];
	$txtPorDtCQty 			= $_GET["value32"];
	$txtRequiredDate   		= $_GET['mreqdt_RequiredDate']; 
	
	$txtunitsalesdesc 		= $_GET["value36"];
	$txtitemdescription 	= $_GET["value30"];
	
		
		
	if ($SMReqId != "" && $SMReqDtId != "") {
		
		
		$query = "select MReqDt_status from temp_materialreqdt where MReqDt_id = $SMReqDtId";
		//echo $query;
		$result=mysql_query($query,$connection) or die(mysql_error());
		$rows=mysql_fetch_array($result);
		if($rows[0]=='u')
			exit;
		
		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;	
		
		$txtProjectCodeDt = "".$txtProjectCodeDt;	
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}	
		
				
		$query = "SELECT Item_Vat FROM Items WHERE item_Code = '".$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(MReq_Taxable,0), ifNull(MReq_NoneTaxable,0), ifNull(MReq_DiscountPer,0), Supplier_code ".
				 " From temp_materialreq  ".
				 " Where MReq_id = ".$SMReqId;
				 //" 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;
				
					   
						
		fbegin();	
				
		$query = " UPDATE temp_materialreqdt SET Warehouse_Code='$lstWarehouse', ".
		         " MReqDt_Remark = '".ereg_replace("'", "\'", trim($txtPorDtRemark))."' ,item_description = '".ereg_replace("'", "\'", trim($txtitemdescription))."'
				 , MReqDt_Quantity = $txtPorDtQty, MReqDt_OQuantity = $txtPorDtOQty, MReqDt_CQuantity = $txtPorDtCQty
				 , Item_Unit2Qty = $txtPorDtQty2, ".
				 " MReqDt_Price = $vPorDtPrice, MReqDt_PriceBase1 = $vPorDtPriceBase1, MReqDt_PriceBase2 = $vPorDtPriceBase2, MReqDt_Discount = $txtPorDtDiscount, ".
				 " MReqDt_PriceTTC = $vPorDtPriceTTC, MReqDt_PriceTTCBase1 = $vPorDtPriceTTCBase1, MReqDt_PriceTTCBase2 = $vPorDtPriceTTCBase2,  ".
				 " MReqDt_DiscountAmount = $vPorDtDiscAmt, MReqDt_Discountbase1 = $vPorDtDiscAmtBase1, MReqDt_Discountbase2 = $vPorDtDiscAmtBase2 
				 ,MReqDt_unitsalesdesc='$txtunitsalesdesc', MReqDt_heatno = '".ereg_replace("'", "\'", trim($txtheatno))."', MReqDt_RequiredDate = ".formatdate($txtRequiredDate)." ";
		if ($Module_ProjectDt == 1)
			$query = $query.", Project_Code = $ProjectCodeDt ";
		if ($Module_CostCenterDt == 1)	
			$query = $query.", CostCent_Code = $CostCentCodeDt ";
		
		$query = $query." Where MReqDt_ID = ".$SMReqDtId;		 
	//echo $query;exit;
		
		$result=mysql_query($query,$connection);
		if ($result){
			
			/* if ( $config['log_file'] == 1){
				 
				 
				 $selectdetail= "select MReq_id from temp_materialreqdt Where MReqDt_ID = ".$SMReqDtId;
				 	$result=mysql_query($selectdetail,$connection);		 
				$res=mysql_fetch_array($result);
				$MReq_id=$res[0];
				//$query_test= "INSERT INTO temp_prequestdt (PrqstDt_ID,Warehouse_Code) values('1','2')";
				//if (!updateData($connection_history, $query_test, true))		 
				//$message  = mysql_error($selectdetail);
				$query_history=" INSERT INTO temp_prequestdt (MReqDt_ID,MReq_id,Warehouse_Code, MReqDt_Remark, item_description, MReqDt_Quantity,  MReqDt_OQuantity,
				MReqDt_CQuantity, Item_Unit2Qty, MReqDt_Price, MReqDt_PriceBase1,MReqDt_PriceBase2,MReqDt_PriceTTC,MReqDt_PriceTTCBase1,MReqDt_PriceTTCBase2,
				MReqDt_DiscountAmount,MReqDt_Discountbase1,MReqDt_Discountbase2,MReqdt_unitsalesdesc
				 ";
					
			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_MReqdt_date, temp_MReqdt_operator_id, temp_MReqdt_schema, temp_MReqdt_status)
				VALUES ( ".$SMReqDtId.",".$SMReqId.",'".$lstWarehouse."', '".ereg_replace("'", "\'", trim($txtPorDtRemark))."','".ereg_replace("'", "\'", trim($txtitemdescription))."',
				 $txtPorDtQty,$txtPorDtOQty,$txtPorDtCQty,$txtPorDtQty2,$vPorDtPrice,$vPorDtPriceBase1,$vPorDtPriceBase2, $vPorDtPriceTTC,$vPorDtPriceTTCBase1,$vPorDtPriceTTCBase2,$vPorDtDiscAmt,
				 $vPorDtDiscAmtBase1,$vPorDtDiscAmtBase2,'$txtunitsalesdesc'";
				 
			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')";
					if (!updateData($connection_history, $query_history, true))		 
				$message  = mysql_error($query_history);
			//echo $query_history;exit;
			}*/
			fcommit();
			
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SMReqId, $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 ($actionmode == "deletedt" ){

	$DeleteAllow = 0;
	$ErrorExists = 0;
	$message  = '';
	
	
	echo "[BRK]";
	
	
	$query = " Select  item_code, MReqDt_status".
			 " From materialreqdt".
			 " Where materialreqdt.MReqDt_id = ".$mreqdtid;
			
	$result = selectData($connection, $query);
	$PurStatus = $result[1];
	
	if ($PurStatus!='') {
		$message  = 'Delete not allowed,check '.$result[0].' status.';
		$DeleteAllow = 1;
		}
	
	 //Check Each prequestdt If Has RelatedId In PurchasesDt
	$query = " Select Count(1), Purchases.Purchase_reference ".
			 " From prequestdt ".
			 " Where related_MReqdtid = ".$mreqdtid."; ";

	$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 ($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 materialreqdt.Item_CodePacked, materialreqdt.Item_code ".
					 " FROM Temp_materialreqdt As materialreqdt ".
					 " Where materialreqdt.MReqDt_id = ".$mreqdtid;
					 //" 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_materialreqdt ".
					 " WHERE MReqDt_id = ".$mreqdtid;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			/* else {
				
				
				 if ( $config['log_file'] == 1){
				$query_history="insert into temp_prequestdt ( PRqstDt_id ,PRqst_id,temp_prequestdt_date, temp_prequestdt_operator_id, temp_prequestdt_schema, temp_prequestdt_status)".
							  "  values(".$prqstdtid.",$PRqst_id,now()
				, '".$User_Name."'
				, '".$_SESSION['dbName']."'
					, 'D')";
					if (!updateData($connection_history, $query_history, true))		 
				$message  = mysql_error($query_history);
			}
				fcommit();
			} */
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querypurdt = " Select PRqstDt_id, materialreqdt.Item_CodePacked, materialreqdt.Item_code  ".
						  " From Temp_materialreqdt As materialreqdt  ".
						  " Where materialreqdt.MReqDt_id = ".$mreqdtid.
						  " And materialreqdt.Item_CodePacked =  '".$vItemCodePacked."'  ";
						  //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						   
			$resultpurdt=mysql_query($querypurdt, $connection) or die(mysql_error());
			while($rowspurdt=mysql_fetch_array($resultpurdt)){		   
					
				// Delete From TempPorderDt For Selected Record
				$query = " DELETE FROM Temp_materialreqdt ".
						 " WHERE MReqDt_id = ".$mreqdtid;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}
				/* else if ( $config['log_file'] == 1){
				$query_history="insert into temp_prequestdt ( PRqstDt_id ,PRqst_id,temp_prequestdt_date, temp_prequestdt_operator_id, temp_prequestdt_schema, temp_prequestdt_status)".
							  "  values(".$prqstdtid.",$PRqst_id,now()
				, '".$User_Name."'
				, '".$_SESSION['dbName']."'
					, 'D')";
					if (!updateData($connection_history, $query_history, true))		 
				$message  = mysql_error($query_history);
			} */
				  
			} 
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		
		if ( $ErrorExists == 0 ){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($mreqid, $txtDate, $SPorVatChkbx, $txtReqDiscount, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, 'D', $connection);
			$message  = $message . $CalculateResult;
			
		} 
		
	
	} // End If No Constraints Found On Delete
	else echo $message;
	
	echo "[BRK]";
	$txtPorId = $SMReqId;
	exit;
}

//Confirm Purchase Request
else if($mainmode == "ConfirmTransfer" && $SMReqId != ''){

	$confirm_flag     = 1;
	$MReq_Confirmed   = 0;
	
	
	$query = " SELECT ifNull(MReq_Confirmed,0) FROM materialreq WHERE MReq_id = '".$SMReqId."'";
	//echo "<br><br>".$query;exit;
	$result = selectData($connection, $query);
	$MReq_Confirmed   = $result[0];
	
	
		
	
	if ($confirm_flag == 1 && $MReq_Confirmed == 0) {
		$query = "UPDATE materialreq SET MReq_Confirmed = 1, Confirm_date = now(), user_confirmed ='".$_SESSION['username']."'  WHERE MReq_id = '".$SMReqId."'";

		if (updateData($connection, $query, true)) {
			
			$message = "Transfer To Purchase Request Confirmed";
			/* if ( $config['log_file'] == 1){
				$query_history="insert into Prequest ( Prqst_Confirmed ,Confirm_date,user_confirmed,
				 Prqst_id,prequest_date, prequest_operator_id, prequest_schema, prequest_status)".
							  "  values(1,now(),'".$_SESSION['username']."','".$SMReqId."',now()
				, '".$User_Name."'
				, '".$_SESSION['dbName']."'
					, 'U')";
					if (!updateData($connection_history, $query_history, true))		 
				$message  = mysql_error($query_history);
			} */
		}
		else
			$message  = mysql_error();
		
	} 

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

	$AllowDelete = 1;
	$message  = '';
	
	//Check If Porder Is Posted
	$query = "SELECT ifNull(MReq_Posted,0) As MReqPosted FROM materialreq WHERE MReq_id = ".$SMReqId;
	$result = selectData($connection, $query);
	$PRqstPosted = $result[0];
	
	if ($PRqstPosted == 1 ){
		$message  = 'Delete not allowed, Material Requisition posted.';
		$AllowDelete = 0;
	}
	
	/*if ($AllowDelete == 1) {
		//Check Each prequestdt If Has RelatedId In PurchasesDt
		$query = " Select Count(prequestdt.PRqstDt_id) ".
				 " From prequestdt ".
				 " Inner Join PurchasesDt on prequestdt.PRqstDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PI' ".
				 " Where prequestdt.PRqst_id = ".$SMReqId;
				 
		$result = selectData($connection, $query);
		$PurExists = $result[0];
		
		if ($PurExists > 0 ){
			$message  = 'Delete not allowed, purchase exists for this purchase request.';
			$AllowDelete = 0;
		}
	
	}*/
	
	//Check Each materialreqdt If Approved
	if ($AllowDelete == 1) {
		$query = " Select Count(materialreqdt.MReqDt_id) ".
				 " From materialreqdt ".
				 " Where materialreqdt.MReq_id = '".$SMReqId."' ".
				 " And upper(ifnull(MReqDt_status,'x')) = 'A' ";
					 
		$result = selectData($connection, $query);
		$PrApproveExists = $result[0];
			
		if ($PrApproveExists > 0 ){
			$message  = 'Delete not allowed, Material Requisition approved.';
			$AllowDelete = 0;
		}
	}

	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
		// Delete From prequestdt For Selected Record SMReqId
		$query = " DELETE FROM prequestdt ".
				 " WHERE PRqst_id = ".$prqstid;
						 
		if (updateData($connection, $query, true)) {
			
			/* if ( $config['log_file'] == 1){
				$query_history="insert into materialreqdt ( MReq_id ,MReqDt_id,MReqdt_date, MReqdt_operator_id, MReqdt_schema, temp_MReqdt_status)".
							  "  values(".$prqstid."',$PRqstDt_id,now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
					if (!updateData($connection_history, $query_history, true))		 
				$message  = mysql_error($query_history);
			} */
										
			// Delete From prequest For Selected Record
			$select_history="select MReq_reference from materialreq WHERE MReq_id = ".$SMReqId;
			$result_history=mysql_query($select_history,$connection) or die(mysql_error());
			$rows=mysql_fetch_array($result_history);
			$reference=$row['0'];
			
			$query = " DELETE FROM materialreq ".
					 " WHERE MReq_id = ".$SMReqId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
			/* else if ( $config['log_file'] == 1){
			$query_history="insert into materialreq ( MReq_id ,MReq_reference, MReq_date, MReq_operator_id, MReq_schema, MReq_status)".
						  "  values(".$prqstid."',$reference,now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
				if (!updateData($connection_history, $query_history, true))		 
			$message  = mysql_error($query_history);
			} */
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

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

	// Delete From TempPorderDt For Selected Record
	$query = " DELETE FROM temp_materialreqdt ".
			 " WHERE MReq_id = ".$MReqId;
			 				
	if (updateData($connection, $query, true)) {
		
		/*  if ( $config['log_file'] == 1){
				$query_history="insert into temp_materialreqdt ( MReq_id , MReqDt_id, temp_MReq_date, MReqdt_operator_id, MReqdt_schema, temp_MReqdt_status)".
							  "  values(".$MReqId."',$PRqstDt_id,now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
				if(!updateData($connection_history, $query_history, true))
					  $message  = mysql_error($query_history); 
		} */
		// Delete From TempPorder For Selected Record
		$query = " DELETE FROM temp_materialreq ".
				 " WHERE MReq_id = ".$MReqId;
				 
			$select_history="select MReq_reference from temp_materialreq  WHERE MReq_id = ".$MReqId;
			$result_history=mysql_query($select_history,$connection) or die(mysql_error());
			$rows=mysql_fetch_array($result_history);
			$reference=$row['0'];
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
		
		/* else if ( $config['log_file'] == 1){
				$query_history="insert into temp_materialreq ( Prqst_id ,PRqst_reference,temp_prequest_date, temp_prequest_operator_id, temp_prequest_schema, temp_prequest_status)".
							  "  values(".$MReqId."',$reference,now(), '".$User_Name."', '".$_SESSION['dbName']."', 'D')";
			  if(!updateData($connection_history, $query_history, true))
				  $message  = mysql_error($query_history); 
		} */
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if($mainmode == "search" && $SMReqId != ''){
	
	$EditAllow   = 1;
	$ErrorExists = 0;
	$message  = '';
	
		
	//If No Constraints Exists On Edit
	if ($EditAllow == 1) {
	
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_materialreq (MReq_id, MReq_reference, MReq_date, MReq_RequestDate, MReq_RequestBy, MReq_remark, Supplier_code, MReq_SupplierContract
				, Currency_code, Costcent_code, MReq_warranty, MReq_document, MReq_DeliveryDate, MReq_DeliveryPlace, MReq_DeliveryContact, MReq_DeliveryTelephone
				, MReq_DeliveryFax, MReq_PaymentTerm, MReq_PorderDepartment, MReq_InspectionPlace, MReq_InspectionDate, MReq_Inspectionby, Project_Code, MReq_TotalQuantity
				, MReq_TotalQuantityUsed, MReq_QuantityEqual, MReq_Posted, CostCenter_code, User_Name, MReq_BelongsToGroup, MReq_BelongsToGrp, MReq_CarNo, MReq_ReducedQuantity
				, MReq_Quantity, SendReceive_Reference, Synchronized, MReq_Price, MReq_PriceBase1, MReq_PriceBase2, MReq_Taxable, MReq_TaxableBase1, MReq_TaxableBase2
				, MReq_NoneTaxable, MReq_NoneTaxableBase1, MReq_NoneTaxableBase2, MReq_DiscountAmount, MReq_DiscountBase1, MReq_DiscountBase2, MReq_Vat, MReq_VatBase1
				, MReq_VatBase2, MReq_DiscountPer, MReq_Application, MReq_Approved, MReq_ApprovedBy, MReq_Status, Status_Remark, MReq_VatChkBox, MReq_Print, MReq_Tax1
				, MReq_Tax2, MReq_Tax3, MReq_Tax4, MReq_Tax5, MReq_Tax1Base1, MReq_Tax2Base1, MReq_Tax3Base1, MReq_Tax4Base1, MReq_Tax5Base1, MReq_Tax1Base2, MReq_Tax2Base2
				, MReq_Tax3Base2, MReq_Tax4Base2, MReq_Tax5Base2, MReq_lstordsupp, MReq_lstordpayterm, MReq_lstorddeliveryterms, MReq_otherSupplier, MReq_monthlyconsumption
				, MReq_Total, MReq_Import, MReq_VATChckbx, logged_code,user_account,username,MReq_Purpose,MReq_Location,MReq_Priority,MReq_Confirmed,Confirm_date) ".
				 " SELECT MReq_id, MReq_reference, MReq_date, MReq_RequestDate, MReq_RequestBy, MReq_remark, Supplier_code, MReq_SupplierContract, Currency_code
				 , Costcent_code, MReq_warranty, MReq_document, MReq_DeliveryDate, MReq_DeliveryPlace, MReq_DeliveryContact, MReq_DeliveryTelephone
				 , MReq_DeliveryFax, MReq_PaymentTerm, MReq_PorderDepartment, MReq_InspectionPlace, MReq_InspectionDate, MReq_Inspectionby, Project_Code
				 , MReq_TotalQuantity, MReq_TotalQuantityUsed, MReq_QuantityEqual, MReq_Posted, CostCenter_code, User_Name, MReq_BelongsToGroup, MReq_BelongsToGrp
				 , MReq_CarNo, MReq_ReducedQuantity, MReq_Quantity, SendReceive_Reference, Synchronized, MReq_Price, MReq_PriceBase1, MReq_PriceBase2, MReq_Taxable
				 , MReq_TaxableBase1, MReq_TaxableBase2, MReq_NoneTaxable, MReq_NoneTaxableBase1, MReq_NoneTaxableBase2, MReq_DiscountAmount, MReq_DiscountBase1
				 , MReq_DiscountBase2, MReq_Vat, MReq_VatBase1, MReq_VatBase2, MReq_DiscountPer, MReq_Application, MReq_Approved, MReq_ApprovedBy, MReq_Status
				 , Status_Remark, MReq_VatChkBox, MReq_Print, MReq_Tax1, MReq_Tax2, MReq_Tax3, MReq_Tax4, MReq_Tax5, MReq_Tax1Base1, MReq_Tax2Base1
				 , MReq_Tax3Base1, MReq_Tax4Base1, MReq_Tax5Base1, MReq_Tax1Base2, MReq_Tax2Base2, MReq_Tax3Base2, MReq_Tax4Base2, MReq_Tax5Base2
				 , MReq_lstordsupp, MReq_lstordpayterm, MReq_lstorddeliveryterms, MReq_otherSupplier, MReq_monthlyconsumption, MReq_Total, MReq_Import
				 , MReq_VATChckbx, '".$_SESSION['useraccount']."' ,user_account,username,MReq_Purpose,MReq_Location,MReq_Priority,MReq_Confirmed,Confirm_date ".
				 " FROM materialreq ".
				 " WHERE MReq_id = ".$SMReqId;
		//echo $query;
		if (!updateData($connection, $query, true)) {
			$ErrorExists = 1;
			//$message  = mysql_error($query); 	
		}
				
	/* 	else if ( $config['log_file'] == 1){

			$query_history= " INSERT INTO temp_materialreq (MReq_id, MReq_reference, MReq_date, MReq_RequestDate, MReq_RequestBy, MReq_remark, Supplier_code, MReq_SupplierContract
						, Currency_code, Costcent_code, MReq_warranty, MReq_document, MReq_DeliveryDate, MReq_DeliveryPlace, MReq_DeliveryContact, MReq_DeliveryTelephone
						, MReq_DeliveryFax, MReq_PaymentTerm, MReq_PorderDepartment, MReq_InspectionPlace, MReq_InspectionDate, MReq_Inspectionby, Project_Code, MReq_TotalQuantity
						, MReq_TotalQuantityUsed, MReq_QuantityEqual, MReq_Posted, CostCenter_code, User_Name, MReq_BelongsToGroup, MReq_BelongsToGrp, MReq_CarNo, MReq_ReducedQuantity
						, MReq_Quantity, SendReceive_Reference, Synchronized, MReq_Price, MReq_PriceBase1, MReq_PriceBase2, MReq_Taxable, MReq_TaxableBase1, MReq_TaxableBase2
						, MReq_NoneTaxable, MReq_NoneTaxableBase1, MReq_NoneTaxableBase2, MReq_DiscountAmount, MReq_DiscountBase1, MReq_DiscountBase2, MReq_Vat, MReq_VatBase1
						, MReq_VatBase2, MReq_DiscountPer, MReq_Application, MReq_Approved, MReq_ApprovedBy, MReq_Status, Status_Remark, MReq_VatChkBox, MReq_Print, MReq_Tax1
						, MReq_Tax2, MReq_Tax3, MReq_Tax4, MReq_Tax5, MReq_Tax1Base1, MReq_Tax2Base1, MReq_Tax3Base1, MReq_Tax4Base1, MReq_Tax5Base1, MReq_Tax1Base2, MReq_Tax2Base2
						, MReq_Tax3Base2, MReq_Tax4Base2, MReq_Tax5Base2, MReq_lstordsupp, MReq_lstordpayterm, MReq_lstorddeliveryterms, MReq_otherSupplier, MReq_monthlyconsumption
						, MReq_Total, MReq_Import, MReq_VATChckbx, logged_code,user_account,username,MReq_Purpose,MReq_Location,MReq_Priority,MReq_Confirmed,Confirm_date) ".
						 " SELECT MReq_id, MReq_reference, MReq_date, MReq_RequestDate, MReq_RequestBy, MReq_remark, Supplier_code, MReq_SupplierContract, Currency_code
						 , Costcent_code, MReq_warranty, MReq_document, MReq_DeliveryDate, MReq_DeliveryPlace, MReq_DeliveryContact, MReq_DeliveryTelephone
						 , MReq_DeliveryFax, MReq_PaymentTerm, MReq_PorderDepartment, MReq_InspectionPlace, MReq_InspectionDate, MReq_Inspectionby, Project_Code
						 , MReq_TotalQuantity, MReq_TotalQuantityUsed, MReq_QuantityEqual, MReq_Posted, CostCenter_code, User_Name, MReq_BelongsToGroup, MReq_BelongsToGrp
						 , MReq_CarNo, MReq_ReducedQuantity, MReq_Quantity, SendReceive_Reference, Synchronized, MReq_Price, MReq_PriceBase1, MReq_PriceBase2, MReq_Taxable
						 , MReq_TaxableBase1, MReq_TaxableBase2, MReq_NoneTaxable, MReq_NoneTaxableBase1, MReq_NoneTaxableBase2, MReq_DiscountAmount, MReq_DiscountBase1
						 , MReq_DiscountBase2, MReq_Vat, MReq_VatBase1, MReq_VatBase2, MReq_DiscountPer, MReq_Application, MReq_Approved, MReq_ApprovedBy, MReq_Status
						 , Status_Remark, MReq_VatChkBox, MReq_Print, MReq_Tax1, MReq_Tax2, MReq_Tax3, MReq_Tax4, MReq_Tax5, MReq_Tax1Base1, MReq_Tax2Base1
						 , MReq_Tax3Base1, MReq_Tax4Base1, MReq_Tax5Base1, MReq_Tax1Base2, MReq_Tax2Base2, MReq_Tax3Base2, MReq_Tax4Base2, MReq_Tax5Base2
						 , MReq_lstordsupp, MReq_lstordpayterm, MReq_lstorddeliveryterms, MReq_otherSupplier, MReq_monthlyconsumption, MReq_Total, MReq_Import
						 , MReq_VATChckbx, '".$_SESSION['useraccount']."' ,user_account,username,MReq_Purpose,MReq_Location,MReq_Priority,MReq_Confirmed,Confirm_date ".
						 " FROM Prequest ".
						 " WHERE MReq_id = ".$SMReqId;
			$result_history=mysql_query($query_history,$connection_history);
						//echo $query_history;exit;
						
			$last_id_query ="select max(temp_prequest_history_id ) from temp_Prequest";
			$result_history=mysql_query($last_id_query,$connection_history);
			$row=mysql_fetch_array($result_history);
			$last_id=$row[0];
						  
			$update_history="update temp_materialreq set temp_mreq_date=now(),
						mreq_operator_id='".$User_Name."', 
						mreq_schema='".$_SESSION['dbName']."', temp_mreq_status='I'  
						where mreq_history_id = ".$last_id;
						
			$result_history=mysql_query($update_history,$connection_history);
			$message= mysql_error($query_history);
			// echo $update_history;exit;
} */
		//echo $message.$query; exit;				 
			
		if ($ErrorExists == 0) {
			
			$query = " INSERT INTO temp_materialreqdt (MReqDt_id, MReq_id, MReq_Date, Item_code, MReqDt_Quantity, MReqDt_QuantityUsed, MReqDt_QuantityEqual, MReqDt_Remark, Project_code, CostCent_code, 
						Item_Barcode, Currency_Code, Supplier_code, MReqDt_PrintRemark, MReqDt_PrintRow, Warehouse_Code, Porder_References, Synchronized, MReqDt_Price, MReqDt_PriceBase1, MReqDt_PriceBase2, 
						MReqDt_Discount, MReqDt_DiscountAmount, MReqDt_DiscountBase1, MReqDt_DiscountBase2, Item_ManufacturedCode, item_vat, Item_UnitCoef, Item_Unit2Qty, MReqDt_QuantityExist, MReqDt_LastPrice,
						MReqDt_LastCurrency_code, MReqDt_LastSupplier_code, MReqDt_PriceTTC, Item_description,MReqDt_OQuantity,MReqDt_CQuantity, logged_code,user_name,MReqDt_status,MReqDt_approvedlevel,
						approvedby,user_account,MReqdt_unitsalesdesc,Approved_date, MReqDt_heatno, MReqDt_RequiredDate ) ".
					 " SELECT MReqDt_id, MReq_id, MReq_Date, Item_code, MReqDt_Quantity, MReqDt_QuantityUsed, MReqDt_QuantityEqual, MReqDt_Remark, Project_code, CostCent_code, Item_Barcode, Currency_Code, 
					 Supplier_code, MReqDt_PrintRemark, MReqDt_PrintRow, Warehouse_Code, Porder_References, Synchronized, MReqDt_Price, MReqDt_PriceBase1, MReqDt_PriceBase2, MReqDt_Discount, 
					 MReqDt_DiscountAmount , MReqDt_DiscountBase1, MReqDt_DiscountBase2, Item_ManufacturedCode, item_vat, Item_UnitCoef, Item_Unit2Qty, MReqDt_QuantityExist, MReqDt_LastPrice, 
					 MReqDt_LastCurrency_code, MReqDt_LastSupplier_code, MReqDt_PriceTTC,Item_description,MReqDt_OQuantity,MReqDt_CQuantity, '".$_SESSION['useraccount']."', 
					 '".$_SESSION['username']."' ,MReqDt_status,MReqDt_approvedlevel,approvedby,user_account,MReqdt_unitsalesdesc,Approved_date, MReqDt_heatno, MReqDt_RequiredDate ".
					 " FROM materialreqdt ".
					 " WHERE MReq_id = ".$SMReqId;
			//echo $message.$query; exit;				 
		
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 			
		/* else if ( $config['log_file'] == 1){

						$query_history= "  INSERT INTO temp_PrequestDt (PRqstDt_id, PRqst_id, PRqst_Date, Item_code, PRqstDt_Quantity, PRqstDt_QuantityUsed, PRqstDt_QuantityEqual, PRqstDt_Remark
					 , Project_code, CostCent_code, Item_Barcode, Currency_Code, Supplier_code, PRqstDt_PrintRemark, PRqstDt_PrintRow, Warehouse_Code, Porder_References
					 , Synchronized, PRqstDt_Price, PRqstDt_PriceBase1, PRqstDt_PriceBase2, PRqstDt_Discount, PRqstDt_DiscountAmount, PRqstDt_DiscountBase1, PRqstDt_DiscountBase2
					 , Item_ManufacturedCode, item_vat, Item_UnitCoef, Item_Unit2Qty, PRqstDt_QuantityExist, PRqstDt_LastPrice, PRqstDt_LastCurrency_code
					 , PRqstDt_LastSupplier_code, PRqstDt_PriceTTC, Item_description,PRqstDt_OQuantity,PRqstDt_CQuantity, logged_code,user_name,PRqstDt_status,PRqstDt_approvedlevel,approvedby,user_account,prequestdt_unitsalesdesc,Approved_date ) ".
					 " SELECT PRqstDt_id, PRqst_id, PRqst_Date, Item_code, PRqstDt_Quantity, PRqstDt_QuantityUsed, PRqstDt_QuantityEqual, PRqstDt_Remark
					 , Project_code, CostCent_code, Item_Barcode, Currency_Code, Supplier_code, PRqstDt_PrintRemark, PRqstDt_PrintRow, Warehouse_Code
					 , Porder_References, Synchronized, PRqstDt_Price, PRqstDt_PriceBase1, PRqstDt_PriceBase2, PRqstDt_Discount, PRqstDt_DiscountAmount
					 , PRqstDt_DiscountBase1, PRqstDt_DiscountBase2, Item_ManufacturedCode, item_vat, Item_UnitCoef, Item_Unit2Qty, PRqstDt_QuantityExist
					 , PRqstDt_LastPrice, PRqstDt_LastCurrency_code, PRqstDt_LastSupplier_code, PRqstDt_PriceTTC,Item_description,PRqstDt_OQuantity,PRqstDt_CQuantity, '".$_SESSION['useraccount']."', '".$_SESSION['username']."' ,PRqstDt_status,PRqstDt_approvedlevel,approvedby,user_account,prequestdt_unitsalesdesc,Approved_date ".
					 " FROM PrequestDt ".
					 " WHERE PRqst_id = ".$SMReqId;
						$result_history=mysql_query($query_history,$connection_history);
						$last_id_query ="select max(temp_prequestdt_history_id ) from temp_Prequestdt";
						  $result_history=mysql_query($last_id_query,$connection_history);
						  $row=mysql_fetch_array($result_history);
						  $last_id=$row[0];
						$update_history="update temp_PrequestDt set temp_prequestdt_date=now(),
									temp_prequestdt_operator_id='".$User_Name."', 
									temp_prequestdt_schema='".$_SESSION['dbName']."', temp_prequestdt_status='I'  
									where temp_prequestdt_history_id = ".$last_id;
									  $result_history=mysql_query($update_history,$connection_history);
									  $message =mysql_error($query_history);
		} */

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


	 if($module_PRWarehouse == 1){
	$querywarehouse = "select count(*) from temp_materialreqdt where Warehouse_Code like '$warehousecode[0]' and MReq_id=$SMReqId 
						union 
						select count(*) from temp_materialreqdt where MReq_id=$SMReqId";
	$reswarehouse = mysql_query($querywarehouse,$connection);
	$numwarehouse = mysql_num_rows($reswarehouse);
	//echo $numwarehouse; exit;
	} else $numwarehouse = 1;
	if($numwarehouse == 1){ 
	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 = 'P';	
	if (empty($txtPorCategory))
		$txtPorCategory = 0;
	if (empty($txtReqDiscountAmt))
		$txtReqDiscountAmt = 0;
	if (empty($txtReqDiscount))
		$txtReqDiscount = 0;
	
	$txtCostCentCode = "".$txtCostCentCode;		
	if ($txtCostCentCode == '')
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
	
	$txtProjectCode = "".$txtProjectCode;	
	if ($txtProjectCode == '')
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
		
		
	$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_materialreqdt ".
				 " Where MReq_id = '".$SMReqId."' ".
				 " And (Item_CodePacked Is Not Null and Item_CodePacked != '') ";
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$sub_rowcount = mysql_num_rows ($sub_result);
	
	if ($sub_rowcount > 0) {
		while($sub_row=mysql_fetch_array($sub_result)){
			$ItemQty = 0;
			$ItemPackQty = 0;
			
			$CheckQty = 0;
			$PackDtCode = '';
			$PackDtQty  = 0;
			
			$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
						  " From PackDt ".
						  " Where Item_Code = '".$sub_row[0]."' ";
			$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
			while($sub_row1=mysql_fetch_array($sub_result1)){
				// PackDt Items Should Be Different And Have Same Qty
				if ($PackDtCode != '' && $PackDtCode != $sub_row1[1] && $PackDtQty  == $sub_row1[2])
					$CheckQty = 1;
				
				$PackDtCode = $sub_row1[1];
				$PackDtQty  = $sub_row1[2];
			}
			
			// If PackDt Items Are Different And Have Same Qty Then Check For Qty Differences
			if ($CheckQty == 1) {
				$sub_query1 = " Select Item_Code, Item_CodePackDt, PackDt_Quantity ".
							  " From PackDt ".
							  " Where Item_Code = '".$sub_row[0]."' ";
				$sub_result1 = mysql_query($sub_query1,$connection) or die(mysql_error());			  
				while($sub_row1=mysql_fetch_array($sub_result1)){
					$sub_query2 = " Select Item_CodePacked, Item_Code, Sum(ifNull(PRqstDt_Quantity,0)) As PRqstDtQuantity ".
								  " From temp_materialreqdt ".
								  " Where MReq_id = '".$SMReqId."' ".
								  " 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;
		
	}
	if ($txtProjectCode != '') {
		echo "txtProjectCode=".$txtProjectCode;
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCode."'";
				//echo 	$sub_query;exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
		
	}
	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;

	}
	
	echo "abs";
	//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 "lll";
	//echo $sub_query;exit;
	
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
		
		//Update Detail Amount Columns In Case Currency Is Modified
		$sub_query = " Select MReqDt_id, Currency_Code, ifNull(MReqDt_Price,0), ifNull(MReqDt_PriceBase1,0), ifNull(MReqDt_PriceBase2,0), ".
					 " ifNull(MReqDt_PriceTTC,0), ifNull(MReqDt_PriceTTCBase1,0), ifNull(MReqDt_PriceTTCBase2,0), ifNull(MReqDt_DiscountAmount,0), ".
					 " ifNull(MReqDt_DiscountBase1,0), ifNull(MReqDt_DiscountBase2,0) ".
					 " From temp_materialreqdt ".
					 " Where MReq_id = ".$SMReqId;	
		$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_materialreqdt SET  ".
							  " Currency_Code = '".$txtCurr."', ".
							  " MReqDt_Price = $vPorDtPrice, MReqDt_PriceBase1 = $vPorDtPriceBase1, MReqDt_PriceBase2 = $vPorDtPriceBase2, ".
							  " MReqDt_PriceTTC = $vPorDtPriceTTC, MReqDt_PriceTTCBase1 = $vPorDtPriceTTCBase1, MReqDt_PriceTTCBase2 = $vPorDtPriceTTCBase2, ".
							  " MReqDt_DiscountAmount = $vPorDtDiscAmt, MReqDt_DiscountBase1 = $vPorDtDiscAmtBase1, MReqDt_DiscountBase2 = $vPorDtDiscAmtBase2 ".
							  " Where MReq_id = ".$sub_row[0];
					
				//echo "abs".$sub_query1;
				//exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 
				
				/*else if ( $config['log_file'] == 1){
					$query_history="insert into temp_materialreqdt ( Currency_Code ,".
							  " MReqDt_Price , MReqDt_PriceBase1 , MReqDt_PriceBase2  ".
							  " ,MReqDt_PriceTTC ,MReqDt_PriceTTCBase1 , MReqDt_PriceTTCBase2 , ".
							  " MReqDt_DiscountAmount , MReqDt_DiscountBase1 , MReqDt_DiscountBase2 ".
							  " MReqDt_id,MReq_id,MReqDt_date, MReqDt_operator_id, MReqDt_schema, MReqDt_status )
							  values('".$txtCurr."',$vPorDtPrice,$vPorDtPriceBase1,$vPorDtPriceBase2,$vPorDtPriceTTC,$vPorDtPriceTTCBase1,$vPorDtPriceTTCBase2,
							  $vPorDtDiscAmt,$vPorDtDiscAmtBase1,$vPorDtDiscAmtBase2,$sub_row[0],$SMReqId,now()
							, '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
							  if(!updateData($connection_history, $query_history, true))
								  $message  = mysql_error($query_history); 
					}*/
			}
			
					
		}  //End Loop of prequestdt Query
		
		//Distribute The Total Discount On Detail Table
		$sub_query3 = " Select Sum((ifNull(MReqDt_Quantity,0)*ifNull(MReqDt_Price,0))-((ifNull(MReqDt_Quantity,0)*ifNull(MReqDt_Price,0)*ifNull(MReqDt_Discount,0))/100)) As Total ".
					  " From temp_materialreqdt ".
					  " Where MReq_id = ".$SMReqId;
		$sub_result3 = selectData($connection, $sub_query3);
		$vPorTotal   = $sub_result3[0];	
		$vPorDisAmt	 = $txtReqDiscountAmt;
		
		$sub_query4 = " Select MReqDt_id,  ".
					  " ((ifNull(MReqDt_Quantity,0)*ifNull(MReqDt_Price,0))-((ifNull(MReqDt_Quantity,0)*ifNull(MReqDt_Price,0)*ifNull(MReqDt_Discount,0))/100)) As Total ".
					  " From temp_materialreqdt As materialreqdt  ".
					  " Where materialreqdt.MReq_id = ".$SMReqId;
					  //" And prequestdt.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_materialreqdt SET MReqDt_DiscountAmount = $vPorDtDiscAmt, ".
						 " MReqDt_DiscountBase1 = $vPorDtDiscAmtBase1, MReqDt_DiscountBase2 = $vPorDtDiscAmtBase2  ".
						 " Where MReqDt_id = ".$vPorDtId;
						 //" And Logged_Code = '".$PLoggedCode."' ";
			
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 
			/*if ( $config['log_file'] == 1){
				$query_history = " insert into temp_materialreqdt ( MReqDt_DiscountAmount , MReqDt_DiscountBase1 , MReqDt_DiscountBase2, MReqDt_id,  ".
								 " MReqDt_id, MReqDt_date, MReqDt_operator_id, MReqDt_schema, MReqDt_status )  values ".
								 " ('".$vPorDtDiscAmt."', $vPorDtDiscAmtBase1, $vPorDtDiscAmtBase2, $SMReqId, $vPorDtId, now(), '".$User_Name."', '".$_SESSION['dbName']."'
									, 'U')";
			  if(!updateData($connection_history, $query_history, true))
				  $message  = mysql_error($query_history); 
			  
			}*/
		}
				 
										 
		
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SMReqId, $txtDate, $SPorVatChkbx, $txtReqDiscount, $txtReqDiscountAmt, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Module_AdditionalTaxes, $PurchaseTTC, 'P', $connection);
		$message  = $message . $CalculateResult;
		
		$preq="select * from temp_materialreqdt where MReq_id=".$SMReqId ;
			$result_pre = mysql_query($preq, $connection);
				 $row=mysql_fetch_row($result_pre);
				$PRqstDt_id=$row['0'] ;
				
		$sub_query2 = " UPDATE temp_materialreqdt SET ".
					  " MReq_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 MReq_id = $SMReqId ";
		
		//echo $sub_query2."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
		
						 
		$query = " UPDATE temp_materialreq SET ".
				 " MReq_date = '".insertMySQLDate($txtDate)."', ".
				 " MReq_remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
				 " MReq_RequestDate = '".insertMySQLDate($txtDate)."', ".
				 " MReq_DeliveryDate = '".insertMySQLDate($txtDeliveryDate)."', ".
				 " MReq_RequestBy = '".ereg_replace("'", "\'", trim($txtRequestBy))."', ".
				 " MReq_DeliveryPlace = '".ereg_replace("'", "\'", trim($txtDeliveryPlace))."',  MReq_DeliveryContact = '".ereg_replace("'", "\'", trim($txtDeliveryContact))."', ".
				 " Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcent_code = $CostCentCode, MReq_VatChkBox = $SPorVatChkbx, ".
				 " MReq_Import = '".$txtPorCategory."', MReq_Status =  '".$txtPorStatus."', ".
				 " Status_Remark = '".ereg_replace("'", "\'", trim($txtStatusRemark))."', ".
				 " MReq_Purpose = '".ereg_replace("'", "\'", trim($txtPurpose))."' ,".
				 " MReq_Location = '".ereg_replace("'", "\'", trim($txtLocation))."', ".
				 " MReq_Priority = '".ereg_replace("'", "\'", trim($txtPriority))."' ".
				 " WHERE MReq_id= '$SMReqId' ";
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; //exit;
				//echo $query;exit;
		if ($result){
			/*
			if ( $config['log_file'] == 1){
				$query_history = " insert into temp_materialreq ( MReq_date, MReq_remark , MReq_RequestDate,  MReq_RequestBy, MReq_DeliveryPlace, MReq_DeliveryContact , Currency_Code, Project_Code,Costcent_code, ".
								 " MReq_VatChkBox, MReq_Import, MReq_Status, Status_Remark, MReq_Purpose, MReq_Location, MReq_Priority , MReq_id, temp_MReq_date, temp_MReq_operator_id, temp_MReq_schema, temp_MReq_status)".
								 " values(  '".insertMySQLDate($txtDate)."', '".ereg_replace("'", "\'", trim($txtRemark))."', '".insertMySQLDate($txtDate)."', '".ereg_replace("'", "\'", trim($txtRequestBy))."', ".
								 "  '".ereg_replace("'", "\'", trim($txtDeliveryPlace))."','".ereg_replace("'", "\'", trim($txtDeliveryContact))."', ".
								 "'".$txtCurr."', $ProjectCode,  $CostCentCode, $SPorVatChkbx, ".
								 " '".$txtPorCategory."','".$txtPorStatus."', ".
								 " '".ereg_replace("'", "\'", trim($txtStatusRemark))."', ".
								 " '".ereg_replace("'", "\'", trim($txtPurpose))."' ,".
								 " '".ereg_replace("'", "\'", trim($txtLocation))."', ".
								 "  '".ereg_replace("'", "\'", trim($txtPriority))."' ".
									"'$SMReqId',now()
									, '".$User_Name."'
									, '".$_SESSION['dbName']."'
									, 'U')";
									
									
							  if(!updateData($connection_history, $query_history, true))
								  $message  = mysql_error($query_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 materialreq WHERE MReq_id = '$SMReqId '";
			$result  = selectData($connection, $query);
			
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From temp_materialreq where MReq_id = '".$SMReqId."'";
			//echo $query; 
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();		
				$query = "SELECT CopyData_TempMaterialRequisition('".$SMode."', ".$SMReqId.", '".$_SESSION['useraccount']."', '".$_SESSION['username']."') FROM Dual ";
				echo $query."<br>";
				//exit;
				$result = selectData($connection, $query);
				$result = $result[0];
					
				if ($result != 0){
					/* if ( $config['log_file'] == 1){
				
						$query_history = "SELECT CopyData_TempMaterialRequisition('".$SMode."', ".$SMReqId.", '".$_SESSION['useraccount']."', '".$_SESSION['username']."','".$_SESSION['dbName']."') FROM Dual ";
						$result = selectData($connection_history, $query_history);
						$result1 = $result[0];
						$result_history=mysql_query($query_history,$connection_history);
					} */
												  
			
					fcommit();
						
					$query   = " SELECT MReq_reference, Costcent_code, Project_Code FROM materialreq WHERE MReq_id = $SMReqId ";
					$result  = selectData($connection, $query);
					$vPorRef = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
						
					if ($vPorRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1) ||
						($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1)) {
							
						if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						else $vProjCostCent = '';
						
						fbegin();
						$vPorRef = get_nextsequence('MaterialReq_Reference',$vProjCostCent,$connection);	
						fcommit();
										
						$query = " UPDATE materialreq SET MReq_reference = $vPorRef ";
								 
						/* if ($Module_PrequestAutoApprove == 1){
							$query = $query.", MReq_Approved = 1 ";
						} */
						$query = $query." WHERE MReq_id = $SMReqId ";
							
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						
						
						/* else 	
						if ( $config['log_file'] == 1){
							
							
							
							$query_history="insert into materialreq ( MReq_reference, MReq_date, MReq_operator_id, MReq_schema, MReq_status)
								   values( $vPorRef , 1, now(), '".$User_Name."', '".$_SESSION['dbName']."', 'U')";
										
							if (!updateData($connection_history, $query_history, true)) 
								$message  = mysql_error($query_history);
							  	
							  
						} */
							
						/* if ($Module_PrequestAutoApprove == 1){
							$query = " UPDATE prequestdt SET PRqstDt_approvedlevel = 1, PRqstDt_status = 'A' WHERE PRqst_id = $SMReqId ";
								
							if (!updateData($connection, $query, true)) 
								$message  = mysql_error();	
							else if ( $config['log_file'] == 1){
							
						
							$query_history="insert into prequestdt ( PRqstDt_approvedlevel ,PRqstDt_status,PRqst_id".
								
								  ",prequestdt_date, prequestdt_operator_id, prequestdt_schema, prequestdt_status)
								   values( 1 ,'A',$SMReqId".
										",now()
										, '".$User_Name."'
										, '".$_SESSION['dbName']."'
										, 'U')";
							
						if (!updateData($connection_history, $query_history, true)) 
							$message  = mysql_error($query_history);
					
							  
								}
						} */
					}
					
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempMaterialRequisition 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 ($ErrorExists == 1)	
			$message = 'Save not allowed. Please check for Supplier/Project/Costcenter Code.';
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';		
			
		frollback();
	}	
 } else {
	$ErrorExists = 1;
	$message = "Warehouses codes do not match!";
} 
}

else if($mainmode == "confirmmaterialreq"){
	$SMReqId = $_GET["SMReqId"];
		
	$confirm_flag     = 1;
	$MReq_Confirmed   = 0;
	
	
	$query = " SELECT ifNull(MReq_Confirmed,0) FROM materialreq WHERE MReq_id = '".$SMReqId."'";
	$result = selectData($connection, $query);
	$MReq_Confirmed   = $result[0];
	
	if ($confirm_flag == 1 && $MReq_Confirmed == 0) {
		$query = "UPDATE materialreq SET MReq_Confirmed = 1, MReq_Cancelled = 0, Confirm_date = now(), user_confirmed ='".$_SESSION['username']."'  WHERE MReq_id = '".$SMReqId."'";

		if (updateData($connection, $query, true)) {
			$message = "Transfer To Purchase Request Confirmed";
		}
		else
			$message  = mysql_error();
	} 
	
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
	
} 
else if($mainmode == "cancelmaterialreq"){
	$SMReqId = $_GET["SMReqId"];
		
	$cancel_flag     = 1;
	$MReq_Cancelled   = 0;
	
	
	$query = " SELECT ifNull(MReq_Cancelled,0) FROM materialreq WHERE MReq_id = '".$SMReqId."'";
	$result = selectData($connection, $query);
	$MReq_Cancelled   = $result[0];
	
	if ($cancel_flag == 1 && $MReq_Cancelled == 0) {
		$query = "UPDATE materialreq SET MReq_Confirmed = 0, MReq_Cancelled = 1, Confirm_date = null, user_confirmed = null  WHERE MReq_id = '".$SMReqId."'";

		if (updateData($connection, $query, true)) {
			$message = "Transfer To Purchase Request Confirmed";
		}
		else
			$message  = mysql_error();
	} 
	
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
	
}

$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=".$SMReqId."&PrPorRef=".$vPorRef);
if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_MaterialRequisition.php?actionmode=".$mode."&mainaction=".$mainmode."&PrMReqId=".$SMReqId."&PrPorRef=".$vPorRef."&message=".$message);
	else
		header ("Location: ./Form_MaterialRequisition.php?actionmode=submitrecord&mainaction=".$mainmode."&txtMReqId=".$SMReqId."&message=".$message);
}	
else if($mode == "" && ($mainmode == "ConfirmTransfer" ))
	header ("Location: ./Form_MaterialRequisitionSearch.php?message=".$message);	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_MaterialRequisitionSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_MaterialRequisitionSearchPending.php");
else if ($mode == "deletedt" )		
	header ("Location: ./Form_MaterialRequisition.php?actionmode=".$mode."&mainaction=".$mainmode."&txtMReqId=".$SMReqId."&message=".$message);	
else if ($mode == "" && $mainmode == "search" )	{
	if ($EditAllow == 1)
		header ("Location: ./Form_MaterialRequisitionSearch.php?PMode=1");
	else
		header ("Location: ./Form_MaterialRequisitionSearch.php?PMode=0&message=".$message);
}


						  
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_materialreqdt SET  ".
				 " MReqDt_Price = MReqDt_PriceTTC, MReqDt_PriceBase1 = MReqDt_PriceTTCBase1, MReqDt_PriceBase2 = MReqDt_PriceTTCBase2 ".
				 " Where MReq_id = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
		
		
		/* if ( $config['log_file'] == 1){
			$query_history="insert into temp_materialreqdt ( MReqDt_Price ,MReqDt_PriceBase1 ,MReqDt_PriceBase2,MReq_id,temp_MReqdt_date, temp_MReqdt_operator_id, temp_MReqdt_schema, temp_MReqdt_status)
							values( MReqDt_PriceTTC ,MReqDt_PriceTTCBase1,MReqDt_PriceTTCBase2,".$PId.",now()
							, '".$User_Name."'
							, '".$_SESSION['dbName']."'
							, 'U')";
			$result_history=mysql_query($query_history,$connection_history);
											  
		}*/
	}
	else if ($PPurchaseTTC ==1 && $PVatChk == 1 && $PMode == 'P') {

		$query = " UPDATE temp_materialreqdt SET  ".
				 " MReqDt_Price      = (MReqDt_PriceTTC / (1 + Item_Vat/100)), ".
				 " MReqDt_PriceBase1 = (MReqDt_PriceTTCBase1 / (1 + Item_Vat/100)), ".
				 " MReqDt_PriceBase2 = (MReqDt_PriceTTCBase2 / (1 + Item_Vat/100)) ".
				 " Where MReq_id = ".$PId;

		//echo $query; exit;
		$result=mysql_query($query,$connection);
		
		
			
		/* if ( $config['log_file'] == 1){

			$query_history="insert into temp_materialreqdt ( MReqDt_Price ,MReqDt_PriceBase1 ,MReqDt_PriceBase2,MReq_id, temp_MReqdt_date, temp_MReqdt_operator_id, temp_MReqdt_schema, temp_MReqdt_status)
						   values( (MReqDt_PriceTTC / (1 + Item_Vat/100)) ,(MReqDt_PriceTTCBase1 / (1 + Item_Vat/100)),(MReqDt_PriceTTCBase2 / (1 + Item_Vat/100)),".$PId."
							,now()
							, '".$User_Name."'
							, '".$_SESSION['dbName']."'
							, 'U')";
			$result_history=mysql_query($query_history,$connection_history);
											  
		}*/
	}	
	//echo $query; exit;
	
	
	
	//Calculating Master Amounts
	$sub_query = " Select Item_Code, ((ifNull(MReqDt_Quantity,0)*ifNull(MReqDt_Price,0))-((ifNull(MReqDt_Quantity,0)*ifNull(MReqDt_Price,0)*ifNull(MReqDt_Discount,0))/100)) As Total, ifNull(Item_Vat,0),  ".
				 " MReqDt_Quantity, ifNull(MReqDt_DiscountAmount,0), ifNull(Item_Tax1,0), ifNull(Item_Tax2,0), ifNull(Item_Tax3,0), ifNull(Item_Tax4,0), ifNull(Item_Tax5,0) ".
				 " From temp_materialreqdt ".
				 " Where MReq_id = ".$PId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";	
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error($sub_query));
	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();
		
	$sub_query1 = " UPDATE temp_materialreq SET ".
				  " MReq_Taxable = $vPorTaxable, MReq_TaxableBase1 = $vPorTaxableBase1, MReq_TaxableBase2 = $vPorTaxableBase2, ".
				  " MReq_NoneTaxable = $vPorNoneTaxable, MReq_NoneTaxableBase1 = $vPorNoneTaxableBase1, MReq_NoneTaxableBase2 = $vPorNoneTaxableBase2, ".
				  " MReq_DiscountAmount = $vPorDiscountAmt, MReq_DiscountBase1 = $vPorDiscountAmtBase1, MReq_DiscountBase2 = $vPorDiscountAmtBase2, ".
				  " MReq_DiscountPer = $vPorDiscountPer, MReq_Vat = $vPorVat, MReq_VatBase1 = $vPorVatBase1, MReq_VatBase2 = $vPorVatBase2, ".
				  " MReq_Total = $vPorGrossTotal, MReq_TotalBase1 = $vPorGrossTotalBase1, MReq_TotalBase2 = $vPorGrossTotalBase2, ".
				  " MReq_Tax1 = $vPorTax1, MReq_Tax1Base1 = $vPorTax1B1, MReq_Tax1Base2 = $vPorTax1B2,  ".
				  " MReq_Tax2 = $vPorTax2, MReq_Tax2Base1 = $vPorTax2B1, MReq_Tax2Base2 = $vPorTax2B2,  ".
				  " MReq_Tax3 = $vPorTax3, MReq_Tax3Base1 = $vPorTax3B1, MReq_Tax3Base2 = $vPorTax3B2,  ".
				  " MReq_Tax4 = $vPorTax4, MReq_Tax4Base1 = $vPorTax4B1, MReq_Tax4Base2 = $vPorTax4B2,  ".
				  " MReq_Tax5 = $vPorTax5, MReq_Tax5Base1 = $vPorTax5B1, MReq_Tax5Base2 = $vPorTax5B2,  ".
				  " MReq_VATChckbx = $PVatChk  ".
				  " WHERE MReq_ID = ".$PId;
				  //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					
				
	$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_prequest ( MReq_Taxable ,MReq_TaxableBase1 ,MReq_TaxableBase2,MReq_NoneTaxable,
				MReq_NoneTaxableBase1,MReq_NoneTaxableBase2,MReq_DiscountAmount,MReq_DiscountBase1,MReq_DiscountBase2,
				MReq_DiscountPer,MReq_Vat,MReq_VatBase1,MReq_VatBase2,MReq_Total,MReq_TotalBase1,MReq_TotalBase2,MReq_Tax1,
				MReq_Tax1Base1,MReq_Tax1Base2,MReq_Tax2,MReq_Tax2Base1,MReq_Tax2Base2,MReq_Tax3,MReq_Tax3Base1,MReq_Tax3Base2,
				MReq_Tax4,MReq_Tax4Base1,MReq_Tax4Base2,MReq_Tax5,MReq_Tax5Base1,MReq_Tax5Base2,MReq_VATChckbx,MReq_ID
				temp_MReq_date, temp_MReq_operator_id, temp_MReq_schema, temp_MReq_status)
				values($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  ,".$PId."
				,now()
				, '".$User_Name."'
				, '".$_SESSION['dbName']."'
				, 'U')";
				$result_history=mysql_query($query_history,$connection_history);
				$message=mysql_error($query_history);
		}*/
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}						  
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 formatdate($dateval){
	if($dateval != ''){
	$ndate = explode("/", $dateval);
	$dateval = $ndate[2]."-".$ndate[1]."-".$ndate[0];
	$dateval = "'".$dateval."'";
	} else $dateval = "NULL";
	return $dateval;
}



?>