<?php

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

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

$connection = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
//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);
}



$querycostcent=" select costcent_applyvat ".
               " from costcent left join ".$_SESSION['dbLabel'].".loginstk on costcent.costcent_code like concat(loginstk.costcent_code,'%') ".
 			   " where user_account='".$_SESSION['useraccount']."' ".
 			   "";
			   
$costcentres = mysql_query($querycostcent,$connection) or die(mysql_error());
$rows=mysql_fetch_array($costcentres);
$costcent_applyvat = $rows[0];
if($costcent_applyvat=='')	$costcent_applyvat = 1;

//User Access
$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp from ".$_SESSION['dbLabel'].".login where user_account='".$_SESSION['useraccount']."' and Upper(Login_Schema) = Upper('".$_SESSION['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}

//Read From Module Table
$querymodule=" Select 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_PostToJournal,0) As Module_PostToJournal, ifNull(Module_UniqueManualNo,0) As Module_UniqueManualNo ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

					
print <<<HERE
<head>

<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<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='insertpurchasesjv' method=''>
<input type='text' name='mode' value='$mode'>
<input type='text' name='mainmode' value='$mainmode'>
<input type='text' name='SId' value='$SId'>
<input type='text' name='SDtId' value='$SDtId'>
<input type='text' name='SVatChkbx' value='$SVatChkbx'>

HERE;

