<?php

session_start();

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

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

//Set Time Execution For the Report
set_time_limit(0);

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



$querylog="select FI_PurchasesVATMod, ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."'";
$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 ifNull(Module_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_NegativeQuantity,0) As Module_NegativeQuantity, ".
			 " ifNull(Module_ReferenceByCostcenter,0) As Module_ReferenceByCostcenter, ifNull(Module_ReferenceByProject,0) As Module_ReferenceByProject, ".
			 " ifNull(Module_rawmaterial,0) As Module_RawMaterial, ifNull(Module_DoubleUnit,0) As Module_DoubleUnit, ifNull(Module_Unit1Method,0) As Module_Unit1Method, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_ExpireDate,0) As Module_ExpireDate, ifNull(Module_SerialNo,0) As Module_SerialNo ".
		     " 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"];}   

$SPurType    		= $_GET["SPurType"]; if ($SPurType == ""){$SPurType = $_POST["SPurType"];} 
$SPurId    			= $_GET["SPurId"]; if ($SPurId == ""){$SPurId = $_POST["SPurId"];} 
$SPurDtId			= $_GET["SPurDtId"]; if ($SPurDtId == ""){$SPurDtId = $_POST["SPurDtId"];} 

$txtPurId    		= $_GET["txtPurId"]; if ($txtPurId == ""){$txtPurId = $_POST["txtPurId"];} 
$txtDate 			= $_GET["txtDate"]; if ($txtDate == ""){$txtDate = $_POST["txtDate"];} 
$txtMaturityDate 	= $_GET["txtMaturityDate"]; if ($txtMaturityDate == ""){$txtMaturityDate = $_POST["txtMaturityDate"];} 
$txtSupplier 	   	= $_GET["txtSupplier"]; if ($txtSupplier == ""){$txtSupplier = $_POST["txtSupplier"];} 
$txtCurr   			= $_GET["txtCurr"]; if ($txtCurr == ""){$txtCurr = $_POST["txtCurr"];} 
$txtPurCategory   	= $_GET["txtPurCategory"]; if ($txtPurCategory == ""){$txtPurCategory = $_POST["txtPurCategory"];} 
$txtRemark  		= $_GET["txtRemark"]; if ($txtRemark == ""){$txtRemark = $_POST["txtRemark"];} 
$txtProjectCode 	= $_GET["txtProjectCode"]; if ($txtProjectCode == ""){$txtProjectCode = $_POST["txtProjectCode"];} 
$txtCostCentCode	= $_GET["txtCostCentCode"]; if ($txtCostCentCode == ""){$txtCostCentCode = $_POST["txtCostCentCode"];} 
$txtInvoiceNo		= $_GET["txtInvoiceNo"]; if ($txtInvoiceNo == ""){$txtInvoiceNo = $_POST["txtInvoiceNo"];} 

$PPurId    			= $_GET["PPurId"]; if ($PPurId == ""){$PPurId = $_POST["PPurId"];} 
$PPurDate 			= $_GET["PPurDate"]; if ($PPurDate == ""){$PPurDate = $_POST["PPurDate"];} 
$PPurCurr 			= $_GET["PPurCurr"]; if ($PPurCurr == ""){$PPurCurr = $_POST["PPurCurr"];} 
$PPurMaturityDate   = $_GET["PPurMaturityDate"]; if ($PPurMaturityDate == ""){$PPurMaturityDate = $_POST["PPurMaturityDate"];} 
$PPurSupplier 	   	= $_GET["PPurSupplier"]; if ($PPurSupplier == ""){$PPurSupplier = $_POST["PPurSupplier"];} 
$PPurCategory   	= $_GET["PPurCategory"]; if ($PPurCategory == ""){$PPurCategory = $_POST["PPurCategory"];} 
$PPurRemark  		= $_GET["PPurRemark"]; if ($PPurRemark == ""){$PPurRemark = $_POST["PPurRemark"];} 
$PPurProjectCode 	= $_GET["PPurProjectCode"]; if ($PPurProjectCode == ""){$PPurProjectCode = $_POST["PPurProjectCode"];} 
$PPurCostCentCode	= $_GET["PPurCostCentCode"]; if ($PPurCostCentCode == ""){$PPurCostCentCode = $_POST["PPurCostCentCode"];} 
$PPurInvoiceNo		= $_GET["PPurInvoiceNo"]; if ($PPurInvoiceNo == ""){$PPurInvoiceNo = $_POST["PPurInvoiceNo"];} 

$lstWarehouse		= $_GET["lstWarehouse"]; if ($lstWarehouse == ""){$lstWarehouse = $_POST["lstWarehouse"];} 
$txtItemCode		= $_GET["txtItemCode"]; if ($txtItemCode == ""){$txtItemCode = $_POST["txtItemCode"];} 
$txtPurDtRemark		= $_GET["txtPurDtRemark"]; if ($txtPurDtRemark == ""){$txtPurDtRemark = $_POST["txtPurDtRemark"];} 
$txtPurDtQty		= $_GET["txtPurDtQty"]; if ($txtPurDtQty == ""){$txtPurDtQty = $_POST["txtPurDtQty"];} 
$txtPurDtQty2		= $_GET["txtPurDtQty2"]; if ($txtPurDtQty2 == ""){$txtPurDtQty2 = $_POST["txtPurDtQty2"];} 
$txtProjectCodeDt	= $_GET["txtProjectCodeDt"]; if ($txtProjectCodeDt == ""){$txtProjectCodeDt = $_POST["txtProjectCodeDt"];} 
$txtCostCentCodeDt	= $_GET["txtCostCentCodeDt"]; if ($txtCostCentCodeDt == ""){$txtCostCentCodeDt = $_POST["txtCostCentCodeDt"];} 
$txtPurDtVolume		= $_GET["txtPurDtVolume"]; if ($txtPurDtVolume == ""){$txtPurDtVolume = $_POST["txtPurDtVolume"];} 
$txtPurDtBatchNo	= $_GET["txtPurDtBatchNo"]; if ($txtPurDtBatchNo == ""){$txtPurDtBatchNo = $_POST["txtPurDtBatchNo"];} 
$txtPurDtExpireDate	= $_GET["txtPurDtExpireDate"]; if ($txtPurDtExpireDate == ""){$txtPurDtExpireDate = $_POST["txtPurDtExpireDate"];} 
$txtgrncostprice	= $_GET["txtgrncostprice"]; if ($txtgrncostprice == ""){$txtgrncostprice = $_POST["txtgrncostprice"];} 




/*
print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<script type="text/javascript" language="javascript">


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

</head>
<body>
<form name='insertpurchase' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SPurType' value='$SPurType'>
<input type='text' name='SPurId' value='$SPurId'>
<input type='text' name='SPurDtId' value='$SPurDtId'>
HERE;
*/
$message='';