$message='';

 
if ($mode == "submitrecord" ){
	
	
	$txtLedgerNo 		= $_GET["value1"];
	$txtDescription1 	= $_GET["value2"];
	$txtDescription2 	= $_GET["value3"];
	$txtDtCurr 			= $_GET["value4"];
	$txtDtQty 			= $_GET["value5"];
	$txtDtPrice 		= $_GET["value6"];
	$txtDtDiscPer 		= $_GET["value7"];
	$txtDtTotal 		= $_GET["value8"];
	$txtDtVat 			= $_GET["value9"];
	$txtDtManualNo 		= $_GET["value10"];
	$txtProjectCodeDt 	= $_GET["value11"];
	$txtCostCentCodeDt 	= $_GET["value12"];
	$txtAssetPer 		= $_GET["value13"];
	
	
	$ErrorExists = 0;
	
	if (!isset($PCurr))   $PCurr = $base1;
	  
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$PCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$PCurr."' )";
	$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 ($PCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$PCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PProjectCode != '') {
		$sub_query = " Select Count(Project_Code) From Project ".
					 " Where Project_Code = '".$PProjectCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSupplierCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$PSupplierCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($txtLedgerNo != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtLedgerNo."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PWHTAcc != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtWHTAcc."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}	
	
	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 == 1)
		$message = 'Insert not allowed. Please check for Supplier/Project/Costcenter/Ledger Code.';
	

	
	//Insert Master Table
	if ($SId == "" && $ErrorExists == 0){
		
		if (empty($PDiscountAmt))	$PDiscountAmt = 0;
		if (empty($PDiscountPer))	$PDiscountPer = 0;
		if (empty($PVatChkbx))	    $PVatChkbx = 0;
		
		if (empty($PWHTChk))		$PWHTChk = 0;
		if (empty($PWHTPer))		$PWHTPer = 0;
		if (empty($PWHTAmt))	    $PWHTAmt = 0;
		
		$txtInvoiceDate = $_GET["PInvoiceDate"];
		
		if ($txtInvoiceDate == '') $txtInvoiceDate = "NULL";
		else $txtInvoiceDate = "'".insertMySQLDate($txtInvoiceDate)."'";
		
		$CostCentCode = "".$CostCentCode;
		$PProjectCode = "".$PProjectCode;
		
		if ($PCostCentCode == '')		$CostCentCode = 'Null';
		else		$CostCentCode = "'".$PCostCentCode."'";
				
		if ($PProjectCode == '')	$ProjectCode = 'Null';
		else		$ProjectCode = "'".$PProjectCode."'";
		
		
		$Acc_Query = " SELECT VATAccountNonStock, DiscountAccount FROM purchasesetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		//$vVatAccount = $Acc_Result[0];
		if (empty($PVatPrefix)) $vVatAccount = $Acc_Result[0];
		else $vVatAccount = $PVatPrefix;
		
		$sub_queryVat = " SELECT GetVATAccount('".$PSupplierCode."','".$vVatAccount."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vVatAccount = $sub_resultVat[0];
				
		fbegin();	
		$vPurchasesJVId = get_nextsequence('PurchasesJV_Id','',$connection);	
		fcommit();
			 
		fbegin();
		$query = " INSERT INTO Temp_PurchasesJV (PurchaseJV_ID, PurchaseJV_Reference, PurchaseJV_Date, JournalDt_ValueDate, Supplier_Code, PurchaseJV_InvoiceNo, Purchase_Remark, ".
				 " Currency_Code, Project_Code, Costcenter_Code, PurchaseJV_Posted, PurchaseJV_Edit, Purchase_Mode, PurchaseJV_BelongsToGroup, Journal_Type, Journal_Id, ".
				 " PurchaseJV_Taxable, PurchaseJV_TaxableBase1, PurchaseJV_TaxableBase2, PurchaseJV_NoneTaxable, PurchJV_NoneTaxableBase1, PurchJV_NoneTaxableBase2, ".
				 " PurchaseJV_Total, PurchaseJV_TotalBase1, PurchaseJV_TotalBase2, PurchaseJV_VAT, PurchaseJV_VatBase1, PurchaseJV_VatBase2, PurchaseJV_VatCheck, PurchaseJV_DiscountPer, ".
				 " PurchaseJV_DiscAmount, PurchaseJV_DiscAmount1, PurchaseJV_DiscAmount2, PurchaseJV_Amount, PurchaseJV_AmountBase1, PurchaseJV_AmountBase2, ".
				 " PurchaseJV_VatAccount, PurchaseJV_DiscountAccount, PurchaseJV_Type, PurchaseJV_WHTChk, PurchaseJV_WHTAccount, PurchaseJV_WHTPer, PurchaseJV_WHTAmt, ".
				 " PurchaseJV_WHTAmt1, PurchaseJV_WHTAmt2, PurchaseJv_ManualNo, PurchaseJv_VatPrefix, User_Account, Logged_Code, InvoiceDate ) ".
				 " VALUES ( ".$vPurchasesJVId.", Null, '".insertMySQLDate($PDate)."', '".insertMySQLDate($PMaturityDate)."', '".ereg_replace("'", "\'", trim($PSupplierCode))."', ".
				 "          '".ereg_replace("'", "\'", trim($PInvoiceNo))."', '".ereg_replace("'", "\'", trim($PRemark))."', '".$PCurr."', $ProjectCode, $CostCentCode, ".
				 "          0, 0, 0, $FI_BelongsToGrp, 'JP', Null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PVatChkbx, 0, 0, 0, 0, 0, 0, 0, '".$vVatAccount."', '".$Acc_Result[1]."', ".
				 "          Null, $PWHTChk, '".$PWHTAcc."', $PWHTPer, 0, 0, 0, '".ereg_replace("'", "\'", trim($PManualNo))."', '".trim($PVatPrefix)."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."',".
				 "  ".$txtInvoiceDate." )";
					 
			 
		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	
		
		if ($result){
			$SId = $vPurchasesJVId;
			fcommit();
		}else{
			$SId = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}
	
	}
	
	//Insert Detail Tables
	if ($SId != "" && $SDtId == "" && $ErrorExists == 0){
	
		if (empty($PDiscountAmt))	$PDiscountAmt = 0;
		if (empty($PDiscountPer))	$PDiscountPer = 0;
		if (empty($PVatChkbx))	    $PVatChkbx = 0;
			
		if (empty($txtDtVat))	    $txtDtVat = 0;	
		if (empty($txtDtPrice))		$txtDtPrice = 0;
		if (empty($txtDtDiscPer))   $txtDtDiscPer = 0;
		if (empty($txtDtQty))  	    $txtSaDtQty = 0;      	
		if (empty($txtDtTotal))     $txtDtTotal = 0;  
	
		$PCostCentCode = "".$PCostCentCode;
		if ($PCostCentCode == '')	$CostCentCode = 'Null';
		else						$CostCentCode = "'".$PCostCentCode."'";
			
		$PProjectCode = "".$PProjectCode; 	
		if ($PProjectCode == '')	$ProjectCode = 'Null';
		else						$ProjectCode = "'".$PProjectCode."'";   
		
		$txtProjectCodeDt = "".$txtProjectCodeDt;
		if ($Module_ProjectDt == 1){
			if ($txtProjectCodeDt == '')	$ProjectCodeDt = $ProjectCode;
			//if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null'; changed by elie
			else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
		} else {
			$ProjectCodeDt = $ProjectCode;
		}
		
		$txtCostCentCodeDt = "".$txtCostCentCodeDt;
		if ($Module_CostCenterDt == 1) {
			if ($txtCostCentCodeDt == '')	$CostCentCodeDt = $CostCentCode;
			else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
		} else {
			$CostCentCodeDt = $CostCentCode;
		}
		
		if (empty($txtDtManualNo)) $vDtManualNo = 'Null';
		else	$vDtManualNo = "'".$txtDtManualNo."'";
		
		$vDtQty           = 0;
		$vDtDiscPer       = 0;
		$vDtTotal         = 0;
		$vDtPrice         = 0;
		$vDtPriceBase1    = 0;
		$vDtPriceBase2    = 0;
		$vDtDiscAmt       = 0;
		$vDtDiscAmtBase1  = 0;
		$vDtDiscAmtBase2  = 0;
			
		$vDtQty        = $txtDtQty;
		$vDtDiscPer    = $txtDtDiscPer;
		$vDtVat        = $txtDtVat;
		$vDtTotal      = $txtDtTotal;
		
		$vDtPrice      = $txtDtPrice;
		$vDtPriceBase1 = ($vDtPrice*$rate_dt)/$rate_dt1;
		$vDtPriceBase2 = ($vDtPrice*$rate_dt)/$rate_dt2;

		$vDtDiscAmt       = ((($vDtPrice*$vDtQty) - ($vDtPrice*$vDtQty*$vDtDiscPer/100))*$PDiscountPer)/100;
		$vDtDiscAmtBase1  = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
		$vDtDiscAmtBase2  = ($vDtDiscAmt*$rate_dt)/$rate_dt2;				
				
		
		//Check For Manual No To Be Unique
		if ($Module_UniqueManualNo == 1 && $txtDtManualNo != "") {
			$sub_query = " Select Count(*) From ( Select PurchaseJVDt_ID From PurchasesJVDt ".
						 "                        Where PurchasesJVDt.Journal_Type = 'JP' and upper(PurchasesJVDt.PurchaseJvDt_ManualNo) = '".$txtDtManualNo."' and PurchasesJVDt.PurchaseJVDt_ID != $SDtId ".
						 "                 Union  Select PurchaseJVDt_ID From Temp_PurchasesJVDt as PurchasesJVDt ".
						 "                        Where PurchasesJVDt.Journal_Type = 'JP' and upper(PurchasesJVDt.PurchaseJvDt_ManualNo) = '".$txtDtManualNo."' and PurchasesJVDt.PurchaseJVDt_ID != $SDtId) Q1 ";
			$sub_result = selectData($connection, $sub_query);
			if ($sub_result[0] > 1 ) {
				$ErrorExists = 1;
				$message = 'Manual No should be unique.';
			}	
		}
					
			
		if ($ErrorExists == 0){		
			fbegin();
			$vPurchasesJVDtId = get_nextsequence('PurchasesJVDt_Id','',$connection);	
			fcommit();

			/*if($CostCentCodeDt=='')	
				$CostCentCodeDt = $CostCentCode;
				*/
			fbegin();
			$query = " INSERT INTO Temp_PurchasesJVDt (PurchaseJVDt_Id, PurchaseJV_Id, PurchaseJV_Date, Currency_Code, Supplier_Code, Ledger_Number, PurchaseJVDt_Description, PurchaseJVDt_Description2, ". 
					 " Project_Code, Costcenter_Code, PurchaseJVDt_Quantity, PurchaseJVDt_Price, PurchaseJVDt_PriceBase1, PurchaseJVDt_PriceBase2, PurchaseJVDt_DiscPer, PurchaseJVDt_DiscAmount, ".
					 " PurchaseJVDt_DiscAmount1, PurchaseJVDt_DiscAmount2, PurchaseJVDt_Discount, PurchaseJVDt_Discount1, PurchaseJVDt_Discount2, PurchaseJVDtCalcTotal, PurchaseJVDt_VAT, Journal_Type, ".
					 " PurchaseJvDt_ManualNo, purchasejvdt_assetPer, Logged_Code )  ".
					 " VALUES ( ".$vPurchasesJVDtId.", ".$SId.", '".insertMySQLDate($PDate)."', '".$PCurr."', '".ereg_replace("'", "\'", trim($PSupplierCode))."', ".
					 "          '".ereg_replace("'", "\'", trim($txtLedgerNo))."', '".ereg_replace("'", "\'", trim($txtDescription1))."', '".ereg_replace("'", "\'", trim($txtDescription2))."', ".
					 "          $ProjectCodeDt, $CostCentCodeDt, $vDtQty, $vDtPrice, $vDtPriceBase1, $vDtPriceBase2, $vDtDiscPer, $vDtDiscAmt, $vDtDiscAmtBase1, $vDtDiscAmtBase2, ".
					 "          $vDtDiscAmt, $vDtDiscAmtBase1, $vDtDiscAmtBase2, $vDtTotal, $vDtVat, 'JP', $vDtManualNo, ".GetSQLValueString($txtAssetPer,'double').",'".$_SESSION['useraccount']."'	) ";
				 
			//echo $query."<br>";exit;				
			$result=mysql_query($query,$connection);
			
			if ($result){
				fcommit();
			} else{
				$txtDtId = "";
				$ErrorExists = 1;
				$message  = mysql_error(); 
				frollback();
			}	
			
			
			if ($ErrorExists == 0) {
				//Calculating Master Amounts
				$CalculateResult = Calculate_MasterAmounts($SId, $PDate, $PVatChkbx, $PDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'I', $connection);
				$message  = $message . $CalculateResult;
			}
		}
	} // End Case Insert In Detail Tables
	echo "[BRK]";
	echo $SId;
	echo "[BRK]";
	echo $message;
	echo "[BRK]";
exit;

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

	$AllowDelete = 0;
	$ErrorExists = 0;
	$message  = '';
	
	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 No Constraints Exists On Delete
	if ($AllowDelete == 0) {
		
		fbegin();
		
		// Delete From Temp_PurchasesJVDt For Selected Record
		$query = " DELETE FROM Temp_PurchasesJVDt ".
				 " WHERE PurchaseJVDt_Id = ".$SDtId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
					 
		if (!updateData($connection, $query, true)) {
			$message  = mysql_error();
			$ErrorExists = 1;
			frollback();
		}  
		else {
			fcommit();
		}
			
			
	
			
		if ( $ErrorExists == 0 ){ 
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SId, $txtDate, $SVatChkbx, $txtDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'D', $connection);
			$message  = $message . $CalculateResult;
		} // End If No Error Exists 
	
	} // End If No Constraints Found On Delete
	
	
}
else if ($actionmode=='checkaccountno'){

$vaccountno = $_GET["vaccountno"];

$vaccountname = $_GET["vaccountname"];

if ($codedesc==1)
	$query = "  select ledger_name from ledger where ledger_number = '".$vaccountno ."' and LEDGER_GRPDET=FALSE ";
	else
	$query = "  select ledger_number from ledger where ledger_name = '".$vaccountname ."' and LEDGER_GRPDET=FALSE ";

$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]";
exit;
}	
//Edit Detail Tables
else if ($mode == "editdt" && $SId != "" && $SDtId != ""){

	$txtLedgerNo 		= $_GET["value1"];
	$txtDescription1 	= $_GET["value2"];
	$txtDescription2 	= $_GET["value3"];
	$txtDtCurr 			= $_GET["value4"];
	$txtDtQty 			= $_GET["value5"];
	$txtDtPrice 		= $_GET["value6"];
	$txtDtDiscPer 		= $_GET["value7"];
	$txtDtTotal 		= $_GET["value8"];
	$txtDtVat 			= $_GET["value9"];
	$txtDtManualNo 		= $_GET["value10"];
	$txtProjectCodeDt 	= $_GET["value11"];
	$txtCostCentCodeDt 	= $_GET["value12"];
	$txtAssetPer 		= $_GET["value13"];
	
	if (empty($PDiscountAmt))	$PDiscountAmt = 0;
	if (empty($PDiscountPer))	$PDiscountPer = 0;
	if (empty($PVatChkbx))	    $PVatChkbx = 0;
			
	if (empty($txtDtVat))	    $txtDtVat = 0;	
	if (empty($txtDtPrice))		$txtDtPrice = 0;
	if (empty($txtDtDiscPer))   $txtDtDiscPer = 0;
	if (empty($txtDtQty))  	    $txtSaDtQty = 0;      	
	if (empty($txtDtTotal))     $txtDtTotal = 0;  
	
	if (empty($txtDtManualNo)) $vDtManualNo = 'Null';
	else	$vDtManualNo = "'".$txtDtManualNo."'";
			
	
			
	$vDtQty           = 0;
	$vDtDiscPer       = 0;
	$vDtTotal         = 0;
	$vDtPrice         = 0;
	$vDtPriceBase1    = 0;
	$vDtPriceBase2    = 0;
	$vDtDiscAmt       = 0;
	$vDtDiscAmtBase1  = 0;
	$vDtDiscAmtBase2  = 0;
	$ErrorExists      = 0;
	
	$sub_query = " Select Currency_code, ifNull(PurchaseJV_DiscountPer,0), date_format(PurchaseJV_Date, '%d/%m/%Y'), ifNull(PurchaseJV_VatCheck,0) ".
				 " From Temp_PurchasesJV As PurchasesJV ".
				 " Where PurchaseJV_ID = ".$SId;
	$sub_result = selectData($connection, $sub_query);
	$vCurr         = $sub_result[0];
	$vDiscountPer  = $sub_result[1];
	$vDate         = $sub_result[2];
	$vVatChkbx     = $sub_result[3];
			
			
	$query = "SELECT Curdt_Rate FROM curdt WHERE Currency_Code = '".$vCurr."' AND Curdt_date = (SELECT MAX(Curdt_date) FROM curdt WHERE Currency_Code = '".$vCurr."' )";
	$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];
	
			
	$vDtQty        = $txtDtQty;
	$vDtDiscPer    = $txtDtDiscPer;
	$vDtVat        = $txtDtVat;
	$vDtTotal      = $txtDtTotal;
		
	$vDtPrice      = $txtDtPrice;
	$vDtPriceBase1 = ($vDtPrice*$rate_dt)/$rate_dt1;
	$vDtPriceBase2 = ($vDtPrice*$rate_dt)/$rate_dt2;

	$vDtDiscAmt       = ((($vDtPrice*$vDtQty) - ($vDtPrice*$vDtQty*$vDtDiscPer/100))*$vDiscountPer)/100;
	$vDtDiscAmtBase1  = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
	$vDtDiscAmtBase2  = ($vDtDiscAmt*$rate_dt)/$rate_dt2;
	
	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.';
		}
	}
	
	//Check For Manual No To Be Unique
	if ($Module_UniqueManualNo == 1 && $txtDtManualNo != "") {
		$sub_query = " Select Count(*) From ( Select PurchaseJVDt_ID From PurchasesJVDt ".
					 "                        Where PurchasesJVDt.Journal_Type = 'JP' and upper(PurchasesJVDt.PurchaseJvDt_ManualNo) = '".$txtDtManualNo."' and PurchasesJVDt.PurchaseJVDt_ID != $SDtId ".
					 "                 Union  Select PurchaseJVDt_ID From Temp_PurchasesJVDt as PurchasesJVDt ".
					 "                        Where PurchasesJVDt.Journal_Type = 'JP' and upper(PurchasesJVDt.PurchaseJvDt_ManualNo) = '".$txtDtManualNo."' and PurchasesJVDt.PurchaseJVDt_ID != $SDtId) Q1 ";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] > 1 ) {
			$ErrorExists = 1;
			$message = 'Manual No should be unique.';
		}	
	}
		
	if ($Module_ProjectDt == 1){
		if (empty($txtProjectCodeDt))	$ProjectCodeDt = 'Null';
		else	$ProjectCodeDt = "'".$txtProjectCodeDt."'";
	} 
	if ($Module_CostCenterDt == 1) {
		if (empty($txtCostCentCodeDt))	$CostCentCodeDt = 'Null';
		else	$CostCentCodeDt = "'".$txtCostCentCodeDt."'";
	}
	
	
	if ($ErrorExists == 0){					 
		fbegin();
		$query = " UPDATE Temp_PurchasesJVDt SET Ledger_Number = '".ereg_replace("'", "\'", trim($txtLedgerNo))."', ".
				 " PurchaseJVDt_Description = '".ereg_replace("'", "\'", trim($txtDescription1))."', PurchaseJVDt_Description2 = '".ereg_replace("'", "\'", trim($txtDescription2))."',  ". 
				 " PurchaseJVDt_Quantity = $vDtQty, PurchaseJVDt_Price = $vDtPrice, PurchaseJVDt_PriceBase1 = $vDtPriceBase1, PurchaseJVDt_PriceBase2 = $vDtPriceBase2,  ".
				 " PurchaseJVDt_DiscPer = $vDtDiscPer, PurchaseJVDt_DiscAmount = $vDtDiscAmt, PurchaseJVDt_DiscAmount1 = $vDtDiscAmtBase1, PurchaseJVDt_DiscAmount2 = $vDtDiscAmtBase2,  ".
				 " PurchaseJVDt_Discount = $vDtDiscAmt, PurchaseJVDt_Discount1 = $vDtDiscAmtBase1, PurchaseJVDt_Discount2 = $vDtDiscAmtBase2,  ".
				 " PurchaseJVDtCalcTotal = $vDtTotal, PurchaseJVDt_VAT = $vDtVat, PurchaseJvDt_ManualNo = $vDtManualNo, purchasejvdt_assetPer = ".GetSQLValueString($txtAssetPer,'double')."  ";
				 
		if ($Module_ProjectDt == 1)
			$query = $query.", Project_Code = $ProjectCodeDt ";
		if ($Module_CostCenterDt == 1)	
			$query = $query.", CostCenter_Code = $CostCentCodeDt ";
				
		$query = $query." WHERE PurchaseJVDt_Id = '".$SDtId."'";

		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);
			
		if ($result){
			fcommit();
			
			//Calculating Master Amounts
			$CalculateResult = Calculate_MasterAmounts($SId, $vDate, $vVatChkbx, $vDiscountPer, 0, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'U', $connection);
			$message  = $message . $CalculateResult;

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

else if($mode == "changedate" && $mainmode == ''){
	if($txtPaymentTerms == '') $txtPaymentTerms = 0;
	$ndate = explode('/',$txtInvoiceDate);
	$txtInvoiceDate = $ndate[2]."-".$ndate[1]."-".$ndate[0];
	
	$query = "select date_format(DATE_ADD(date_format('$txtInvoiceDate','%Y-%m-%d'),INTERVAL $txtPaymentTerms DAY), '%d/%m/%Y')  ; ";
	$res = mysql_query($query,$connection);
	$row = mysql_fetch_row($res);
	echo $row[0];
	exit;
}
//Delete Record Mode From Main Tables
else if ($mode == "" && $mainmode == "delete" && $SId != ''){

	$AllowDelete = 0;
	$message  = '';
	
	
	//Check If PurchasesJV Is Posted
	$query = "SELECT ifNull(PurchaseJV_Posted,0) As PurchaseJVPosted FROM PurchasesJV WHERE PurchaseJV_ID = ".$SId;
	$result = selectData($connection, $query);
	$PurchaseJVPosted = $result[0];
	
	if ($PurchaseJVPosted == 1 ){
		$message  = 'Delete not allowed, Transaction posted.';
		$AllowDelete = 1;
	}
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);
	
	 $sub_query= " Select ifNull(AllowLockedPeriod,0) As AllowLockedPeriod, LockedPeriod As LockedPeriodDate, LockedPeriodDays As LockedPeriodDays ".
				" From ".$_SESSION['dbLabel'].".ListUserDir  ".
				" Where Usercode='".$_SESSION['useraccount']."' ".
				" And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
				" And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
				  
	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(PurchaseJV_Date,'%d/%m/%Y') FROM PurchasesJV WHERE PurchaseJV_ID = ".$SId;
		$result = selectData($connection, $query);
		$txtDate  = $result[0];
 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && date('Y-m-d',strtotime(insertMySQLDate($txtDate))) <= date('Y-m-d',strtotime($LockedPeriodDate))) $AllowDelete = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $AllowDelete = 1;
		if($AllowDelete==1) $message  = 'Delete not allowed, Exceed Lock Period.';
	}
 
	
	
	//If No Constraints Exists On Delete
	if ($AllowDelete == 0) {
		
		$sub_query = " Select Journal_Id From PurchasesJV Where PurchaseJV_ID = ".$SId;
		$sub_result = selectData($connection, $sub_query);
		$vJournalID = $sub_result[0];
		if(empty($vJournalID)) $vJournalID = -1;
		
		$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
					if($config['log_file'] == 1){
						$transType = "D";
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'purchasesjv', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
	    // Delete From PurchasesJVDt For Selected Record
		$query = " DELETE FROM PurchasesJVDt ".
				 " WHERE PurchaseJV_ID = ".$SId;
					 
		if (updateData($connection, $query, true)) {
			// Delete From PurchasesJV For Selected Record
			$query = " DELETE FROM PurchasesJV ".
					 " WHERE PurchaseJV_ID = ".$SId;
				
			if (!updateData($connection, $query, true))		 
				$message  = mysql_error(); 
				
			if ($vJournalID != -1) {
				
				$query = " DELETE FROM Journal ".
						 " WHERE Journal_Id = ".$vJournalID;
				
				if (!updateData($connection, $query, true))		 
					$message  = mysql_error(); 	
			
			}	
		}
		else
			$message  = mysql_error(); 	
		
	}
	
	
}

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

	// Delete From Temp_PurchasesJVDt For Selected Record
	$query = " DELETE FROM Temp_PurchasesJVDt ".
			 " WHERE PurchaseJV_ID = ".$SId;
			 
	if (updateData($connection, $query, true)) {
		// Delete From Temp_PurchasesJV For Selected Record
		$query = " DELETE FROM Temp_PurchasesJV ".
				 " WHERE PurchaseJV_ID = ".$SId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";
			
		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	
	

}
else if($mainmode == "loadporderjv" && $SelectedRec != ''){
	$ErrorExists = 0;
	$message  = '';
	
		fbegin();	
		$vPurchasesJVId = get_nextsequence('PurchasesJV_Id','',$connection);	
		fcommit();
		
		fbegin();
		//Copy Data From Main Tables To Temp Tables 
		$query = " INSERT INTO temp_purchasesjv (PurchaseJV_Id, PurchaseJV_Reference, PurchaseJV_Date, Supplier_Code, Currency_Code, Project_Code, Costcenter_Code, Journal_Id, ".
				 " JournalDt_ValueDate, journal_type, purchasejv_edit, purchasejv_posted, PurchaseJV_Total, PurchaseJV_TotalBase1, PurchaseJV_TotalBase2, purchasejv_discamount, ".
				 " PurchaseJV_DiscAmount1, PurchaseJV_DiscAmount2, Purchase_Remark, purchase_mode, User_Account, PurchaseJV_VAT, PurchaseJV_VatBase1, PurchaseJV_VatBase2, purchasejv_percharge, ".
				 " purchasejv_chargeamount, PurchaseJV_ChargeAmount1, PurchaseJV_ChargeAmount2, PurchaseJV_ChargeDebit, PurchaseJv_ChargeCredit, PurchaseJV_CreditAccount, PurchaseJV_CheckAccount, ".
				 " PurchaseJV_CashAccount, PurchaseJV_Amount, PurchaseJV_AmountBase1, PurchaseJV_AmountBase2, PurchaseJV_CheckNo, PurchaseJV_CheckDate, PurchaseJV_Bank, PurchaseJV_BankBranch, PurchaseJV_CreditCur, ".
				 " PurchaseJV_CashCur, PurchaseJV_CheckCur, PurchaseJV_RetentionPer, PurchaseJV_RetentionAmt1, PurchaseJV_RetentionAmt2, PurchaseJV_RetentionAmt, PurchaseJV_VatAccount, PurchaseJV_BelongsToGroup, SendReceive_Reference, ".
				 " Generatedinvoice_Ref, PurchaseJV_InvoiceNo, purchasejv_taxable, purchasejv_nonetaxable, PurchJV_NoneTaxableBase1, PurchJV_NoneTaxableBase2, PurchaseJV_TaxableBase1, PurchaseJV_TaxableBase2, purchasejv_vatcheck, ".
				 " Synchronized, PurchaseJV_type, PurchaseJV_OriginType, LPO_Number, PurchaseJV_manualVat, PurchaseJV_VATPER, PurchaseJV_DiscountPer, PurchaseJV_DiscountAccount, Purchasejv_Reservation, ".
				 " Purchasejv_CheckIn, Purchasejv_CheckOut, Purchasejv_RoomType, BRANCH_CODE, PurchaseJV_WHTPer, PurchaseJV_WHTAmt, PurchaseJV_WHTAmt1, PurchaseJV_WHTAmt2, PurchaseJV_WHTChk, PurchaseJV_WHTAccount, ".
				 " PurchaseJv_ManualNo, PurchaseJv_VatPrefix, Logged_Code) ".
				 " SELECT $vPurchasesJVId, Null, now(), Supplier_Code, porderjv.Currency_Code, porderjv.Project_Code, porderjv.Costcenter_Code, Journal_Id, ".
				 " JournalDt_ValueDate, 'JP', PorderJV_edit, PorderJV_posted, PorderJV_Total, PorderJV_TotalBase1, PorderJV_TotalBase2, PorderJV_discamount, ".
				 " PorderJV_DiscAmount1, PorderJV_DiscAmount2, Purchase_Remark, purchase_mode, '".$_SESSION['useraccount']."', PorderJV_VAT, PorderJV_VatBase1, PorderJV_VatBase2, PorderJV_percharge, ".
				 " PorderJV_chargeamount, PorderJV_ChargeAmount1, PorderJV_ChargeAmount2, PorderJV_ChargeDebit, PorderJV_ChargeCredit, PorderJV_CreditAccount, PorderJV_CheckAccount, ".
				 " PorderJV_CashAccount, PorderJV_Amount, PorderJV_AmountBase1, PorderJV_AmountBase2, PorderJV_CheckNo, PorderJV_CheckDate, PorderJV_Bank, PorderJV_BankBranch, PorderJV_CreditCur, ".
				 " PorderJV_CashCur, PorderJV_CheckCur, PorderJV_RetentionPer, PorderJV_RetentionAmt1, PorderJV_RetentionAmt2, PorderJV_RetentionAmt, PorderJV_VatAccount, PorderJV_BelongsToGroup, porderjv.SendReceive_Reference, ".
				 " Generatedinvoice_Ref, PorderJV_InvoiceNo, PorderJV_taxable, PorderJV_nonetaxable, PorderJV_NoneTaxableBase1, PorderJV_NoneTaxableBase2, PorderJV_TaxableBase1, PorderJV_TaxableBase2, PorderJV_vatcheck, ".
				 " porderjv.Synchronized, PorderJV_type, PorderJV_OriginType, LPO_Number, PorderJV_manualVat, PorderJV_VATPER, PorderJV_DiscountPer, PorderJV_DiscountAccount, PorderJV_Reservation, ".
				 " PorderJV_CheckIn, PorderJV_CheckOut, PorderJV_RoomType, BRANCH_CODE, PorderJV_WHTPer, PorderJV_WHTAmt, PorderJV_WHTAmt1, PorderJV_WHTAmt2, PorderJV_WHTChk, PorderJV_WHTAccount, ".
				 " PorderJV_ManualNo, PorderJV_VatPrefix, '".$_SESSION['useraccount']."' ".
				 " FROM porderjv ".
				 " Inner Join Suppliers on porderjv.Supplier_code = Suppliers.Ledger_Number ".
				 " WHERE porderjv_id = ".$SelectedRec;
		//echo $query;exit;
		if (!updateData($connection, $query, true)) {
			$ErrorExists = 1;
			$message  = mysql_error($connection); 	
			frollback();
		} else {
			fcommit();
			$SId = $vPurchasesJVId;
		}
			
	if ($ErrorExists == 0) {
		$querys = " select porderjvdt_id, Supplier_Code, Currency_Code, Ledger_Number, PorderJVDt_Description, Project_Code, ".
				 " Costcenter_Code, PorderJVdt_quantity, PorderJVdt_price, PorderJVDt_PriceBase1, PorderJVDt_PriceBase2, PorderJVdt_discper, PorderJVDt_DiscAmount, ".
				 " PorderJVDt_DiscAmount1, PorderJVDt_DiscAmount2, Journal_Id, Warehouse_Code, PorderJVDt_ExpireDate, PorderJVdt_posted, PorderJVdt_discount, ".
				 " PorderJVdt_discount1, PorderJVdt_discount2, PorderJVdt_charge, PorderJVdt_charge1, PorderJVdt_charge2, PrefixJV_ID, PorderJVDt_VAT, Synchronized, ".
				 " PorderJVDt_Description2, PorderJVDTCalcTotal, PorderJVdt_tax, PorderJVdt_taxbase1, PorderJVdt_taxbase2, PorderJVdt_description3, PorderJVdt_date, ".
				 " PorderJVDt_ManualNo ".
				 " from porderjvdt ".
				 " where PorderJV_Id = $SelectedRec"; //echo $querys."<br>";
		$results = mysql_query($querys,$connection);
		while($rows = mysql_fetch_array($results)){	
			extract($rows);
			if($Journal_Id == '') $Journal_Id = "NULL";
			if($PrefixJV_ID == '') $PrefixJV_ID = "NULL";
			if($PorderJVDt_ExpireDate == '') $PorderJVDt_ExpireDate = "NULL";
			else $PorderJVDt_ExpireDate = "'".$PorderJVDt_ExpireDate."'";
			if($PorderJVdt_date == '') $PorderJVdt_date = "NULL";
			else $PorderJVdt_date = "'".$PorderJVdt_date."'";
			
			fbegin();
				$vPurchasesJVDtId = get_nextsequence('PurchasesJVDt_Id','',$connection);	
			fcommit();
			
			fbegin();
			$query = " insert into temp_purchasesjvdt (PurchaseJVDt_Id, PurchaseJV_Id, PurchaseJV_Date,RelatedDt_Id, Supplier_Code, Currency_Code, Ledger_Number, PurchaseJVDt_Description, Project_Code, ".
					 " Costcenter_Code, purchasejvdt_quantity, purchasejvdt_price, PurchaseJVDt_PriceBase1, PurchaseJVDt_PriceBase2, purchasejvdt_discper, PurchaseJVDt_DiscAmount, ".
					 " PurchaseJVDt_DiscAmount1, PurchaseJVDt_DiscAmount2, Journal_Id, Warehouse_Code, PurchaseJVDt_ExpireDate, purchasejvdt_posted, Journal_Type, purchasejvdt_discount, ".
					 " purchasejvdt_discount1, purchasejvdt_discount2, purchasejvdt_charge, purchasejvdt_charge1, purchasejvdt_charge2, PrefixJV_ID, PurchaseJvDt_VAT, Synchronized, ".
					 " PurchaseJVDt_Description2, PurchaseJVDTCalcTotal, purchasesjvdt_tax, purchasesjvdt_taxbase1, purchasesjvdt_taxbase2, purchasejvdt_description3, purchasesjvdt_date, ".
					 " PurchaseJvDt_ManualNo, Logged_Code)".
					 " values( $vPurchasesJVDtId, $vPurchasesJVId, now(),'$porderjvdt_id', '$Supplier_Code', '$Currency_Code', '$Ledger_Number', '$PorderJVDt_Description', '$Project_Code', ".
					 " '$Costcenter_Code', '$PorderJVdt_quantity', '$PorderJVdt_price', '$PorderJVDt_PriceBase1', '$PorderJVDt_PriceBase2', '$PorderJVdt_discper', '$PorderJVDt_DiscAmount', ".
					 " '$PorderJVDt_DiscAmount1', '$PorderJVDt_DiscAmount2', $Journal_Id, '$Warehouse_Code', ".$PorderJVDt_ExpireDate.", '$PorderJVdt_posted', 'JP', '$PorderJVdt_discount', ".
					 " '$PorderJVdt_discount1', '$PorderJVdt_discount2', '$PorderJVdt_charge', '$PorderJVdt_charge1', '$PorderJVdt_charge2', $PrefixJV_ID, '$PorderJVDt_VAT', '$Synchronized', ".
					 " '$PorderJVDt_Description2', '$PorderJVDTCalcTotal', '$PorderJVdt_tax', '$PorderJVdt_taxbase1', '$PorderJVdt_taxbase2', '$PorderJVdt_description3', ".$PorderJVdt_date.", ".
					 " '$PorderJVDt_ManualNo', '".$_SESSION['useraccount']."' )";
					 
			//echo $query;exit;
			if (!updateData($connection, $query, true)) {
				$ErrorExists = 1;
				$message  = mysql_error($connection); 	
				frollback();
			} else {
				fcommit();
			}
		}
	}
	
}

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

	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO Temp_PurchasesJV (PurchaseJV_ID, PurchaseJV_Reference, PurchaseJV_Date, JournalDt_ValueDate, Supplier_Code, PurchaseJV_InvoiceNo, Purchase_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, PurchaseJV_Posted, PurchaseJV_Edit, Purchase_Mode, PurchaseJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " PurchaseJV_Taxable, PurchaseJV_TaxableBase1, PurchaseJV_TaxableBase2, PurchaseJV_NoneTaxable, PurchJV_NoneTaxableBase1, PurchJV_NoneTaxableBase2, ".
			 " PurchaseJV_Total, PurchaseJV_TotalBase1, PurchaseJV_TotalBase2, PurchaseJV_VAT, PurchaseJV_VatBase1, PurchaseJV_VatBase2, PurchaseJV_VatCheck, PurchaseJV_DiscountPer, ".
			 " PurchaseJV_DiscAmount, PurchaseJV_DiscAmount1, PurchaseJV_DiscAmount2, PurchaseJV_Amount, PurchaseJV_AmountBase1, PurchaseJV_AmountBase2, ".
			 " PurchaseJV_VatAccount, PurchaseJV_DiscountAccount, PurchaseJV_Type, PurchaseJV_WHTChk, PurchaseJV_WHTAccount, PurchaseJV_WHTPer, PurchaseJV_WHTAmt, ".
			 " PurchaseJV_WHTAmt1, PurchaseJV_WHTAmt2, PurchaseJv_ManualNo, PurchaseJv_VatPrefix,InvoiceDate, User_Account, Logged_Code ) ".
			 " SELECT PurchaseJV_ID, PurchaseJV_Reference, PurchaseJV_Date, JournalDt_ValueDate, Supplier_Code, PurchaseJV_InvoiceNo, Purchase_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, PurchaseJV_Posted, PurchaseJV_Edit, Purchase_Mode, PurchaseJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " PurchaseJV_Taxable, PurchaseJV_TaxableBase1, PurchaseJV_TaxableBase2, PurchaseJV_NoneTaxable, PurchJV_NoneTaxableBase1, PurchJV_NoneTaxableBase2, ".
			 " PurchaseJV_Total, PurchaseJV_TotalBase1, PurchaseJV_TotalBase2, PurchaseJV_VAT, PurchaseJV_VatBase1, PurchaseJV_VatBase2, PurchaseJV_VatCheck, PurchaseJV_DiscountPer, ".
			 " PurchaseJV_DiscAmount, PurchaseJV_DiscAmount1, PurchaseJV_DiscAmount2, PurchaseJV_Amount, PurchaseJV_AmountBase1, PurchaseJV_AmountBase2, ".
			 " PurchaseJV_VatAccount, PurchaseJV_DiscountAccount, PurchaseJV_Type, PurchaseJV_WHTChk, PurchaseJV_WHTAccount, PurchaseJV_WHTPer, PurchaseJV_WHTAmt, ".
			 " PurchaseJV_WHTAmt1, PurchaseJV_WHTAmt2, PurchaseJv_ManualNo, PurchaseJv_VatPrefix,InvoiceDate, User_Account, '".$_SESSION['useraccount']."'  ".
			 " FROM PurchasesJV ".
			 " WHERE PurchaseJV_ID = ".$SId;
				 
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}  

	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO Temp_PurchasesJVDt (PurchaseJVDt_Id, PurchaseJV_Id, PurchaseJV_Date, Currency_Code, Supplier_Code, Ledger_Number, PurchaseJVDt_Description, PurchaseJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, PurchaseJVDt_Quantity, PurchaseJVDt_Price, PurchaseJVDt_PriceBase1, PurchaseJVDt_PriceBase2, PurchaseJVDt_DiscPer, PurchaseJVDt_DiscAmount, ".
				 " PurchaseJVDt_DiscAmount1, PurchaseJVDt_DiscAmount2, PurchaseJVDt_Discount, PurchaseJVDt_Discount1, PurchaseJVDt_Discount2, PurchaseJVDtCalcTotal, PurchaseJVDt_VAT, Journal_Type, ".
				 " PurchaseJvDt_ManualNo,RelatedDt_Id, purchasejvdt_assetPer, Logged_Code )  ".
				 " SELECT PurchaseJVDt_Id, PurchaseJV_Id, PurchaseJV_Date, Currency_Code, Supplier_Code, Ledger_Number, PurchaseJVDt_Description, PurchaseJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, PurchaseJVDt_Quantity, PurchaseJVDt_Price, PurchaseJVDt_PriceBase1, PurchaseJVDt_PriceBase2, PurchaseJVDt_DiscPer, PurchaseJVDt_DiscAmount, ".
				 " PurchaseJVDt_DiscAmount1, PurchaseJVDt_DiscAmount2, PurchaseJVDt_Discount, PurchaseJVDt_Discount1, PurchaseJVDt_Discount2, PurchaseJVDtCalcTotal, PurchaseJVDt_VAT, Journal_Type, ".
				 " PurchaseJvDt_ManualNo,RelatedDt_Id, purchasejvdt_assetPer, '".$_SESSION['useraccount']."'   ".
				 " FROM PurchasesJVDt ".
				 " WHERE PurchaseJV_ID = ".$SId;
		 
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 			
		
	}
}


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

	if (!isset($txtCurr))   $txtCurr = $base1;
	
	if (empty($txtDiscountAmt))	$txtDiscountAmt = 0;
	if (empty($txtDiscountPer))	$txtDiscountPer = 0;
	if (empty($txtVatChkbx))	$txtVatChkbx = 0;
	
	if (empty($txtWHTChk))		$txtWHTChk = 0;
	if (empty($txtWHTPer))		$txtWHTPer = 0;
	if (empty($txtWHTAmt))	    $txtWHTAmt = 0;
	
	$txtCostCentCode = "".$txtCostCentCode;	
	$txtProjectCode = "".$txtProjectCode;
	
	if ($txtCostCentCode == '')	$CostCentCode = 'Null';
	else		$CostCentCode = "'".$txtCostCentCode."'";
			
	if ($txtProjectCode == '')	$ProjectCode = 'Null';
	else		$ProjectCode = "'".$txtProjectCode."'";      
	
	if ($txtInvoiceDate == '') $txtInvoiceDate = "NULL";
	else $txtInvoiceDate = "'".insertMySQLDate($txtInvoiceDate)."'";

	$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];
	
	
	$ExceedCreditLimit = 0;
	$SaveAllowed = 1;
	$ErrorExists = 0;
	
	$vDtQty           = 0;
	$vDtDiscPer       = 0;
	$vDtTotal         = 0;
	$vDtPrice         = 0;
	$vDtPriceBase1    = 0;
	$vDtPriceBase2    = 0;
	$vDtDiscAmt       = 0;
	$vDtDiscAmtBase1  = 0;
	$vDtDiscAmtBase2  = 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 != '') {
		$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;
	}
	if ($txtSupplierCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Suppliers ".
					 " Where Ledger_Number = '".$txtSupplierCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($txtWHTAcc != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$txtWHTAcc."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}	
	
	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

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

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) { 
		if (!(empty($LockedPeriodDate)) && $LockedPeriodDate != '' && insertMySQLDate($txtDate) < $LockedPeriodDate) $ExceedLockPeriod = 1;
		if ($LockedPeriodDays != '' && dateDiff(insertMySQLDate(displayToday()),insertMySQLDate($txtDate)) > $LockedPeriodDays) $ExceedLockPeriod = 1;
	}
	//echo $sub_query;exit;					
					
	if ($SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {
		
		$sub_query = " Select PurchaseJVDt_Id, Currency_Code, ifNull(PurchaseJVDt_Price,0), ifNull(PurchaseJVDt_PriceBase1,0), ifNull(PurchaseJVDt_PriceBase2,0), ".
					 " ifNull(PurchaseJVDt_DiscAmount,0), ifNull(PurchaseJVDt_DiscAmount1,0), ifNull(PurchaseJVDt_DiscAmount2,0), ifNull(PurchaseJVDtCalcTotal,0) ".
					 " From Temp_PurchasesJVDt ".
					 " Where PurchaseJV_Id = ".$SId;	
		$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
		while($sub_row=mysql_fetch_array($sub_result)){
					
			$vDtPrice         = $sub_row[2];
			$vDtPriceBase1    = $sub_row[3];
			$vDtPriceBase2    = $sub_row[4];
			$vDtDiscAmt       = $sub_row[5];
			$vDtDiscAmtBase1  = $sub_row[6];
			$vDtDiscAmtBase2  = $sub_row[7];
			$vDtTotal		  = $sub_row[8];

					
			if ($sub_row[1] != $txtCurr) {
				$vDtPrice    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vDtPrice, $connection);
				$vDtDiscAmt  = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vDtDiscAmt, $connection);
				$vDtTotal    = ConvertCurrency($sub_row[1], $txtCurr, insertMySQLDate($txtDate), $vDtTotal, $connection);
						
				$vDtPriceBase1    = ($vDtPrice*$rate_dt)/$rate_dt1;
				$vDtPriceBase2    = ($vDtPrice*$rate_dt)/$rate_dt2;
				$vDtDiscAmtBase1  = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
				$vDtDiscAmtBase2  = ($vDtDiscAmt*$rate_dt)/$rate_dt2;
					
				$sub_query1 = " UPDATE Temp_PurchasesJVDt SET  ".
							  " PurchaseJVDt_Price = $vDtPrice, PurchaseJVDt_PriceBase1 = $vDtPriceBase1, PurchaseJVDt_PriceBase2 = $vDtPriceBase2, ".
							  " PurchaseJVDt_DiscAmount = $vDtDiscAmt, PurchaseJVDt_DiscAmount1 = $vDtDiscAmtBase1, PurchaseJVDt_DiscAmount2 = $vDtDiscAmtBase2, ".
							  " PurchaseJVDt_Discount = $vDtDiscAmt, PurchaseJVDt_Discount1 = $vDtDiscAmtBase1, PurchaseJVDt_Discount2 = $vDtDiscAmtBase2, ".
							  " PurchaseJVDtCalcTotal = $vDtTotal ".
							  " Where PurchaseJVDt_Id = ".$sub_row[0];
					
				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 
					
			}
		}
		
		$sub_query2 = " UPDATE Temp_PurchasesJVDt SET ".
					  " Currency_Code = '".$txtCurr."', PurchaseJV_Date = '".insertMySQLDate($txtDate)."', ".
					  " Supplier_Code = '".ereg_replace("'", "\'", trim($txtSupplierCode))."' ";
					  
		if ($Module_ProjectDt != 1)
			$sub_query2 = $sub_query2.", Project_Code = $ProjectCode ";
		if ($Module_CostCenterDt != 1)	
			$sub_query2 = $sub_query2.", CostCenter_Code = $CostCentCode ";
			
		$sub_query2 = $sub_query2." WHERE PurchaseJV_Id = $SId ";
				   
		//echo $querydt."<br>";exit;		   
		if (!updateData($connection, $sub_query2, true))		 
			$message  = mysql_error(); 
			
	
		//Distribute The Total Discount On Detail Table
		$sub_query3 = " Select Sum((ifNull(PurchaseJVDt_Quantity,0)*ifNull(PurchaseJVDt_Price,0))-((ifNull(PurchaseJVDt_Quantity,0)*ifNull(PurchaseJVDt_Price,0)*ifNull(PurchaseJVDt_DiscPer,0))/100)) As Total ".
					  " From Temp_PurchasesJVDt ".
					  " Where PurchaseJV_Id = ".$SId;
		$sub_result3 = selectData($connection, $sub_query3);
		$vTotal   = $sub_result3[0];	
		$vDisAmt  = $txtDiscountAmt;
			
		$sub_query4 = " Select PurchaseJVDt_Id,  ".
					  " ((ifNull(PurchaseJVDt_Quantity,0)*ifNull(PurchaseJVDt_Price,0))-((ifNull(PurchaseJVDt_Quantity,0)*ifNull(PurchaseJVDt_Price,0)*ifNull(PurchaseJVDt_DiscPer,0))/100)) As Total ".
					  " From Temp_PurchasesJVDt As PurchasesJVDt  ".
					  " Where PurchasesJVDt.PurchaseJV_Id = ".$SId;
					   
		//echo $query; 
		$sub_result4=mysql_query($sub_query4,$connection) or die(mysql_error());
		while($sub_rows4=mysql_fetch_array($sub_result4)){
			
			$vDtId      = $sub_rows4[0];
			$vDtTotal   = $sub_rows4[1];
				
				
			$vDtDiscAmt	     = 0;
			$vDtDiscAmt 	 = ($vDtTotal/$vTotal)*$vDisAmt;
			$vDtDiscAmtBase1 = ($vDtDiscAmt*$rate_dt)/$rate_dt1;
			$vDtDiscAmtBase2 = ($vDtDiscAmt*$rate_dt)/$rate_dt2;
				
			$queryupd =  " UPDATE Temp_PurchasesJVDt SET ".
						 " PurchaseJVDt_DiscAmount = $vDtDiscAmt, PurchaseJVDt_DiscAmount1 = $vDtDiscAmtBase1, PurchaseJVDt_DiscAmount2 = $vDtDiscAmtBase2,  ".
						 " PurchaseJVDt_Discount = $vDtDiscAmt, PurchaseJVDt_Discount1 = $vDtDiscAmtBase1, PurchaseJVDt_Discount2 = $vDtDiscAmtBase2  ".
						 " Where PurchaseJVDt_Id = ".$vDtId;
						 //" And Logged_Code = '".$PLoggedCode."' ";
			//echo $queryupd; exit;
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 
				

		}
			
		$Acc_Query = " SELECT VATAccountNonStock, DiscountAccount FROM purchasesetup ";
		$Acc_Result = selectData($connection, $Acc_Query);
		
		//$vVatAccount = $Acc_Result[0];
		if (empty($txtVatPrefix)) $vVatAccount = $Acc_Result[0];
		else $vVatAccount = $txtVatPrefix;
		
		$sub_queryVat = " SELECT GetVATAccount('".$txtSupplierCode."','".$vVatAccount."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vVatAccount = $sub_resultVat[0];
			
		//Calculating Master Amounts
		$CalculateResult = Calculate_MasterAmounts($SId, $txtDate, $SVatChkbx, $txtDiscountPer, $txtDiscountAmt, $rate_dt, $rate_dt1, $rate_dt2, $Setup_VatStartDate, $Setup_VatPercentage, 'P', $connection);
		$message  = $message . $CalculateResult;
		
		$txtWHTAmt1 = ConvertCurrency($txtCurr, $base1, insertMySQLDate($txtDate), $txtWHTAmt, $connection);
		$txtWHTAmt2 = ConvertCurrency($txtCurr, $base2, insertMySQLDate($txtDate), $txtWHTAmt, $connection);
		
		$sub_query5 = " UPDATE Temp_PurchasesJV SET ".
					  " PurchaseJV_Date = '".insertMySQLDate($txtDate)."', PurchaseJv_ManualNo = '".ereg_replace("'", "\'", trim($txtManualNo))."', ".
					  " JournalDt_ValueDate = '".insertMySQLDate($txtMaturityDate)."' , ".
					  " Purchase_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', Supplier_Code = '".ereg_replace("'", "\'", trim($txtSupplierCode))."', ".
					  " PurchaseJV_InvoiceNo = '".ereg_replace("'", "\'", trim($txtInvoiceNo))."', Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcenter_code = $CostCentCode,  ".
					  " PurchaseJV_WHTChk = $txtWHTChk, PurchaseJV_WHTAccount = '".$txtWHTAcc."', PurchaseJV_WHTPer = $txtWHTPer, PurchaseJV_WHTAmt = $txtWHTAmt, ".
					  " PurchaseJV_WHTAmt1 = $txtWHTAmt1, PurchaseJV_WHTAmt2 = $txtWHTAmt2, PurchaseJv_VatPrefix = '".trim($txtVatPrefix)."', PurchaseJV_VatAccount = '".$vVatAccount."', ".
					  " InvoiceDate = ".$txtInvoiceDate." ".
					  " WHERE PurchaseJV_ID = $SId ";
		$sub_result5=mysql_query($sub_query5,$connection);		 
		//echo $sub_query5; exit;		 
		if ($sub_result5){
			
			if ($mainmode == 'insert') $SMode = 'I';
			if ($mainmode == 'edit') $SMode = 'U';
			//echo $SMode;exit;
			
			$vOldProjCode  	  = '';
			$vOldCostCentCode = '';
			
			// In Edit Case, Get The Old Values Project and Costcenter For References Issue
			$query   = " SELECT Project_Code, Costcenter_code  FROM PurchasesJV WHERE PurchaseJV_ID = $SId ";
			$result  = selectData($connection, $query);
			$vOldProjCode  	  = $result[0];
			$vOldCostCentCode = $result[1];
			
			$query = "Select Count(*) From Temp_PurchasesJV where PurchaseJV_ID = '".$SId."'";
			//echo $query; exit;
			$result = selectData($connection, $query);
			$ExistInTemp = $result[0];	
			
			//Check If Record Exists In Temp Tables
			if ($ExistInTemp == 1) {
			
				fbegin();	
                $query_checkDelivery  = "select count(*) as PurchasesJvExist from purchasesjv where PurchaseJv_Id = '$SId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($PurchasesJvExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);				
				$query = " SELECT CopyData_TempPurchasesJV('".$SMode."', ".$SId.", '".$_SESSION['useraccount']."') FROM Dual ";
				$result = selectData($connection, $query);
				$result = $result[0];
				//echo $query; exit;
				//echo 'error='.$result; exit;
				if ($result != 0){ 
					fcommit();
					
					$query   = " SELECT PurchaseJV_Reference, Costcenter_code, Project_Code FROM PurchasesJV WHERE PurchaseJV_ID = '".$SId."'";
					$result  = selectData($connection, $query);
					$vRef  = $result[0];
					$vCostCentCode = $result[1];
					$vProjectCode  = $result[2];
					
					$existCode = 0;
					if ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $vRef != ''){
						$querychk = "select 1 from sequence where '$vOldCostCentCode' like Concat(Sequence.CostCenter,'%') and '$txtCostCentCode' like Concat(Sequence.CostCenter,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					if ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $vRef != ''){
						$querychk = "select 1 from sequence where '$vOldProjCode' like Concat(Sequence.Project,'%') and '$txtProjectCode' like Concat(Sequence.Project,'%') ";
						$reschk = mysql_query($querychk, $connection);
						$rwchk = mysql_fetch_row($reschk);
						$existCode = $rwchk[0];
					}
					
					if ($vRef == '' || ($vOldProjCode != $txtProjectCode && $Module_ReferenceByProject == 1 && $existCode == 0) ||
						 ($vOldCostCentCode != $txtCostCentCode && $Module_ReferenceByCostcenter == 1 && $existCode == 0)) {
							 
						if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
						else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
						else $vProjCostCent = '';
									
							
						fbegin();
						$vRef = get_nextsequence('PurchasesJV_Reference',$vProjCostCent,$connection);	
						fcommit();
								
						$query = " UPDATE PurchasesJV SET ".
								 " PurchaseJV_Reference = $vRef ".
								 " WHERE PurchaseJV_ID = $SId ";
								
						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
							
					}	
						
					
					if ($Module_PostToJournal == 1) {
						$message = Create_PurchasesJVJv($SId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username'], $FI_BelongsToGrp); 
						//echo $message; exit;
					}
						// add item jour when ledger asset = 1
						Add_ItemJour($SId, $FI_BelongsToGrp, $base1, $base2, $connection);
					 
				} else{
					$ErrorExists = 1;
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempPurchasesJV Function.'; 
					frollback();
				}
			
			}	
		} else{
			$message  = mysql_error(); 
			frollback();
		}
		if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '".$SId."', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'purchasesjv', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}
		
	}
	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.';
		
	}
}