//insert details
if ($mode == "submitrecord" || $mode == "submitrecord-ajax" ){
	
	$ErrorExists = 0;
	$InsertAllow = 1;
	
	if (empty($PPurCategory))
		$PPurCategory = 0;
			
	if (empty($PPurCostCentCode))
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$PPurCostCentCode."'";
			
	if (empty($PPurProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$PPurProjectCode."'"; 

	//Check For Supplier, Project and Costcenter Codes Before Insert
	if ($PPurCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PPurCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Costcenter Code.';
		}
	}
	if ($PPurProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PPurProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Project Code.';
		}
	}
	if ($PPurSupplier != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$PPurSupplier."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Supplier Code.';
		}
	}
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	//Insert Master Table
	if ($SPurId == "" && $ErrorExists == 0){
	
			
		fbegin();	
		$PPurId = get_nextsequence('Grn_Id','',$connection);
		fcommit();
		
		$Acc_Query = " SELECT Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, ".
					 " DebitAccount, if( ifNull(DebitCurdefault,0)=1, DebitCur, '".$PPurCurr."') As DebitCur ".
					 " FROM purchasesetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		$Supp_Query = " SELECT ifNull(Supplier_VAT, 0) ".
					  " FROM Suppliers ".
					  " WHERE Ledger_Number = '".ereg_replace("'", "\'", trim($PPurSupplier))."'";
		$Supp_Result = selectData($connection, $Supp_Query);
		if (empty($Supp_Result[0])) $Supp_Result[0] = 0;
				
		fbegin();
		$query = " INSERT INTO temp_grnpurchases (Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_VatChkbx, Purchase_Mode, Journal_Type, Journal_Id, Purchase_BelongsToGroup, ".
				 " Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitAccount, Purchase_DebitCur, Purchase_Import, Purchase_Type, Purchase_Grn, Purchase_PackingListRef, Purchase_FormMNo, ".
				 " User_Account, Logged_Code) ".
				 " VALUES ( ".$PPurId.", Null, '".insertMySQLDate($PPurDate)."', '".ereg_replace("'", "\'", trim($PPurRemark))."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', ".
				 "          '".$PPurCurr."', $ProjectCode, $CostCentCode, '".ereg_replace("'", "\'", trim($PPurInvoiceNo))."', '".insertMySQLDate($PPurMaturityDate)."' , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ".
				 "          0, 0, 0, $Supp_Result[0], 0, 'PR', Null, $FI_BelongsToGrp, '".$Acc_Result[0]."', '".$Acc_Result[1]."', '".$Acc_Result[2]."', '".$Acc_Result[3]."', '".$Acc_Result[4]."', ".
				 "          '".$Acc_Result[5]."', '".$Acc_Result[6]."', '".$PPurCategory."', '".$PPurType."', 1, '".ereg_replace("'", "\'", trim($PPurPackRef))."', '".ereg_replace("'", "\'", trim($PPurFormMNo))."', ".
				 "          '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' )";
		
		//echo $query."<br>";exit;					 
		$result=mysql_query($query,$connection);
		
		
		if ($result){
			$SPurId = $PPurId;
			fcommit();
		}else{
			$PPurId = "";
			$SPurId = "";
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	
	//Insert Detail Tables
	if ($SPurId != "" && $SPurDtId == ""  && $ErrorExists == 0){
	
		
		if (empty($txtPurDtQty))
		    $txtPurDtQty = 0;      		
		if (empty($txtPurDtQty2))
		    $txtPurDtQty2 = 0;	
		if (empty($txtPurDtVolume))   
			$txtPurDtVolume = 'Null';	
			
		if (empty($txtPurDtExpireDate))		$vPurDtExpireDate = 'Null';
		else  $vPurDtExpireDate = "'".insertMySQLDate($txtPurDtExpireDate)."'";	
			
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}	
		
		if (empty($txtPurDtPackagingNo))
			$txtPurDtPackagingNo = 0;      		
		if (empty($txtPurDtNbrUnit))
			$txtPurDtNbrUnit = 0;		
				
		$vPurDtDirectStkDbt = '';
		$vPurDtDirectStkCrd = '';
		$vPurDtDirectStkCur = '';
		$vPurDtVatAcc	    = '';
		$vPurDtItemAcc      = '';
		$vPurStpDirectStkDbt = '';
		$vPurStpDirectStkCrd = '';
		$vPurStpDirectStkCur = '';
		$vPurStpVatAcc       = '';
		$vPurStpDebitAcc     = '';
		$vTranStpDirectStkDbt = '';
		$vTranStpDirectStkCrd = '';
		$vTranStpDirectStkCur = '';
		$vTranStpVatAcc       = '';
		$vTranStpNonRmVatAcc  = '';
		$vTranStpRmVatAcc     = '';
		$vTranStpNonRmTTCIncAcc  = '';
		$vTranStpRmTTCIncAcc     = '';
		$vTranStpNonRmAcc  = '';
		$vTranStpRmAcc     = '';
		
		$vItemCodeFinished     = '';
		$vItemCodeSemiFinished = '';
				
		
		$WarningMsg = '';
		
		$query = " SELECT ifNull(Item_Production, 0), ifNull(Item_SemiFinished, 0), ifNull(Item_Pack, 0) ".
			     " FROM Items WHERE item_Code = '".$txtItemCode."'";
		$result = selectData($connection, $query);
		$ItemFinished   = $result[0];
		$ItemSemiFinish = $result[1];
		$ItemPack	    = $result[2];
				
				   
		if ($ItemFinished == 1) {
			$vItemCodeFinished     = "'".$txtItemCode."'";
			$vItemCodeSemiFinished = 'Null';
		}
		else if ($ItemSemiFinish == 1) {
			$vItemCodeFinished     = 'Null';
			$vItemCodeSemiFinished = "'".$txtItemCode."'";
		}
		else {
			$vItemCodeFinished     = 'Null';
			$vItemCodeSemiFinished = 'Null';
		}
		
		if ($ItemPack != 1) {	

			$query = "SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 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];
			$ItemNonStock   = $result[6];
				   
			$vItemUnitCoef = 0;
			$vItemUnit2Qty = 0;
			if ($Module_DoubleUnit == 1) {
				$vItemUnitCoef = $ItemUnit;
				$vItemUnit2Qty = $txtPurDtQty2;
			}
				
			// Get DirectStock Accounts
			$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock  ".
					 " FROM purchasesetup ";
						 
			$result = selectData($connection, $query);
				
			$vPurStpDirectStkDbt   = $result[0];
			$vPurStpDirectStkCrd   = $result[1];
			$vPurStpDirectStkCur   = $result[2];	
			$vPurStpVatAcc         = $result[3];	
			$vPurStpDebitAcc       = $result[4];	
			$vPurStpVatNonStockAcc = $result[5];	
				
				
			$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
					 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
					 " FROM transactionsetup ".
					 " WHERE Journal_type = 'PR' ".
					 " AND Group_code = '".$ItemGroupCode."'  ";
						 
			$result = selectData($connection, $query);
				
			$vTranStpDirectStkDbt = $result[0];
			$vTranStpDirectStkCrd = $result[1];
			$vTranStpDirectStkCur = $result[2];
			$vTranStpVatAcc       = $result[3];
			$vTranStpNonRmVatAcc  = $result[4];
			$vTranStpRmVatAcc     = $result[5];
			$vTranStpNonRmTTCIncAcc  = $result[6];
			$vTranStpRmTTCIncAcc     = $result[7];
			$vTranStpNonRmAcc  = $result[8];
			$vTranStpRmAcc     = $result[9];
				
			if ($Module_RawMaterial == 1) {
				$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
				$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
				$vPurDtDirectStkCur = $vTranStpDirectStkCur;
				$vPurDtVatAcc       = $vTranStpVatAcc;
					
				if ($ItemVat > 0) {
					if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
				}
				else {
					if ($ItemProd == 1) {
						if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
					}	
					else {
						if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
					}
				}	
			} 
			else {
				$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
				$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
				$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
				
				if ($ItemNonStock == 1)		
					$vPurDtVatAcc = $vPurStpVatNonStockAcc;
				else
					$vPurDtVatAcc = $vPurStpVatAcc;
					
				if ($ItemVat > 0)
					$vPurDtItemAcc = $vPurStpVatAcc;
				else
					$vPurDtItemAcc = $vPurStpDebitAcc;	
			}
				
			$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
			$sub_resultVat = selectData($connection, $sub_queryVat);
			if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
				
			fbegin();
			$txtPurDtId = get_nextsequence('Grndt_Id','',$connection);	
			fcommit();
			
			fbegin();
			$query = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, ".
					 " PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked,Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, ".
					 " Purchasedt_ItemAccount, Item_CodeFinished, Item_CodeSemiFinished, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code  ) ".
					 " VALUES ( ".$txtPurDtId.", ".$PPurId.", '".$PPurCurr."', '".insertMySQLDate($PPurDate)."', '".ereg_replace("'", "\'", trim($PPurSupplier))."', 'PR',  ".
					 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$txtItemCode."', $txtPurDtQty, $txtPurDtVolume, ".
					 "          '".ereg_replace("'", "\'", trim($txtPurDtRemark))."' ,  '".ereg_replace("'", "\'", trim($PPurInvoiceNo))."',  Null,   ".
					 "          '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', '".$vPurDtItemAcc."', ".
					 "          $vItemCodeFinished, $vItemCodeSemiFinished, $vItemUnitCoef, $vItemUnit2Qty, $vPurDtExpireDate, '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."', ".
					 "         '".$_SESSION['useraccount']."') ";
			
		
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
				
			if ($result){
				fcommit();
			
			}else{
				$txtPurDtId = "";
				$message  = mysql_error(); 
				frollback();
			}				
			
		}	// End Case Not Pack Item
		else {
			
				fbegin();
				
				if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack") {
					$querypackdt = " SELECT PackDt1.Item_Code, PackDt1.Item_CodePackDt, PackDt1.PackDt_Quantity, PackDt1.PackDt_CostPercentage ".
								   " FROM PackDt, PackDt As PackDt1, Items ".
								   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
								   " AND PackDt.Item_CodePackDt = PackDt1.Item_Code ".
								   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
								   " AND ifNull(Items.Item_SemiFinished,0) = 1 ".
								   " UNION ".
								   " SELECT PackDt.Item_Code, PackDt.Item_CodePackDt, PackDt.PackDt_Quantity, PackDt.PackDt_CostPercentage ".
								   " FROM PackDt, Items ".
								   " WHERE PackDt.Item_Code = '".$txtItemCode."'  ".
								   " AND PackDt.Item_CodePackDt = Items.Item_Code ".
								   " AND ifNull(Items.Item_SemiFinished,0) = 0 ";
				} else {
					$querypackdt = " SELECT Item_Code, Item_CodePackDt, PackDt_Quantity, PackDt_CostPercentage ".
								   " FROM PackDt ".
								   " WHERE Item_Code = '".$txtItemCode."'  ";
				}
				
				//echo $querypackdt;
				$resultpackdt=mysql_query($querypackdt, $connection) or die(mysql_error());
				while($rowspackdt=mysql_fetch_array($resultpackdt)){			   
				
					if ($lstItemType == "FinishGoodPack" || $lstItemType == "SemiFinishPack")	$vItemCodePacked = '';
					else $vItemCodePacked = $rowspackdt[0];
					
					$vItemCode       = $rowspackdt[1];
					$vPackDtQty      = $rowspackdt[2];
					$vPackDtCostPer  = $rowspackdt[3];
						   
					
					fbegin();
					$vPurDtId = get_nextsequence('Grndt_Id','',$connection);
					fcommit();

					$vPurDtQty = $txtPurDtQty*$vPackDtQty;
					
					$query = " SELECT Item_Vat, ITEM_MAXQTY, Group_code, ifNull(Item_Production, 0), ifNull(Item_TTCInclude, 0), ifNull(Item_Unit, 0), ifNull(Item_NonStock, 0) ".
					         " FROM Items WHERE item_Code = '".$vItemCode."'";
					$result = selectData($connection, $query);
					$ItemVat 	   = $result[0];
					$Item_MaxQty   = $result[1];
					$ItemGroupCode = $result[2];
					$ItemProd 	   = $result[3];
					$ItemTTCInc    = $result[4];
					$ItemUnit  	   = $result[5];
					$ItemNonStock  = $result[6];
					
					$vItemUnitCoef = 0;
					$vItemUnit2Qty = 0;
					if ($Module_DoubleUnit == 1) {
						$vItemUnitCoef = $ItemUnit;
						
						if ($Module_Unit1Method == 1)
							$vItemUnit2Qty = $vPurDtQty*$vItemUnitCoef;
						else	
							$vItemUnit2Qty = $vPurDtQty/$vItemUnitCoef;
					}
						
						
					$vPurDtDirectStkDbt = '';
					$vPurDtDirectStkCrd = '';
					$vPurDtDirectStkCur = '';
					$vPurDtVatAcc	    = '';
					$vPurDtItemAcc      = '';
					$vPurStpDirectStkDbt = '';
					$vPurStpDirectStkCrd = '';
					$vPurStpDirectStkCur = '';
					$vPurStpVatAcc       = '';
					$vPurStpDebitAcc     = '';
					$vTranStpDirectStkDbt = '';
					$vTranStpDirectStkCrd = '';
					$vTranStpDirectStkCur = '';
					$vTranStpVatAcc       = '';
					$vTranStpNonRmVatAcc  = '';
					$vTranStpRmVatAcc     = '';
					$vTranStpNonRmTTCIncAcc  = '';
					$vTranStpRmTTCIncAcc     = '';
					$vTranStpNonRmAcc  = '';
					$vTranStpRmAcc     = '';
					
									
				
					// Get DirectStock Accounts
					$query = " SELECT Directstockdebit, Directstockcredit, Directstockcurrency_code, VatAccount, DebitAccount, VATAccountNonStock  ".
							 " FROM purchasesetup ";
							 
					$result = selectData($connection, $query);
					
					$vPurStpDirectStkDbt   = $result[0];
					$vPurStpDirectStkCrd   = $result[1];
					$vPurStpDirectStkCur   = $result[2];	
					$vPurStpVatAcc         = $result[3];	
					$vPurStpDebitAcc       = $result[4];	
					$vPurStpVatNonStockAcc = $result[5];
					
					
					$query = " SELECT Trans_DirectStkDbt, Trans_DirectStkCrd, Trans_DirectStkCur, Trans_VATAccount, Trans_NonRMVatAcc, ".
							 " Trans_RMVatAcc, Trans_NonRMTTCIncAcc, Trans_RMTTCIncAcc, Trans_NonRMAcc, Trans_RMAcc ".
							 " FROM transactionsetup ".
							 " WHERE Journal_type = 'PR' ".
							 " AND Group_code = '".$ItemGroupCode."'  ";
							 
					$result = selectData($connection, $query);
					
					$vTranStpDirectStkDbt = $result[0];
					$vTranStpDirectStkCrd = $result[1];
					$vTranStpDirectStkCur = $result[2];
					$vTranStpVatAcc       = $result[3];
					$vTranStpNonRmVatAcc  = $result[4];
					$vTranStpRmVatAcc     = $result[5];
					$vTranStpNonRmTTCIncAcc  = $result[6];
					$vTranStpRmTTCIncAcc     = $result[7];
					$vTranStpNonRmAcc  = $result[8];
					$vTranStpRmAcc     = $result[9];
					
					if ($Module_RawMaterial == 1) {
						$vPurDtDirectStkDbt = $vTranStpDirectStkDbt;
						$vPurDtDirectStkCrd = $vTranStpDirectStkCrd;
						$vPurDtDirectStkCur = $vTranStpDirectStkCur;
						$vPurDtVatAcc       = $vTranStpVatAcc;
						
						if ($ItemVat > 0) {
							if ($ItemProd == 1)	$vPurDtItemAcc = $vTranStpNonRmVatAcc; else $vPurDtItemAcc = $vTranStpRmVatAcc;
						}
						else {
							if ($ItemProd == 1) {
								if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpNonRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpNonRmAcc;
							}	
							else {
								if ($ItemTTCInc == 1) $vPurDtItemAcc = $vTranStpRmTTCIncAcc; else $vPurDtItemAcc = $vTranStpRmAcc;
							}
						}
					} 
					else {
						$vPurDtDirectStkDbt = $vPurStpDirectStkDbt;
						$vPurDtDirectStkCrd = $vPurStpDirectStkCrd;
						$vPurDtDirectStkCur = $vPurStpDirectStkCur;		
						
						if ($ItemNonStock == 1)		
							$vPurDtVatAcc = $vPurStpVatNonStockAcc;
						else
							$vPurDtVatAcc = $vPurStpVatAcc;
						
						if ($ItemVat > 0)
							$vPurDtItemAcc = $vPurStpVatAcc;
						else
							$vPurDtItemAcc = $vPurStpDebitAcc;	
					}
					
					$sub_queryVat = " SELECT GetVATAccount('".$PPurSupplier."','".$vPurDtVatAcc."') from dual ";
					$sub_resultVat = selectData($connection, $sub_queryVat);
					if ($sub_resultVat[0] != '') $vPurDtVatAcc = $sub_resultVat[0];
					
					$query = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, ".
							 " PurchaseDt_Volume,Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, Item_qtyPacked,Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, ".
							 " PurchaseDt_VATAccount, Purchasedt_ItemAccount, Item_CodeFinished, Item_CodeSemiFinished, Item_UnitCoef, Item_Unit2Qty,PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code)  ".
							 " VALUES ( ".$vPurDtId.", ".$PPurId.", '".$PPurCurr."', '".insertMySQLDate($PPurDate)."' , '".ereg_replace("\'", "''", trim($PPurSupplier))."', 'PR', ".
							 "          $ProjectCodeDt, $CostCentCodeDt, '".$lstWarehouse."', '".$vItemCode."',  $vPurDtQty, $txtPurDtVolume, ".
							 "          '".ereg_replace("'", "\'", trim($txtPurDtRemark))."', '".ereg_replace("'", "\'", trim($PPurInvoiceNo))."',  if('".$vItemCodePacked."'='', Null, '".$vItemCodePacked."'), ".
							 "          $txtPurDtQty, '".$vPurDtDirectStkDbt."', '".$vPurDtDirectStkCrd."', '".$vPurDtDirectStkCur."', '".$vPurDtVatAcc."', '".$vPurDtItemAcc."', ".
							 "          $vItemCodeFinished, $vItemCodeSemiFinished, $vItemUnitCoef, $vItemUnit2Qty, $vPurDtExpireDate, '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."', '".$_SESSION['useraccount']."')".
	 
			
					$result=mysql_query($query,$connection);
							
					//echo $query;
				} // End Loop Of Packdt
				
				
				
				if ($result){

					fcommit();
				}else{
					$txtPurDtId = "";
					$message  = mysql_error(); 
					frollback();
				}	
			
			
		} // End CasePack Item
		
	}
}
//Edit Detail Tables
if (($mode == "editdt" || $mode == "editdt-ajax") && $SPurId != "" && $SPurDtId != ""){

	$ErrorExists == 0;
	
	if ($txtItemCode != '') {
		$sub_query = " Select Count(Item_Code) From Items ".
					 " Where Item_Code = '".$txtItemCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Item Code.';
		}
	}
	if ($lstWarehouse != '') {
		$sub_query = " Select Count(Warehouse_Code) From Warehouse ".
					 " Where Warehouse_Code = '".$lstWarehouse."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Warehouse Code.';
		}
	}
	if ($txtProjectCodeDt != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Project Code.';
		}
	}
	if ($txtCostCentCodeDt != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCodeDt."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Detail Costcenter Code.';
		}
	}
	
	if ($ErrorExists == 0) {
	
		if (empty($txtPurDtQty))
			$txtPurDtQty = 0;      		
		if (empty($txtPurDtQty2))
			$txtPurDtQty2 = 0;	
		if (empty($txtPurDtVolume))   
			$txtPurDtVolume = 'Null';	
			
		if (empty($txtPurDtExpireDate))		$vPurDtExpireDate = 'Null';
		else  $vPurDtExpireDate = "'".insertMySQLDate($txtPurDtExpireDate)."'";
		
		if ($Module_ProjectDt == 1){
			if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} 
		if ($Module_CostCenterDt == 1) {
			if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		}
			
						   
							
		fbegin();	
								
		$query = " UPDATE temp_grnpurchasesdt SET  ".
				 " PurchaseDt_Quantity = $txtPurDtQty, Item_Unit2Qty = $txtPurDtQty2, PurchaseDt_Volume = $txtPurDtVolume, ".
				 " Purchasedt_Remark = '".ereg_replace("'", "\'", trim($txtPurDtRemark))."', PurchaseDt_ExpireDate = $vPurDtExpireDate, ".
				 " PurchaseDt_BatchNo = '".ereg_replace("'", "\'", trim($txtPurDtBatchNo))."' ";
				 if($txtgrncostprice!=""){
				 if($txtgrncostprice!=0){
					 
				 	$query = $query." ,PurchaseDt_costBase1 = '".ConvertCurrency($PPurCurr, $base1, insertMySQLDate($PPurDate), $txtgrncostprice, $connection)."' ".
				 " ,PurchaseDt_costBase2 = '".ConvertCurrency($PPurCurr, $base2, insertMySQLDate($PPurDate), $txtgrncostprice, $connection)."' ".
				 " ,PurchaseDt_cost = '".ereg_replace("'", "\'", trim($txtgrncostprice))."' ";
				 }
				 }
				//$message=$PPurCurr." ".insertMySQLDate($PPurDate)." ".$txtgrncostprice;
				 
		if ($Module_ProjectDt == 1)
			$query = $query.", Project_Code = $ProjectCodeDt ";
		if ($Module_CostCenterDt == 1)	
			$query = $query.", CostCent_Code = $CostCentCodeDt ";
			
		$query = $query." Where PurchaseDt_ID = ".$SPurDtId;
			
		
		//echo $query; exit;
		$result=mysql_query($query,$connection);
		if ($result){
			fcommit();
						
		}else{
			$message  = mysql_error($connection); 
			frollback();
		}				
	}		
	
}

	
//Delete Detail Mode
else if ($mode == "deletedt" ){

	$AllowDelete = 0;
	$message  = '';
	
	
	
	if ($AllowDelete == 0) {
		//Check Each PurchaseDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From Temp_GrnPurchasesDt As GrnPurchasesDt ".
				 " Inner Join Temp_Purchasesserialno As Purchasesserialno on Purchasesserialno.GrnDt_Id = GrnPurchasesDt.PurchaseDt_Id ".
				 " Where GrnPurchasesDt.PurchaseDt_ID = '".$SPurDtId."' ".
				 " And GrnPurchasesDt.Journal_Type = 'PR' ".
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'PR' ";
 
		$result = selectData($connection, $query);
		$SerNoUsedExists = $result[0];
		
		if ($SerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial no in use.';
			$AllowDelete = 1;
		}
	
	}
	
	if ($AllowDelete == 0) {
		//Check Each GrnDt If Has RelatedId In PurchasesDt
		$query = " Select Count(GrnPurchasesDt.PurchaseDt_id) ".
				 " From GrnPurchasesDt ".
				 " Inner Join PurchasesDt on GrnPurchasesDt.PurchaseDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PR' ".
				 " Where GrnPurchasesDt.PurchaseDt_ID = '".$SPurDtId."' ".
				 " And GrnPurchasesDt.Journal_Type = 'PR' ";

		$result = selectData($connection, $query);
		$PurchaseExists = $result[0];
		
		if ($PurchaseExists > 0 ){
			$message  = 'Delete not allowed, Good receive note exists in purchases.';
			$AllowDelete = 1;
		}
	
	}
	

	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
		
		$ErrorExists    = 0;

		$querypack = " SELECT GrnPurchasesDt.Item_CodePacked, GrnPurchasesDt.Item_code ".
					 " FROM Temp_GrnPurchasesDt As GrnPurchasesDt ".
					 " Where GrnPurchasesDt.PurchaseDt_ID = '".$SPurDtId."'";
					 //" 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 TempPucrhasesSerialNo For Selected Record
			$query = " DELETE FROM Temp_Purchasesserialno ".
					 " WHERE GrnDt_id  = ".$SPurDtId.
					 " AND Journal_Type = 'PR' ";
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						 
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
					
					
			// Delete From TempPucrhaseDt For Selected Record
			$query = " DELETE FROM Temp_GrnPurchasesDt ".
					 " WHERE PurchaseDt_id = ".$SPurDtId;
					 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
			if (!updateData($connection, $query, true)) {
				$message  = mysql_error();
				$ErrorExists = 1;
				frollback();
			}  
			else {
				fcommit();
			}
				
		}
		// Item Packed Case
		else {
			
			$message = '';
			
			$querypurdt = " Select PurchaseDt_ID, GrnPurchasesDt.Item_CodePacked, GrnPurchasesDt.Item_code  ".
						  " From Temp_GrnPurchasesDt As GrnPurchasesDt  ".
						  " Where GrnPurchasesDt.Purchase_ID = ".$SPurId.
						  " And GrnPurchasesDt.Item_CodePacked =  '".$vItemCodePacked."'  ";
						  //" And Logged_Code = '".$_SESSION['useraccount']."' ";
						   
			$resultpurdt=mysql_query($querypurdt, $connection) or die(mysql_error());
			while($rowspurdt=mysql_fetch_array($resultpurdt)){		   
					
				$vPurDtId =	$rowspurdt[0];
					
				// Delete From TempPucrhasesSerialNo For Selected Record
				$query = " DELETE FROM Temp_Purchasesserialno ".
						 " WHERE GrnDt_id  = ".$vPurDtId.
						 " AND Journal_Type = 'PR' ";
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
								 
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
							
						
				// Delete From TempPucrhaseDt For Selected Record
				$query = " DELETE FROM Temp_GrnPurchasesDt ".
						 " WHERE PurchaseDt_id = ".$vPurDtId;
						 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				
				  
				if (!updateData($connection, $query, true)) {
					$message  = mysql_error(); 
					$ErrorExists = 1;
					frollback();
				}  
				  
			}
			
			if ( $ErrorExists == 0 )
				fcommit();
				
		
		} // End Item Packed Case
		

	} // End If No Constraints Found On Delete
	
	
}

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

	$AllowDelete = 1;
	$message  = '';
	
	//Check If Purchase Is Posted
	$query = "SELECT ifNull(Purchase_Posted,0) As PurchasePosted FROM GrnPurchases WHERE Purchase_id = ".$SPurId;
	$result = selectData($connection, $query);
	$PurPosted = $result[0];
	
	if ($PurPosted == 1 ){
		$message  = 'Delete not allowed, purchase posted.';
		$AllowDelete = 0;
	}
	
	if ($AllowDelete == 1) {
		//Check Each GrnPurchasesDt If Has RelatedId In PurchasesDt
		$query = " Select Count(GrnPurchasesDt.PurchaseDt_id) ".
				 " From GrnPurchasesDt ".
				 " Inner Join PurchasesDt on GrnPurchasesDt.PurchaseDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PR' ".
				 " Where GrnPurchasesDt.Purchase_id = '".$SPurId."' ".
				 " And GrnPurchasesDt.Journal_Type = 'PR' ";

		$result = selectData($connection, $query);
		$PurchaseExists = $result[0];
		
		if ($PurchaseExists > 0 ){
			$message  = 'Delete not allowed, GRN converted to purchase.';
			$AllowDelete = 0;
		}
	
	}
	

	
	if ($AllowDelete == 1) {
		//Check Each PurchaseDt If Has Serial No Used
		$query = " Select Count(SerialNo_Code) ".
				 " From GrnPurchasesDt ".
				 " Inner Join Purchasesserialno on Purchasesserialno.GrnDt_Id = GrnPurchasesDt.PurchaseDt_Id ".
				 " Where GrnPurchasesDt.Purchase_id = '".$SPurId."' ".
				 " And GrnPurchasesDt.Journal_Type = 'PR' ".
				 " And ifNull(SerialNo_Used,0) = 1 ".
				 " And Purchasesserialno.Journal_Type = 'PR' ";
 
		$result = selectData($connection, $query);
		$PurSerNoUsedExists = $result[0];
		
		if ($PurSerNoUsedExists > 0 ){
			$message  = 'Delete not allowed, serial no in use.';
			$AllowDelete = 0;
		}
	
	}
	

	//If No Constraints Exists On Delete
	if ($AllowDelete == 1) {
	
		//Update Used Serials Set USed=0 For Related GrnPurchase Serials
		$sub_query = " SELECT RelatedSerial_Id FROM Purchasesserialno ".
					 " WHERE GrnDt_id In (Select PurchaseDt_id From GrnPurchasesDt Where Purchase_id = '".$SPurId."' ) ".
					 " AND Journal_Type = 'PR' ";
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_rows=mysql_fetch_array($sub_result)){
		
			$sub_query1 = " UPDATE purchasesserialno ".
						  " Set SerialNo_Used = 0, flagunique = 0 ".
						  "	WHERE Serial_ID = '".$sub_rows[0]."'";
						  
			if (!updateData($connection, $sub_query1, true))		 
				$message  = mysql_error(); 		  
		}
		
		
		// Delete From PucrhasesSerialNo For Selected Record
		$query = " DELETE FROM Purchasesserialno ".
				 " WHERE GrnDt_id In (Select PurchaseDt_id From GrnPurchasesDt Where Purchase_id = ".$SPurId." ) ".
				 " AND Journal_Type = 'PR' ";
					 
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
				
		// Delete From PucrhasesDt For Selected Record
		$query = " DELETE FROM GrnPurchasesDt ".
				 " WHERE Purchase_id = ".$SPurId;
					 
		if (updateData($connection, $query, true)) {
			// Delete From Pucrhases For Selected Record
			$query = " DELETE FROM GrnPurchases ".
					 " WHERE Purchase_id = ".$SPurId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
				
		
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

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

			 
	// Delete From TempPucrhasesSerialNo For Selected Record
	$query = " DELETE FROM Temp_Purchasesserialno ".
			 " WHERE GrnDt_id In (Select PurchaseDt_id From Temp_GrnPurchasesDt Where Purchase_id = ".$SPurId." ) ".
			 " AND Journal_Type = 'PR' ";
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (!updateData($connection, $query, true))		 
		$message  = mysql_error(); 
			
	// Delete From TempPucrhasesDt For Selected Record
	$query = " DELETE FROM Temp_GrnPurchasesDt ".
			 " WHERE Purchase_id = ".$SPurId;
			 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
				 
	if (updateData($connection, $query, true)) {
		// Delete From TempPucrhases For Selected Record
		$query = " DELETE FROM Temp_GrnPurchases ".
				 " WHERE Purchase_id = ".$SPurId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	
	

}

//Search Mode	
else if($mainmode == "search" && $SPurId != ''){
	
	$ErrorExists = 0;
	$AllowEdit = 1;
	$message  = '';
	
	if ($AllowEdit == 1) {
		//Check Each GrnPurchasesDt If Has RelatedId In PurchasesDt
		$query = " Select Count(GrnPurchasesDt.PurchaseDt_id) ".
				 " From GrnPurchasesDt ".
				 " Inner Join PurchasesDt on GrnPurchasesDt.PurchaseDt_id = PurchasesDt.RelatedDt_id ".
				 " And PurchasesDt.Journal_Type = 'PR' ".
				 " Where GrnPurchasesDt.Purchase_id = '".$SPurId."' ".
				 " And GrnPurchasesDt.Journal_Type = 'PR' ";

		$result = selectData($connection, $query);
		$PurchaseExists = $result[0];
		
		if ($PurchaseExists > 0 ){
			$message  = 'Edit not allowed, Return GRN converted to return purchase.';
			$AllowEdit = 0;
		}
	
	}
	

	if ($AllowEdit == 1) {
	
		//Copy Data From Main Tables To Temp Tables
		$query = " INSERT INTO temp_grnpurchases (Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, ".
				 " Journal_Type, Journal_Id, Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, ".
				 " Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
				 " Purchase_DebitAccount, Purchase_VatChkbx, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, Purchase_PackingListRef, Purchase_FormMNo, Purchase_ReturnRef, ".
				 " User_Account, Logged_Code) ".
				 " SELECT Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_Charges, Purchase_ChargesBase1, Purchase_ChargesBase2, Purchase_Mode, ".
				 " Journal_Type, Journal_Id, Purchase_tax1, Purchase_tax1base1, Purchase_tax1base2, Purchase_tax2, Purchase_tax2base1, Purchase_tax2base2, Purchase_tax3, Purchase_tax3base1, Purchase_tax3base2, Purchase_tax4, ".
				 " Purchase_tax4base1, Purchase_tax4base2, Purchase_tax5, Purchase_tax5base1, Purchase_tax5base2, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitCur, ".
				 " Purchase_DebitAccount, Purchase_VatChkbx, Purchase_BelongsToGroup, Purchase_Import, Purchase_Type, Purchase_Grn, Porder_Ref, Purchase_PorderReferences, Purchase_PackingListRef, Purchase_FormMNo, Purchase_ReturnRef, ".
				 " User_Account, '".$_SESSION['useraccount']."' ".
				 " FROM GrnPurchases ".
				 " WHERE Purchase_id = ".$SPurId;
		
		if (!updateData($connection, $query, true)) {
			  $ErrorExists = 1;
			  $message  = mysql_error(); 	
		}
			
		//echo $message.$query; exit;				 
		
		if ($ErrorExists == 0) {
			$query = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, ".
					 " PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, ".
					 " PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, PurchaseDt_Charges, PurchaseDt_ChargesBase1, ".
					 " PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, Purchasedt_ItemAccount, ".
					 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, RelatedDt_Id, Item_CodeFinished, Item_CodeSemiFinished, Item_qtyPacked, Related_Ref, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code ,PurchaseDt_cost,PurchaseDt_costBase1,PurchaseDt_costBase2 ) ".
					 " SELECT PurchaseDt_id, Purchase_id, Currency_Code, Purchase_Date, Supplier_Code, Journal_Type, Project_Code, CostCent_Code, Warehouse_Code, Item_code, PurchaseDt_Quantity, PurchaseDt_Price, PurchaseDt_PriceBase1, ".
					 " PurchaseDt_PriceBase2, PurchaseDt_DiscountPer, PurchaseDt_DiscountAmount, PurchaseDt_DiscountBase1, PurchaseDt_DiscountBase2, Item_VAT, PurchaseDt_Volume, Purchasedt_Remark, Purchase_invoiceNo, Item_CodePacked, ".
					 " PurchaseDt_ChargePer, PurchaseDt_ChargesAmnt, PurchaseDt_ChargesAmntB1, PurchaseDt_ChargesAmntB2, PurchaseDt_PriceTTC, PurchaseDt_PriceTTCbase1, PurchaseDt_PriceTTCbase2, PurchaseDt_Charges, PurchaseDt_ChargesBase1, ".
					 " PurchaseDt_ChargesBase2, PurchaseDt_VatCharge, PurchaseDt_VatChargeBase1, PurchaseDt_VatChargeBase2, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, PurchaseDt_VATAccount, Purchasedt_ItemAccount, ".
					 " Item_Tax1, Item_Tax2, Item_Tax3, Item_Tax4, Item_Tax5, RelatedDt_Id, Item_CodeFinished, Item_CodeSemiFinished, Item_qtyPacked, Related_Ref, Item_UnitCoef, Item_Unit2Qty, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, '".$_SESSION['useraccount']."' ,PurchaseDt_cost,PurchaseDt_costBase1,PurchaseDt_costBase2 ".
					 " FROM GrnPurchasesdt ".
					 " WHERE Purchase_id = ".$SPurId;
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 			

			$query = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, PurchaseDt_id, GrnDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, Warehouse_code, Item_ExpireDate, Item_BatchNo, Logged_Code ) ".
					 " SELECT Serial_ID, Purchasesserialno.Journal_Type, Purchasesserialno.PurchaseDt_id, Purchasesserialno.GrnDt_ID, Purchasesserialno.Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, ".
					 " SerialNo_Quantity, Purchasesserialno.Warehouse_code, Item_ExpireDate, Item_BatchNo, '".$_SESSION['useraccount']."' ".
					 " FROM Purchasesserialno ".
					 " Inner Join Temp_GrnPurchasesDt on Purchasesserialno.GrnDt_id = Temp_GrnPurchasesDt.PurchaseDt_id ".
					 //" WHERE PurchaseDt_id In ( Select PurchaseDt_id From Temp_GrnPurchasesDt Where Purchase_id = ".$SPurId." ) ". 
					 " WHERE Purchase_id = ".$SPurId.
					 " AND Purchasesserialno.Journal_Type = 'PR' ";
					 
			
			if (!updateData($connection, $query, true))
			  $message  = mysql_error(); 		

		}
	}
	
}