$message = ereg_replace(' ','%20',$message);
$message = ereg_replace('#','%23',$message);
$message = ereg_replace('&','%26',$message);

$PRemark = ereg_replace(' ','%20',$PRemark);
$PRemark = ereg_replace('#','%23',$PRemark);
$PRemark = ereg_replace('&','%26',$PRemark);

$PInvoiceNo = ereg_replace(' ','%20',$PInvoiceNo);
$PInvoiceNo = ereg_replace('#','%23',$PInvoiceNo);
$PInvoiceNo = ereg_replace('&','%26',$PInvoiceNo);

$PManualNo = ereg_replace(' ','%20',$PManualNo);
$PManualNo = ereg_replace('#','%23',$PManualNo);
$PManualNo = ereg_replace('&','%26',$PManualNo);


//echo $mode.$message; exit;

if($mode == "post") {
	if ($SaveAllowed == 1)
		header ("Location: ./Form_PurchasesJV.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrId=".$SId."&PrRef=".$vRef);
	else
		header ("Location: ./Form_PurchasesJV.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtPurchasesJVId=".$SId);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_PurchasesJVSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_PurchasesJVSearchPending.php?message=".$message);
else if ($mode == "deletedt" )		
	header ("Location: ./Form_PurchasesJV.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtPurchasesJVId=".$SId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_PurchasesJVDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PId=".$SId."&PDate=".$PDate."&PDtId=".$PDtId);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_PurchasesJVSearch.php?PMode=1&message=".$message);	
else if( $mode == "" && $mainmode == "loadporderjv" )
	header ("Location: ./Form_PurchasesOrderJVPost.php?PMode=1&PrId=$SId&message=".$message);
else if ($mode == "submitrecord" ){
    header ("Location: ./Form_PurchasesJVDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PId=".$SId."&PDate=".$PDate."&PMaturityDate=".$PMaturityDate.	
			"&PSupplierCode=".$PSupplierCode."&PInvoiceNo=".$PInvoiceNo."&PCurr=".$PCurr."&PProjectCode=".$PProjectCode.
			"&PCostCentCode=".$PCostCentCode."&PDiscountPer=".$PDiscountPer."&PDiscountAmt=".$PDiscountAmt."&PVatChkbx=".$PVatChkbx.
			"&PManualNo=".$PManualNo."&PRemark=".$PRemark."&message=".$message);
}	
		
						  
function Calculate_MasterAmounts($PId, $PDate, $PVatChk, $PDiscPer, $PDiscAmt, $PRate, $PRate1, $PRate2, $PSetupVatStartDate, $PSetupVatPercentage, $PMode, $connection) {

	$vDtTotal  = 0;
	$vDtVatChk = 0;
	
	$vTaxable        = 0;
	$vNoneTaxable    = 0;
	$vGrossTotal     = 0;
	$vDiscountAmt    = 0;
	$vDiscountPer    = 0;
	$vVatAmt         = 0;
	$vVatAmtBase1    = 0;
	$vVatAmtBase2    = 0;
	$vNetTotal    	 = 0;
	$vNetTotalBase1	 = 0;
	$vNetTotalBase2	 = 0;
		
	

	$vDiscountPer = $PDiscPer;
	
	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(PurchaseJV_VatCheck, 0) From Temp_PurchasesJV Where PurchaseJV_ID = '".$PId."'";
		//echo "<br><br>".$sub_query;
		$sub_result = selectData($connection, $sub_query);
		$PVatChk    = $sub_result[0];
	
	}
	
		
	//Calculating Master Amounts
	$sub_query = " Select Ledger_Number, ((ifNull(PurchaseJVDt_Quantity,0)*ifNull(PurchaseJVDt_Price,0))-((ifNull(PurchaseJVDt_Quantity,0)*ifNull(PurchaseJVDt_Price,0)*ifNull(PurchaseJVDt_DiscPer,0))/100)) As Total, ".
				 " ifNull(PurchaseJVDt_VAT,0),  PurchaseJVDt_Quantity, ifNull(PurchaseJVDt_DiscAmount,0) ".
				 " From Temp_PurchasesJVDt ".
				 " Where PurchaseJV_ID = ".$PId;
										 
	//echo $sub_query;
	$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());
	while($sub_rows=mysql_fetch_array($sub_result)){

		$vDtTotal   = $sub_rows[1];
		$vDtVatChk  = $sub_rows[2];
						
		$tax_flag = 0;
		$notax_flag = 1;
		if ($vDtVatChk > 0){
			$tax_flag = 1;
			$notax_flag = 0;
		}	
						
							
		$vTaxable     = $vTaxable     + ($vDtTotal*$tax_flag);
		$vNoneTaxable = $vNoneTaxable + ($vDtTotal*$notax_flag);
						
		
		// Calculation of Vat Amount
		if ((insertDate($PDate) > $PSetupVatStartDate && $PSetupVatPercentage > 0)  && $PVatChk == 1 && $vDtVatChk == 1 && $vDtTotal > 0)
			$vVatAmt = $vVatAmt + (($vDtTotal - $sub_rows[4])*$PSetupVatPercentage/100);
					
	}			
					
		
	$vGrossTotal = $vTaxable + $vNoneTaxable;
					
	// Calculation of Discount Amount	
	
	if ($PMode == 'P') {
		$vDiscountAmt      = $PDiscAmt;					
	} else {
		if ($vDiscountPer > 0) {
			$vDiscountAmt     = (($vGrossTotal * $vDiscountPer) / 100);
		}	
	}
		
					
	$vTaxableBase1     = ($vTaxable*$PRate)/$PRate1;
	$vTaxableBase2     = ($vTaxable*$PRate)/$PRate2;
	$vNoneTaxableBase1 = ($vNoneTaxable*$PRate)/$PRate1;
	$vNoneTaxableBase2 = ($vNoneTaxable*$PRate)/$PRate2;
	$vDiscountAmtBase1 = ($vDiscountAmt*$PRate)/$PRate1;
	$vDiscountAmtBase2 = ($vDiscountAmt*$PRate)/$PRate2;
	$vGrossTotalBase1  = ($vGrossTotal*$PRate)/$PRate1;
	$vGrossTotalBase2  = ($vGrossTotal*$PRate)/$PRate2;
	$vVatAmtBase1 	   = ($vVatAmt*$PRate)/$PRate1;
	$vVatAmtBase2 	   = ($vVatAmt*$PRate)/$PRate2;
	$vNetTotal         = $vGrossTotal + $vVatAmt - $vDiscountAmt;
	$vNetTotalBase1    = $vGrossTotalBase1 + $vVatAmtBase1 - $vDiscountAmtBase1;
	$vNetTotalBase2    = $vGrossTotalBase2 + $vVatAmtBase2 - $vDiscountAmtBase2;
					

	fbegin();
	
				 
	$sub_query1 = " UPDATE Temp_PurchasesJV SET ".
				  " PurchaseJV_Taxable = $vTaxable, PurchaseJV_TaxableBase1 = $vTaxableBase1, PurchaseJV_TaxableBase2 = $vTaxableBase2, ".
				  " PurchaseJV_NoneTaxable = $vNoneTaxable, PurchJV_NoneTaxableBase1 = $vNoneTaxableBase1, PurchJV_NoneTaxableBase2 = $vNoneTaxableBase2, ".
				  " PurchaseJV_DiscAmount = $vDiscountAmt, PurchaseJV_DiscAmount1 = $vDiscountAmtBase1, PurchaseJV_DiscAmount2 = $vDiscountAmtBase2, ".
				  " PurchaseJV_DiscountPer = $vDiscountPer, PurchaseJV_VAT = $vVatAmt, PurchaseJV_VatBase1 = $vVatAmtBase1, PurchaseJV_VatBase2 = $vVatAmtBase2, ".
				  " PurchaseJV_VatCheck = $PVatChk, ".
				  " PurchaseJV_Total = $vGrossTotal, PurchaseJV_TotalBase1 = $vGrossTotalBase1, PurchaseJV_TotalBase2 = $vGrossTotalBase2, ".
				  " PurchaseJV_Amount = $vNetTotal, PurchaseJV_AmountBase1 = $vNetTotalBase1, PurchaseJV_AmountBase2 = $vNetTotalBase2 ".
				  " WHERE PurchaseJV_ID = ".$PId;
		
	$sub_result1=mysql_query($sub_query1,$connection);
	//echo $sub_query1."<br>";exit;
	if ($sub_result1){
		fcommit();
						
	}else{
		$message  = mysql_error(); 
		$error = 'Error In Function Calculate_MasterAmounts: '.$message;
		frollback();
	}
			
	Return $error;		

}

function Add_ItemJour($SId, $FI_BelongsToGrp, $base1, $base2, $connection){
	$query = "select ledger_assetCode, PurchaseJVDt_Description, purchasesjvdt.Currency_Code, purchasesjvdt.Costcenter_Code, 
			  purchasesjvdt.Project_Code, purchasejvdt_assetPer, round(purchasejvdt_price*purchasejvdt_quantity,2), purchasesjvdt.Ledger_Number, ledger_assetDebit, ledger_assetCredit,
			  PurchaseJV_Date, itemjour.purchasejvdt_id, purchasesjvdt.purchasejvdt_id, ledger_assetLength, ledger_assetSequence
			  from ledger
			  inner join purchasesjvdt on purchasesjvdt.Ledger_Number = ledger.ledger_number
			  left join itemjour on itemjour.purchasejvdt_id = purchasesjvdt.purchasejvdt_id
			  where ifnull(ledger_asset,0) = 1 and purchasejv_id = $SId ";
			  
	$result = mysql_query($query, $connection);
	while ($row = mysql_fetch_array($result)){
		$amount = $row[6];
		$amount1 = ConvertCurrency($row[2], $base1, $row[10], $amount, $connection);
		$amount2 = ConvertCurrency($row[2], $base2, $row[10], $amount, $connection);
		
		if ($row[11] == ''){
			$assetCode = $row[0];
			if ($assetSeq == '') $assetSeq  = $row[14];
			if ($assetSeq == '') $assetSeq = 0;
			$assetLen  = $row[13];
			$assetCode = $assetCode.str_pad($assetSeq, $assetLen, '0', STR_PAD_LEFT);
			
			$assetSeq += 1;
			
			$queryins = "insert into itemjour (ItemJour_Code, ItemJour_Description, Currency_Code, Costcent_code, Project_Code, ItemJour_prcnt, ItemJour_amount, ItemJour_amount1, ItemJour_amount2, Ledger_Number, 
							Ledger_NumberDebit, CostCent_CodeDebit, Project_codeDebit, Ledger_NumberCredit, CostCent_CodeCredit, Project_CodeCredit, Journal_Date, JournalDt_ValueDate, 
							ItemJour_BelongsToGroup, purchasejvdt_id) values 
						( ".GetSQLValueString($assetCode,'text').", ".GetSQLValueString($row[1],'text').", '".$row[2]."', ".GetSQLValueString($row[3],'text').", ".GetSQLValueString($row[4],'text').", ".GetSQLValueString($row[5],'text').",".
						" $amount, $amount1, $amount2, '".$row[7]."', ".GetSQLValueString($row[8],'text').", ".GetSQLValueString($row[3],'text').", ".GetSQLValueString($row[4],'text').", ".GetSQLValueString($row[9],'text').", ".
						" ".GetSQLValueString($row[3],'text').", ".GetSQLValueString($row[4],'text').", '".$row[10]."', '".$row[10]."', '$FI_BelongsToGrp', '".$row[12]."' )";
			$resins = mysql_query($queryins, $connection);
			if ($resins){
				$up = "update ledger set ledger_assetSequence = $assetSeq where ledger_number = '".$row[7]."' ";
				$res = mysql_query($up, $connection);
			}
			
		} else {
			$queryup = "update itemjour set
							ItemJour_Description = ".GetSQLValueString($row[1],'text').", 
							Currency_Code = '".$row[2]."', 
							Costcent_code = ".GetSQLValueString($row[3],'text').", 
							Project_Code = ".GetSQLValueString($row[4],'text').", 
							ItemJour_prcnt = ".GetSQLValueString($row[5],'text').", 
							ItemJour_amount = $amount, 
							ItemJour_amount1 = $amount1, 
							ItemJour_amount2 = $amount2, 
							Ledger_Number = '".$row[7]."', 
							Ledger_NumberDebit = ".GetSQLValueString($row[8],'text').", 
							CostCent_CodeDebit = ".GetSQLValueString($row[3],'text').", 
							Project_codeDebit = ".GetSQLValueString($row[4],'text').", 
							Ledger_NumberCredit = ".GetSQLValueString($row[9],'text').", 
							CostCent_CodeCredit = ".GetSQLValueString($row[3],'text').", 
							Project_CodeCredit = ".GetSQLValueString($row[4],'text').", 
							Journal_Date = '".$row[10]."', 
							JournalDt_ValueDate = '".$row[10]."', 
							ItemJour_BelongsToGroup = '$FI_BelongsToGrp' 
						where purchasejvdt_id = '".$row[11]."' "; 
			$resup = mysql_query($queryup, $connection);
			
		}
	}	
	
}
print <<<HERE
</form>
</body>

HERE;


?>