//Load Invoices
else if($mainmode == "loadgrn"){

	if ($SPurId == "" && $SelectedRec != ''){	
		fbegin();	
		$vPurId = get_nextsequence('Grn_Id','',$connection);	
		fcommit();

				 
		$query = " INSERT INTO temp_grnpurchases (Purchase_id, Purchase_Reference, Purchase_Date, Purchase_Remark, Supplier_code, Currency_Code, Project_Code, Costcent_code, Purchase_InvoiceNo, Journaldt_valuedate, Purchase_Posted, ".
				 " Purchase_Taxable, Purchase_TaxableBase1, Purchase_TaxableBase2, Purchase_NoneTaxable, Purchase_NoneTaxableBase1, Purchase_NoneTaxableBase2, Purchase_DiscountAmount, Purchase_DiscountBase1, Purchase_DiscountBase2, ".
				 " Purchase_DiscountPer, Purchase_Total, Purchase_TotalBase1, Purchase_TotalBase2, Purchase_VAT, Purchase_VATBase1, Purchase_VATBase2, Purchase_VatChkbx, Purchase_Mode, Journal_Type, Journal_Id, Purchase_BelongsToGroup, ".
				 " Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, Purchase_Acctax5, Purchase_DebitAccount, Purchase_DebitCur, Purchase_Import, Purchase_Type, Purchase_Grn, Purchase_PackingListRef, Purchase_FormMNo, ".
				 " Purchase_ReturnRef, User_Account, Logged_Code) ".
				 " SELECT $vPurId, Null, now(), Purchase_Remark, GrnPurchases.Supplier_code, GrnPurchases.Currency_Code, GrnPurchases.Project_Code, GrnPurchases.Costcent_code, Purchase_InvoiceNo, ADDDATE(now(), ifNull(Suppliers.Supplier_PaymentTerms,0)), 0,  ".
				 " 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Purchase_VatChkbx, Purchase_Mode, 'PR', Null, Purchase_BelongsToGroup, Purchase_Acctax1, Purchase_Acctax2, Purchase_Acctax3, Purchase_Acctax4, ".
				 " Purchase_Acctax5, Purchase_DebitAccount, Purchase_DebitCur, Purchase_Import, Purchase_Type, Purchase_Grn, Purchase_PackingListRef, Purchase_FormMNo, Purchase_Reference, '".$_SESSION['useraccount']."', ".
				 " '".$_SESSION['useraccount']."' ".
				 " From GrnPurchases Inner Join Suppliers on GrnPurchases.Supplier_Code = Suppliers.Ledger_Number ".
				 " Where GrnPurchases.Purchase_ID = '".$SelectedRec."' ".
				 " And GrnPurchases.Journal_Type = 'PI' ";		 

		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SPurId = $vPurId;
			fcommit();
		}else{
			$vPurId = "";
			$SPurId = "";
			$message  = mysql_error(); 
			frollback();
		}
		
	}
	
	
	if ($SPurId != '') 
    {   	
		$ErrorExists = 0;
		
		$vPurId = $SPurId;
		
		$sub_query = " SELECT GrnPurchasesDt.PurchaseDt_Id, GrnPurchasesDt.Currency_Code, now(), GrnPurchasesDt.Supplier_Code, GrnPurchasesDt.Project_Code, GrnPurchasesDt.CostCent_Code, GrnPurchasesDt.Warehouse_Code, 
					 GrnPurchasesDt.Item_code, GrnPurchasesDt.Item_CodePacked, GrnPurchasesDt.Item_QtyPacked, ifNull(GrnPurchasesDt.PurchaseDt_Quantity,0), GrnPurchasesDt.PurchaseDt_Volume, 
					 GrnPurchasesDt.Item_UnitCoef, GrnPurchasesDt.Item_Unit2Qty, Purchasedt_Remark, GrnPurchasesDt.Purchase_invoiceNo, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, 
					 Purchasedt_ItemAccount, PurchaseDt_VATAccount, GrnPurchasesDt.Item_CodeFinished, GrnPurchasesDt.Item_CodeSemiFinished, GrnPurchases.Purchase_Reference, GrnPurchasesDt.PurchaseDt_ExpireDate, GrnPurchasesDt.PurchaseDt_BatchNo,PurchaseDt_cost,PurchaseDt_costBase1,PurchaseDt_costBase2 
					 FROM GrnPurchasesDt Inner Join GrnPurchases on GrnPurchasesDt.Purchase_ID = GrnPurchases.Purchase_ID ";
		
		if($SPurDtId != '')			 
			$sub_query = $sub_query." WHERE GrnPurchasesDt.PurchaseDt_Id In (".$SPurDtId.") And GrnPurchasesDt.Journal_Type = 'PI' ";
		else 
			$sub_query = $sub_query." WHERE GrnPurchasesDt.Purchase_ID = '".$SelectedRec."' And GrnPurchasesDt.Journal_Type = 'PI' ";		
			
		//echo $sub_query; exit;
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
		
			 
			$sub_query1 = " Select ifNull(Sum(ifNull(PR.PurchaseDt_Quantity,0)),0) As QuantityReturned ".
					      " From GrnPurchasesDt PR ".
					      " Where PR.RelatedDt_ID =  '".$sub_row[0]."' ".
						  " And PR.Purchase_Id != '".$vPurId."' ".
						  " And PR.Journal_Type = 'PR' ";
			$sub_result1 = selectData($connection, $sub_query1);
			if ($sub_result1[0] == '') $sub_result1[0] = 0;
	
	
			$sub_query2 = " Select Sum(ifNull(Temp_GrnPurchasesDt.PurchaseDt_Quantity,0)) As QuantityReturnedTemp ".
					      " From Temp_GrnPurchasesDt ".
					      " Where Temp_GrnPurchasesDt.RelatedDt_ID =  '".$sub_row[0]."' ".
						  " And Temp_GrnPurchasesDt.Journal_Type = 'PR' ".
						  " And Temp_GrnPurchasesDt.Purchase_Id = '".$vPurId."' ";
			$sub_result2 = selectData($connection, $sub_query2);
			if ($sub_result2[0] == '') $sub_result2[0] = 0;	

			
			//Get The Remaining Qty
			$vPurDtQty = ($sub_row[10] - ($sub_result1[0] + $sub_result2[0]));
			
			if ($vPurDtQty > 0 ) {
			
				$vItemUnitCoef = 0;
				$vItemUnit2Qty = 0;
				if ($Module_DoubleUnit == 1) {
					$vItemUnitCoef = $sub_row[12];
					
					if ($Module_Unit1Method == 1)
						$vItemUnit2Qty = $vPurDtQty*$vItemUnitCoef;
					else	
						$vItemUnit2Qty = $vPurDtQty/$vItemUnitCoef;
				}
			
				fbegin();
				$vPurDtId = get_nextsequence('Grndt_Id','',$connection);	
				fcommit();
				
					 
				fbegin();
				
				$sub_query3 = " INSERT INTO temp_grnpurchasesdt (PurchaseDt_id, Purchase_id, RelatedDt_Id, Currency_Code, Purchase_Date, Supplier_Code, Project_Code, CostCent_Code, Warehouse_Code, Item_code, Item_CodePacked, ". 
							  " Item_QtyPacked, PurchaseDt_Quantity, PurchaseDt_Volume, Item_UnitCoef, Item_Unit2Qty, Purchasedt_Remark, Purchase_invoiceNo, Purchasedt_DirectStkDbt, Purchasedt_DirectStkCrd, Purchasedt_DirectStkCur, ".
							  " Purchasedt_ItemAccount, PurchaseDt_VATAccount, Item_CodeFinished, Item_CodeSemiFinished, PurchaseDt_OldData, Journal_Type, Related_Ref, PurchaseDt_ExpireDate, PurchaseDt_BatchNo, Logged_Code,PurchaseDt_cost,PurchaseDt_costBase1,PurchaseDt_costBase2 ) ".
							  " VALUES ( $vPurDtId, $vPurId, '".$sub_row[0]."', '".$sub_row[1]."', '".$sub_row[2]."', '".$sub_row[3]."', '".$sub_row[4]."', '".$sub_row[5]."', '".$sub_row[6]."', '".$sub_row[7]."', if('".$sub_row[8]."'='', Null, '".$sub_row[8]."'), ". 
							  " '".$sub_row[9]."', $vPurDtQty, '".$sub_row[11]."', '".$vItemUnitCoef."', '".$vItemUnit2Qty."', '".$sub_row[14]."', '".$sub_row[15]."', '".$sub_row[16]."', '".$sub_row[14]."', '".$sub_row[18]."', '".$sub_row[19]."', '".$sub_row[20]."', ".
							  " '".$sub_row[21]."', '".$sub_row[22]."', 0, 'PR', '".$sub_row[23]."', '".$sub_row[24]."', '".$sub_row[25]."', '".$_SESSION['useraccount']."', '".$sub_row[26]."', '".$sub_row[27]."', '".$sub_row[28]."' ) ";

				//echo $sub_query3; exit;	
				$sub_result3=mysql_query($sub_query3,$connection);
			
			
				if ($sub_result3){
					$sub_query4 = " SELECT Serial_ID, purchasesserialno.Item_Code, purchasesserialno.Warehouse_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, ifNull(SerialNo_Quantity,0), ifNull(SerialNo_QuantitySold,0)  ".
								  " FROM purchasesserialno ".
								  " WHERE purchasesserialno.PurchaseDt_ID  = '".$sub_row[0]."' ".
								  " AND purchasesserialno.Journal_Type = 'PI' ".
								  " AND Not Exists ( Select 1 from purchasesserialno as purchasesserialno1 ".
								  "                  Where purchasesserialno1.RelatedSerial_Id = purchasesserialno.Serial_ID ".
								  "                  And purchasesserialno1.Journal_Type = 'PR'  ".
								  "                  union  ".
								  "                  Select 1 from temp_purchasesserialno ".
								  "                  Where temp_purchasesserialno.RelatedSerial_Id = purchasesserialno.Serial_ID ".
								  "                  And temp_purchasesserialno.Journal_Type = 'PR' ) ";
								  
					//echo $sub_query4; exit;
					$sub_result4 = mysql_query($sub_query4,$connection) or die(mysql_error());
					while($sub_row4=mysql_fetch_array($sub_result4)){
						fbegin();
						$vSerId = get_nextsequence('Serial_Id','',$connection);	
						fcommit();
							
						$sub_query5 = " INSERT INTO temp_purchasesserialno (Serial_ID, Journal_Type, GrnDt_ID, PurchaseDt_ID, Item_Code, SerialNo_Code, SerialNo_Used, RelatedSerial_Id, SerialNo_Quantity, SerialNo_QuantitySold, Warehouse_code, Logged_Code ) ".
									  " VALUES ( ".$vSerId.", 'PR', $vPurDtId, $vPurDtId, '".$sub_row4[1]."', '".$sub_row4[3]."', 0, '".$sub_row4[0]."', '".$sub_row4[6]."', 0, '".$sub_row4[2]."', '".$_SESSION['useraccount']."' ) ";
						//echo $sub_query5; exit;										 
						$sub_result5 = mysql_query($sub_query5,$connection);	
					}
					
					fcommit();
				}else{
					$ErrorExists = 1;
					$message  = mysql_error(); 
					frollback();
				}
			} // End if($vPurDtQty > 0)
		}  //End Loop of GrnPurchasesDt Query
		
		
	
	} 
}


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

	if (empty($txtPurCategory))
		$txtPurCategory = 0;
	//echo $txtPurCategory; exit;		
	if (empty($txtCostCentCode))
		$CostCentCode = 'Null';
	else
		$CostCentCode = "'".$txtCostCentCode."'";
			
	if (empty($txtProjectCode))
		$ProjectCode = 'Null';
	else
		$ProjectCode = "'".$txtProjectCode."'";	
		
	
	$SaveAllow   = 1;
	$ErrorExists = 0;
	
	$sub_query = " Select Distinct Item_CodePacked ".
				 " From temp_grnpurchasesdt ".
				 " Where Purchase_ID = '".$SPurId."' ".
				 " 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(PurchaseDt_Quantity,0)) As PurchaseDtQuantity ".
								  " From temp_grnpurchasesdt ".
								  " Where Purchase_ID = '".$SPurId."' ".
								  " And Item_CodePacked = '".$sub_row1[0]."' ".
								  " And Item_Code = '".$sub_row1[1]."' ".
								  " Group by Item_CodePacked, Item_Code ";
								  
					$sub_result2 = selectData($connection, $sub_query2);
					$ItemPackQty = $sub_result2[2] / $sub_row1[2];
					if (empty($sub_result2[2])) $ItemPackQty = -1;
					
					if ($ItemQty == 0) $ItemQty = $ItemPackQty;
					if ($ItemQty != $ItemPackQty) $SaveAllow = 0;
					
					
				}
			}		  
			
		}
	}
	
	//Check For Supplier, Project and Costcenter Codes Before Insert
	if ($txtCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Costcenter Code.';
		}
	}
	if ($txtProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$txtProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Project Code.';
		}
	}
	if ($txtSupplier != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$txtSupplier."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Supplier Code.';
		}
	}
	
	if ($ErrorExists == 0 && $Module_SerialNo == 1) {
		//Checking For Difference Btw Qty and Count SerialNo
		$sub_query = " Select Count(*) From ( ".
					 " 	Select GrnPurchasesDt.PurchaseDt_ID, GrnPurchasesDt.Item_code, ifNull(PurchaseDt_Quantity,0) as PurchaseDt_Quantity, Count(SerialNo_Code) As CountSerialNo ".
					 " 	From Temp_GrnPurchasesDt As GrnPurchasesDt Left Join Items on GrnPurchasesDt.Item_code = Items.Item_code ".
					 " 	Left Join Temp_Purchasesserialno on GrnPurchasesDt.PurchaseDt_ID = Temp_Purchasesserialno.GrnDt_ID ".
					 " 	And Temp_Purchasesserialno.Journal_Type = 'PR' ".
					 " 	And Temp_Purchasesserialno.PurchaseDt_ID Is Not Null ".
					 " 	Where GrnPurchasesDt.Purchase_ID = ".$SPurId.
					 " 	And ifNull(Items.item_withserialno,0) = 1 ".
					 " 	Group By GrnPurchasesDt.PurchaseDt_ID ".
					 " 	Having ifNull(PurchaseDt_Quantity,0) != CountSerialNo ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item Serials.';
		}		 
	}				 
					 
	if ($ErrorExists == 0) {
		//Checking For Qty Not To Be Zero
		$sub_query = " Select Count(*) From ( ".
					 " 	Select GrnPurchasesDt.PurchaseDt_ID, GrnPurchasesDt.Item_code, ifNull(PurchaseDt_Quantity,0) as PurchaseDt_Quantity ".
					 " 	From Temp_GrnPurchasesDt As GrnPurchasesDt ".
					 " 	Where GrnPurchasesDt.Purchase_ID = ".$SPurId.
					 " 	And ifNull(PurchaseDt_Quantity,0) = 0 ".
					 " ) Q1 ";
		 //echo $sub_query; exit;
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 0) {
			$ErrorExists = 1;
			$message = 'Save not allowed. Please check for Item(s) Quantity [Qty cannot be zero].';
		}		 
	}				 
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

	$sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	
	$ExceedLockPeriod = 0;
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($txtDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	//echo $sub_query;exit;
	
	
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
		//Update Serials ExpireDate and BatchNo From Detail Table
		if ($Module_ExpireDate == 1 && $Module_SerialNo == 1) {
			$sub_query5 = " Select PurchaseDt_Id, PurchaseDt_ExpireDate, PurchaseDt_BatchNo ".
						  " From Temp_GrnPurchasesDt As GrnPurchasesDt  ".
						  " Where GrnPurchasesDt.Purchase_ID = ".$SPurId;
						  
			//echo $sub_query5; 
			$sub_result5=mysql_query($sub_query5,$connection) or die(mysql_error());
			while($sub_rows5=mysql_fetch_array($sub_result5)){
				if (empty($sub_rows5[1]))		$vPurDtExpireDate = 'Null';
				else  $vPurDtExpireDate = "'".$sub_rows5[1]."'";		
		
				$query = " UPDATE temp_purchasesserialno SET ".
						 " Item_ExpireDate = $vPurDtExpireDate, Item_BatchNo = '".$sub_rows5[2]."' ".
					     " WHERE GrnDt_Id  = '".$sub_rows5[0]."' ".
						 " AND Journal_Type = 'PR' ";
				//echo $query."<br>";exit;		   
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 
			
			}
		}
	
		$sub_query = " UPDATE temp_grnpurchasesdt SET ".
					 " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', ".
					 " Purchase_Date = '".insertMySQLDate($txtDate)."', Purchase_invoiceNo = '".$txtInvoiceNo."' ";
					 
		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 Purchase_id = $SPurId ";
		
		//echo $sub_query."<br>";exit;		   
		if (!updateData($connection, $sub_query, true))		 
			$message  = mysql_error(); 
		
			
		$query = " UPDATE temp_grnpurchases SET ".
		         " Supplier_code = '".ereg_replace("'", "\'", trim($txtSupplier))."', ".
				 " Purchase_Date = '".insertMySQLDate($txtDate)."', Purchase_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', ".
				 " Project_Code = $ProjectCode, Costcent_code = $CostCentCode, Purchase_InvoiceNo = '".$txtInvoiceNo."', ".
				 " Journaldt_valuedate = '".insertMySQLDate($txtMaturityDate)."', Purchase_Import = '".$txtPurCategory."' ".
				 " WHERE Purchase_id = $SPurId ";
		
				
		$result=mysql_query($query,$connection);
		//echo $query."<br>"; exit;
				
		if ($result){
						
					
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			
			$vOldProjCode  	= '';
			$vOldCostCentCode = '';
			// In Edit Case, Get The Old Values For Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcent_code  FROM GrnPurchases WHERE Purchase_id = $SPurId ";
			$result  = selectData($connection, $query);
			$vOldProjCode     = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From Temp_GrnPurchases where Purchase_ID = '".$SPurId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
				fbegin();
				$query = "SELECT CopyData_TempGrnPurchases('PR', ".$SPurId.", '".$_SESSION['useraccount']."') FROM Dual ";
				$result = selectData($connection, $query);
				$result = $result[0];
				
				if ($result != 0){
					fcommit();
						
					$query   = " SELECT Purchase_Reference, Costcent_code, Project_Code FROM GrnPurchases WHERE Purchase_id = $SPurId ";
					$result  = selectData($connection, $query);
					$vPurRef = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
						
					if ($vPurRef == '' || ($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();
						$vPurRef = get_nextsequence('GrnReturn_Reference',$vProjCostCent,$connection);	
						fcommit();
							
						$query = " UPDATE GrnPurchases SET ".
								 " Purchase_Reference = $vPurRef ".
								 " WHERE Purchase_id = $SPurId ";
							
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						
					}
						
				
				} else{
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempGrnPurchases Function'; 
					frollback();
				}
			}
			
		} else{
			$message  = mysql_error(); 
			frollback();
		}
	}// End if($SaveAllowed == 1)
	else {
		if ($SaveAllow == 0) 
			$message = "Save not allowed. Not allowed to load part of Pack/PromoPack Items.";
		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';		
			
		frollback();
	}	
}


$message = ereg_replace(' ','%20',$message);
$PPurRemark    = ereg_replace(' ','%20',$PPurRemark);
$PPurInvoiceNo = ereg_replace(' ','%20',$PPurInvoiceNo);

$lstWarehouse  = ereg_replace('#','%23',$lstWarehouse);
$PPurRemark    = ereg_replace('#','%23',$PPurRemark);
$PPurInvoiceNo = ereg_replace('#','%23',$PPurInvoiceNo);

$lstWarehouse  = ereg_replace('&','%26',$lstWarehouse);
$PPurRemark    = ereg_replace('&','%26',$PPurRemark);
$PPurInvoiceNo = ereg_replace('&','%26',$PPurInvoiceNo);




//if($mode == "post")
	//header ("Location: ./Form_RetGoodRecNote.php?actionmode=post&mainaction=&PrPurId=".$SPurId."&PrPurRef=".$vPurRef."&message=".$message);
if($mode == "post") {
	if ($SaveAllow == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0)
		header ("Location: ./Form_RetGoodRecNote.php?actionmode=".$mode."&mainaction=".$mainmode."&PrPurId=".$SPurId."&PrPurRef=".$vPurRef."&message=".$message);
	else
		header ("Location: ./Form_RetGoodRecNote.php?actionmode=submitrecord&mainaction=".$mainmode."&txtPurId=".$SPurId."&message=".$message);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_RetGoodRecNoteSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_RetGoodRecNoteSearchPending.php");
else if ($mode == "cancel" )		
	header ("Location: ./Form_RetGoodRecNote.php?message=".$message);
//else if ($mode == "deletedt" )		
	//header ("Location: ./Form_RetGoodRecNote.php?actionmode=".$mode."&mainaction=".$mainmode."&txtPurId=".$SPurId."&message=".$message);	
else if ($mode == "editdt")		
	header ("Location: ./Form_RetGoodRecNoteDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPurId=".$SPurId."&PPurDate=".$PPurDate."&PPurDtId=".$SPurDtId."&message=".$message);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_RetGoodRecNoteSearch.php?PMode=$AllowEdit&message=".$message);	
else if ($mode == "" && $mainmode == "loadgrn" )  
	header ("Location: ./Form_RetGoodRecNote_LoadGrn.php?PMode=1&PPurId=".$SPurId."&message=".$message);				
else if($mode == "submitrecord") {
    header ("Location: ./Form_GoodRecNoteDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PPurType=".$SPurType."&PPurId=".$PPurId.	
			"&PPurDate=".$PPurDate."&PPurMaturityDate=".$PPurMaturityDate."&PPurSupplier=".$PPurSupplier."&PPurCurr=".$PPurCurr.
			"&PPurProjectCode=".$PPurProjectCode."&PPurCostCentCode=".$PPurCostCentCode."&PPurInvoiceNo=".$PPurInvoiceNo.
			"&lstWarehouse=".$lstWarehouse."&PPurRemark=".$PPurRemark."&message=".$message );
}
$return_arr = array();

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

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

HERE;
*/

?>