<?php

session_start();

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

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

/////////////////////////////////////////////
// Add in Page You Want To Debug////////////
// ---------------------------------///////
//////////////////////////////////////////

define("_DEBUG",       "DEBUG MODE ON");
define("_PRODUCTION",  "DEBUG MODE OFF");
///////////////////////////////////////////   
$_mode = _PRODUCTION;   // Set mode to production after debug is finished
$_showhiddeninputs = 0; //show hidden inputs 1/0 only will work in debug mode 
   


 
if ($_mode == _DEBUG) 
{

///////////////////////////////////////////////////////////
error_reporting (E_ALL ^ E_NOTICE ^ E_WARNING);
///////////////////////////////////////////////////////////
ini_set('display_errors', TRUE); // Error display
ini_set('log_errors', TRUE); // Error logging
ini_set('error_log', '../notice-logs.log'); // Logging file   // ../  to create file in main root cz ususaly root is contract
ini_set('log_errors_max_len', 10240); // Logging file size
///////////////////////////////////////////////////////////
}

 

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

//Read From SalesSetup Table
   $querySalesSetup="Select TipsMaxBase1,ifnull(TipsMaxBase2,0), ifnull(salesjv_paymentmode,0) as salesjv_paymentmode ,cashcur , cashcur2 ,creditaccount,creditaccount2,cashaccount,cashaccount2,checkaccount,checkaccount2  From SalesSetup";
   $resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
   while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
   	extract($rowSalesSetup);
   }

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

//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 , ifnull(module_shipmentclosing,0) as module_shipmentclosing ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}

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


if ($actionmode == 'addRemark'){
	$salesJvId = $_GET['salesJvId'];
	$query = "select setup_id, remark_description from sorderJv_RemarkSetup order by remark_description";
	$result = mysql_query($query,$connection);

	while($row = mysql_fetch_array($result)){
		$querychk = "select salesJvRemarkdt_id from temp_salesJvRemarkdt where salesJv_id = $salesJvId and Remarkdt_id = $row[0] ";
		$reschk = mysql_query($querychk,$connection);
		$rowchk = mysql_fetch_row($reschk);
		$salesJvRemarkdt_id = $rowchk[0];
		
		$remarkchk = 'remarkchk'.$row[0];
		if($$remarkchk == '') $$remarkchk = 0;
		
		if($salesJvRemarkdt_id == ''){
			fbegin();	
			$salesJvRemarkdt_id = get_nextsequence('salesJvRemarkdt_id','',$connection);	
			fcommit();
			$queryins = "insert into temp_salesJvRemarkdt (salesJvRemarkdt_id, salesJv_id, Remarkdt_id, salesJvRemarkdt_chk) values 
						($salesJvRemarkdt_id, $salesJvId, $row[0], ".$$remarkchk.") ";
			$resin =mysql_query($queryins, $connection);			
			
		} else {
			$queryup = "update temp_salesJvRemarkdt set salesJvRemarkdt_chk =  ".$$remarkchk." where salesJvRemarkdt_id = $salesJvRemarkdt_id ";
			$resup =mysql_query($queryup, $connection);			
		}
	}
	header("Location: ./Form_SalesJvRemark.php?jvId=$salesJvId");
	exit;
}
if($actionmode == "searchcustomer"){
		$txtClientCode = $_GET['txtClientCode'];
		$query_checkcustomer  = "select ledger_number as CustomerCode, ledger_name as CustomerName  
		                         from clients
								 where ledger_number = '$txtClientCode'";
		$result_checkcustomer = mysql_query($query_checkcustomer, $connection);
		$num_checkcustomer    = mysql_num_rows($result_checkcustomer);
		if($num_checkcustomer > 0){
			$response = 1;
		}
		else{
			$response = 0;
		}
		$row_checkcustomer    = mysql_fetch_array($result_checkcustomer);
		extract($row_checkcustomer);
		echo $response;
		echo "[BRK]";
		echo $CustomerCode;
		echo "[BRK]";
		echo $CustomerName;
		echo "[BRK]";
		exit;
	}

	else if($actionmode == "SetExpAmt"){
		$txtGitLedger = $_GET['txtGitLedger'];
		$txtDate = $_GET['txtDate'];
		$txtProjectCode = $_GET['txtProjectCode'];
		$query="SELECT
					ledger.ledger_number, 
					ledger.ledger_name,
					ifnull(sum( IF ( journaldt_dbcd = 'D',
				Journaldt_amount1 
						, (-1) *  Journaldt_amount1 
					) ),0) AS Balance,journal.project_code,
					expences_ledger,income_ledger
					
					FROM journaldt
					
					LEFT JOIN ledger ON ledger.ledger_number = journaldt.ledger_number
					left join ShipmentClosing_setup on ShipmentClosing_setup.ledger_number = journaldt.ledger_number
					LEFT JOIN journal ON journal.journal_id = journaldt.journal_id
					LEFT JOIN project ON journal.project_code = project.project_code
					where journaldt.journal_date <= '".insertMySQLDate($txtDate)."' and 
					 ledger.ledger_number =  '$txtGitLedger' 
					and  journal.project_code =  '$txtProjectCode' 
					GROUP BY journal.project_code,ledger.ledger_number";
					//echo $query;exit;
		$result= mysql_query($query, $connection);
		
		$row   = mysql_fetch_array($result);
		extract($row);
		echo "[BRK]";
		echo $Balance;
		echo "[BRK]";
		echo $expences_ledger;
		echo "[BRK]";
		exit;
	}
else
    if($actionmode == "searchledger"){
		$txtLedgerNo = $_GET['txtLedgerNo'];
		$query_chkledger = "select ledger_number as LedgerNumber, ledger_name as LedgerName
		                    from ledger
							where ledger_number = '$txtLedgerNo' and Ledger_grpdet = 0";
		$result_chkledger = mysql_query($query_chkledger, $connection);
		$num_chkledger    = mysql_num_rows($result_chkledger);
		$row_chkledger    = mysql_fetch_array($result_chkledger);
		extract($row_chkledger);
		if($num_chkledger > 0){
			$response = 1;
		}
		else{
			$response = 0;
		}
		echo $response;
		echo "[BRK]";
		echo $LedgerNumber;
		echo "[BRK]";
		echo $LedgerName;
		echo "[BRK]";
		exit;
	}		
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='insertsalesjv' 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" ){

	$ErrorExists = 0;

	$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"];
	$txtDtCost 			= $_GET["value13"];
	$txtterms 			= $_GET["txtterms"];

	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 Client, Salesman, 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 ($PClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$PClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($PSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$PSalesmanCode."'";
		$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 ($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 Client/Salesman/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($cashcurrency1) ) $cashcurrency1 = 0;
		if (empty($bankcurrency1) ) $bankcurrency1 = 0;		
		if (empty($cardcurrency1) ) $cardcurrency1 = 0;		
		if (empty($cashcurrency2) ) $cashcurrency2 = 0;		
		if (empty($bankcurrency2) ) $bankcurrency2 = 0;
		if (empty($cardcurrency2) ) $cardcurrency2 = 0;

		if (empty($PCostCentCode))		$CostCentCode = 'Null';
		else		$CostCentCode = "'".$PCostCentCode."'";

		if (empty($PProjectCode))	$ProjectCode = 'Null';
		else		$ProjectCode = "'".$PProjectCode."'";

		if (empty($PSalesmanCode))	$SalesmanCode = 'Null';
		else	$SalesmanCode = "'".ereg_replace("'", "\'", trim($PSalesmanCode))."'";		

		fbegin();	
		$vSalesJVId = get_nextsequence('SalesJV_Id','',$connection);	
		fcommit();

		$Acc_Query = " SELECT VATAccountNonStock, DiscountAccount FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);

		//$vVatAccount = $Acc_Result[0];
		if (empty($PVatPrefix)) $vVatAccount = $Acc_Result[0];
		else $vVatAccount = $PVatPrefix;

		$sub_queryVat = " SELECT GetVATAccount('".$PClientCode."','".$vVatAccount."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vVatAccount = $sub_resultVat[0];

		if($costcent_applyvat==0) $PVatChkbx=0; 
		 /*
		&cashcurrency1=0&bankcurrency1=0&cardcurrency1=0&cashcurrency2=0&bankcurrency2=0&cardcurrency2=0
		*/
		fbegin(); //    on begin  insert payment accounts from sales setup 
		$query = " INSERT INTO Temp_SalesJV (SalesJV_ID, SalesJV_Reference, SalesJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
				 " Currency_Code, Project_Code, Costcenter_Code, SalesJV_Posted, SalesJV_Edit, Sales_Mode, SalesJV_BelongsToGroup, Journal_Type, Journal_Id, ".
				 " SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, ".
				 " SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, SalesJV_VAT, SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_DiscountPer, ".
				 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, SalesJV_VatAccount, SalesJV_DiscountAccount, SalesJv_ManualNo, ".
				 " SalesJv_VatPrefix, User_Account, Logged_Code,SalesJv_CashAmmount1,SalesJv_BankAmmount1, SalesJv_CreditCardAmmount1  ,SalesJv_CashAmmount2,SalesJv_BankAmmount2, ".
				 " SalesJv_CreditCardAmmount2 , SalesJv_CashAccount1,SalesJv_CashAccount2,SalesJv_BankAccount1,SalesJv_BankAccount2,SalesJv_CreditCardAccount1,SalesJv_CreditCardAccount2,".
				 " SalesJV_PaymentTerms,salejv_gitledger,salejv_expledger,salejv_expamount ) ".
				 " VALUES ( ".$vSalesJVId.", Null, '".insertMySQLDate($PDate)."', '".insertMySQLDate($PMaturityDate)."', '".ereg_replace("'", "\'", trim($PClientCode))."', ".
				 "          $SalesmanCode, '".ereg_replace("'", "\'", trim($PRemark))."', '".$PCurr."', $ProjectCode, $CostCentCode, ".
				 "          0, 0, 0, $FI_BelongsToGrp, 'JS', Null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $PVatChkbx, 0, 0, 0, 0, '".$vVatAccount."', '".$Acc_Result[1]."', ".
				 "          '".ereg_replace("'", "\'", trim($PManualNo))."', '".trim($PVatPrefix)."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."'". 
				 "," .$cashcurrency1 .",".$bankcurrency1 .",".$cardcurrency1 .",".$cashcurrency2 .",".$bankcurrency2 .",".$cardcurrency2 ."";

				// $query = $query . "," .$creditaccount ."," .$creditaccount2 ."," .$cashaccount ."," .$cashaccount2 .",".$checkaccount.",".$checkaccount2;

				 $query = $query . "," .GetSQLValueString($cashaccount,'text') ."," .GetSQLValueString($cashaccount2,'text') ."," .GetSQLValueString($checkaccount,'text') .",
									" .GetSQLValueString($checkaccount2,'text') .",".GetSQLValueString($creditaccount,'text').",".GetSQLValueString($creditaccount2,'text');

				 // Cash Bank Credit

				 $query = $query  ." , " .GetSQLValueString($txtterms,'text') ." 
				 , " .GetSQLValueString($gitledger,'text') ." , " .GetSQLValueString($expledger,'text') .", " .GetSQLValueString($expamt,'double') ." )";
				 
				// global $_mode; 
                // if($_mode == _DEBUG ) trigger_error($$query,E_USER_NOTICE);  // exit;


		$result=mysql_query($query,$connection);
		//echo $query."<br>";exit;	

		if ($result){
			$SId = $vSalesJVId;
			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;  

		if (empty($PCostCentCode))		$CostCentCode = 'Null';
		else		$CostCentCode = "'".$PCostCentCode."'";

		if (empty($PProjectCode))	$ProjectCode = 'Null';
		else		$ProjectCode = "'".$PProjectCode."'";   

		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($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;

		/* Cost HERE */

		$vDtCost          =  $txtDtCost;
		if ($vDtCost == '') $vDtCost = 0;
		$vDtCostBase1     = ($vDtCost*$rate_dt)/$rate_dt1;
		$vDtCostBase2     = ($vDtCost*$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 SalesJvDt_ID From SalesJvDt ".
						 "                        Where SalesJvDt.Journal_Type = 'JS' and upper(SalesJvDt.SalesJvDt_ManualNo) = '".$txtDtManualNo."' and SalesJvDt.SalesJvDt_ID != $SDtId ".
						 "                 Union  Select SalesJvDt_ID From Temp_SalesJvDt as SalesJvDt ".
						 "                        Where SalesJvDt.Journal_Type = 'JS' and upper(SalesJvDt.SalesJvDt_ManualNo) = '".$txtDtManualNo."' and SalesJvDt.SalesJvDt_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();
			$vSalesJVDtId = get_nextsequence('SalesJVDt_Id','',$connection);	
			fcommit();

			fbegin();

			// INsert  Income Account , Cost Account , SupplierAccount

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

	         $querydflproject="select CostAccount, SupplierAccount from salesjvsetup where IncomeAccount = '".ereg_replace("'", "\'", trim($txtLedgerNo))."'  ";
             $resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
               while($rows=mysql_fetch_array($resultdflproject)){
             	extract($rows);
				}
				if ($txtexpamt=='') $txtexpamt=0;
      if($salesjv_paymentmode ==1)
	  {
			$query = " INSERT INTO Temp_SalesJVDt (SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesJVDt_Description, SalesJVDt_Description2, ". 
					 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, ".
					 " SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDTCalcTotal, SalesJVDt_VAT, Journal_Type, SalesJvDt_ManualNo, cost, costbase1, costbase2, costaccount,
					  supplieraccount, Logged_Code ,ledger_numbercredit ,ledger_numberdebit,expencesamt )  ".
					 " VALUES ( ".$vSalesJVDtId.", ".$SId.", '".insertMySQLDate($PDate)."', '".$PCurr."', '".ereg_replace("'", "\'", trim($PClientCode))."', ".
					 "          '".ereg_replace("'", "\'", trim($PSalesmanCode))."', '".ereg_replace("'", "\'", trim($txtLedgerNo))."', '".ereg_replace("'", "\'", trim($txtDescription1))."', ".
					 "          '".ereg_replace("'", "\'", trim($txtDescription2))."', $ProjectCodeDt, $CostCentCodeDt, $vDtQty, $vDtPrice, $vDtPriceBase1, $vDtPriceBase2, $vDtDiscPer, ".
					 "          $vDtDiscAmt, $vDtDiscAmtBase1, $vDtDiscAmtBase2, $vDtTotal, $vDtVat, 'JS', $vDtManualNo, $vDtCost, $vDtCostBase1, $vDtCostBase2, '".$CostAccount."' , '".$SupplierAccount."', ".
					 " '".$_SESSION['useraccount']."','$txtledgernocl' ,'$txtledgernoexp','$txtexpamt'	) ";		  
	  }
	  else
	  {
		  			$query = " INSERT INTO Temp_SalesJVDt (SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesJVDt_Description, SalesJVDt_Description2, ". 
					 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, ".
					 " SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDTCalcTotal, SalesJVDt_VAT, Journal_Type, SalesJvDt_ManualNo, Logged_Code ,ledger_numbercredit ,ledger_numberdebit,expencesamt )  ".
					 " VALUES ( ".$vSalesJVDtId.", ".$SId.", '".insertMySQLDate($PDate)."', '".$PCurr."', '".ereg_replace("'", "\'", trim($PClientCode))."', ".
					 "          '".ereg_replace("'", "\'", trim($PSalesmanCode))."', '".ereg_replace("'", "\'", trim($txtLedgerNo))."', '".ereg_replace("'", "\'", trim($txtDescription1))."', ".
					 "          '".ereg_replace("'", "\'", trim($txtDescription2))."', $ProjectCodeDt, $CostCentCodeDt, $vDtQty, $vDtPrice, $vDtPriceBase1, $vDtPriceBase2, $vDtDiscPer, ".
					 "          $vDtDiscAmt, $vDtDiscAmtBase1, $vDtDiscAmtBase2, $vDtTotal, $vDtVat, 'JS', $vDtManualNo,  ".
					 " '".$_SESSION['useraccount']."' ,'$txtledgernocl' ,'$txtledgernoexp' ,'$txtexpamt'	) ";
	  }


			//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;   // ID is data 1 ,  cz data 0 is document
	echo "[BRK]";
	echo $message;  //data 2 
	echo "[BRK]";
	if ($salesjv_paymentmode == '1'){
			$queryExtractBases="select  Round((ifNull(SalesJV_Totalbase1,0) + IfNull(SalesJV_VATbase1,0) - IfNull(SalesJV_DiscountAmount1,0)), 2) As SalesJV_NetTotal , Round((ifNull(SalesJV_TotalBase2,0) + IfNull(SalesJV_VatBase2,0) - IfNull(SalesJV_DiscountAmount2,0)), 2) As SalesJV_NetTotal2  from temp_salesjv	where SalesJV_Id = " .$SId;;

	   $resultextractbases=mysql_query($queryExtractBases,$connection) or die(mysql_error());
	   while($rows=mysql_fetch_array($resultextractbases)){
		extract($rows);
	   }
	
	
      
		 
/*		  
	$queryExtractBases=" select  Round((ifNull(SalesJV_Total,0) + IfNull(SalesJV_VAT,0) - IfNull(SalesJV_DiscountAmount,0)), 2) As SalesJV_NetTotal , Round((ifNull(SalesJV_TotalBase2,0) + IfNull(SalesJV_VatBase2,0) - IfNull(SalesJV_DiscountAmount2,0)), 2) As SalesJV_NetTotal2  from temp_salesjv	where SalesJV_Id = " .$SId; */

   $resultextractbases=mysql_query($queryExtractBases,$connection) or die(mysql_error());
   while($rows=mysql_fetch_array($resultextractbases)){
	extract($rows);
   }
 
		$val1 =  round($SalesJV_NetTotal,$DecimalBase);
		$val2 =  round($SalesJV_NetTotal2,$DecimalBase2);
		
		//;
 	
		$val1 = "Total: " .number_format($val1 . "" ,$DecimalBase)  .$base1;
		$val2 = "Total: " .number_format($val2 . "" ,$DecimalBase2) .$base2;
	} 
	else {
		$val1 = '';
		$val2 = '';
	}
	echo  $val1;// data 3

	echo "[BRK]";

	echo $val2;
    echo "[BRK]";	//data 4
	      //_rodolphe   
	
exit;
} 
else if ($actionmode=='checkaccountno'){

$codedesc = $_GET["codedesc"];

$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;
}	
//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_SalesJVDt For Selected Record
		$query = " DELETE FROM Temp_SalesJVDt ".
				 " WHERE SalesJVDt_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

}

//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"];
	$txtDtCost = $_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;  

	$ErrorExists = 0;

	$vDtQty           = 0;
	$vDtDiscPer       = 0;
	$vDtTotal         = 0;
	$vDtPrice         = 0;
	$vDtPriceBase1    = 0;
	$vDtPriceBase2    = 0;

	$vDtCost         = 0;
	$vDtCostBase1    = 0;
	$vDtCostBase2    = 0;

	$vDtDiscAmt       = 0;
	$vDtDiscAmtBase1  = 0;
	$vDtDiscAmtBase2  = 0;

	$sub_query = " Select Currency_code, ifNull(SalesJV_DiscountPer,0), date_format(SalesJV_Date, '%d/%m/%Y'), ifNull(SalesJV_VatCheck,0) ".
				 " From Temp_SalesJV As SalesJV ".
				 " Where SalesJV_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];

	if (empty($txtDtManualNo)) $vDtManualNo = 'Null';
	else	$vDtManualNo = "'".$txtDtManualNo."'";

	$vDtQty        = $txtDtQty;
	$vDtDiscPer    = $txtDtDiscPer;
	$vDtVat        = $txtDtVat;
	$vDtTotal      = $txtDtTotal;

	$vDtPrice      = $txtDtPrice;
	$vDtPriceBase1 = ($vDtPrice*$rate_dt)/$rate_dt1;
	$vDtPriceBase2 = ($vDtPrice*$rate_dt)/$rate_dt2;

    $vDtCost          =  $txtDtCost;
	if ($vDtCost == '') $vDtCost = 0;
	$vDtCostBase1     = ($vDtCost*$rate_dt)/$rate_dt1;
	$vDtCostBase2     = ($vDtCost*$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;

	//Check For Manual No To Be Unique
	if ($Module_UniqueManualNo == 1 && $txtDtManualNo != "") {
		$sub_query = " Select Count(*) From ( Select SalesJvDt_ID From SalesJvDt ".
					 "                        Where SalesJvDt.Journal_Type = 'JS' and upper(SalesJvDt.SalesJvDt_ManualNo) = '".$txtDtManualNo."' and SalesJvDt.SalesJvDt_ID != $SDtId ".
					 "                 Union  Select SalesJvDt_ID From Temp_SalesJvDt as SalesJvDt ".
					 "                        Where SalesJvDt.Journal_Type = 'JS' and upper(SalesJvDt.SalesJvDt_ManualNo) = '".$txtDtManualNo."' and SalesJvDt.SalesJvDt_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){
		 $querydflproject="select CostAccount, SupplierAccount from salesjvsetup where IncomeAccount = '".ereg_replace("'", "\'", trim($txtLedgerNo))."'  ";
		 $resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
		   while($rows=mysql_fetch_array($resultdflproject)){
			extract($rows);
			}

		fbegin();
		if($txtexpamt=='') $txtexpamt=0;
		      if($salesjv_paymentmode ==1)
	  {
		  	$query = " UPDATE Temp_SalesJVDt SET ".
				 " SalesJVDt_Description = '".ereg_replace("'", "\'", trim($txtDescription1))."', SalesJVDt_Description2 = '".ereg_replace("'", "\'", trim($txtDescription2))."',  ". 
				 " SalesJVDt_Quantity = $vDtQty, SalesJVDt_Price = $vDtPrice, SalesJVDt_PriceBase1 = $vDtPriceBase1, SalesJVDt_PriceBase2 = $vDtPriceBase2,  ".
				 " SalesJVDt_DiscountPer = $vDtDiscPer, SalesJVDt_DiscountAmount = $vDtDiscAmt, SalesJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesJVDt_DiscountAmount2 = $vDtDiscAmtBase2,  ".
				 " SalesJVDTCalcTotal = $vDtTotal, SalesJVDt_VAT = $vDtVat, SalesJvDt_ManualNo = $vDtManualNo, ledger_number = '$value1', ".
				 " cost = $vDtCost, costbase1 = $vDtCostBase1, costbase2 = $vDtCostBase2, costaccount = '".$CostAccount."' , supplieraccount = '".$SupplierAccount."'
				 ,ledger_numbercredit = '$txtledgernocl' ,ledger_numberdebit = '$txtledgernoexp' ,expencesamt= '$txtaxpamt' ";
	  }
	  else
	  {
		  	$query = " UPDATE Temp_SalesJVDt SET ".
				 " SalesJVDt_Description = '".ereg_replace("'", "\'", trim($txtDescription1))."', SalesJVDt_Description2 = '".ereg_replace("'", "\'", trim($txtDescription2))."',  ". 
				 " SalesJVDt_Quantity = $vDtQty, SalesJVDt_Price = $vDtPrice, SalesJVDt_PriceBase1 = $vDtPriceBase1, SalesJVDt_PriceBase2 = $vDtPriceBase2,  ".
				 " SalesJVDt_DiscountPer = $vDtDiscPer, SalesJVDt_DiscountAmount = $vDtDiscAmt, SalesJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesJVDt_DiscountAmount2 = $vDtDiscAmtBase2,  ".
				 " SalesJVDTCalcTotal = $vDtTotal, SalesJVDt_VAT = $vDtVat, SalesJvDt_ManualNo = $vDtManualNo, ledger_number = '$value1' 
				 ,ledger_numbercredit = '$txtledgernocl' ,ledger_numberdebit = '$txtledgernoexp' ,expencesamt = '$txtexpamt'  ";
				 
	  }
	

		if ($Module_ProjectDt == 1)
			$query = $query.", Project_Code = $ProjectCodeDt ";
		if ($Module_CostCenterDt == 1)	
			$query = $query.", CostCenter_Code = $CostCentCodeDt ";	

		$query = $query." WHERE SalesJVDt_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();
		}
	}

	
	if ($salesjv_paymentmode == '1'){
		$queryExtractBases=" select  Round((ifNull(SalesJV_Totalbase1,0) + IfNull(SalesJV_VATbase1,0) - IfNull(SalesJV_DiscountAmount1,0)), 2) As SalesJV_NetTotal , Round((ifNull(SalesJV_TotalBase2,0) + IfNull(SalesJV_VatBase2,0) - IfNull(SalesJV_DiscountAmount2,0)), 2) As SalesJV_NetTotal2  from temp_salesjv	where SalesJV_Id =  " .$SId;

	   $resultextractbases=mysql_query($queryExtractBases,$connection) or die(mysql_error());
	   while($rows=mysql_fetch_array($resultextractbases)){
		extract($rows);
	   }
	
 
		 
		/*
	  $queryExtractBases=" select  Round((ifNull(SalesJV_Total,0) + IfNull(SalesJV_VAT,0) - IfNull(SalesJV_DiscountAmount,0)), 2) As SalesJV_NetTotal , Round((ifNull(SalesJV_TotalBase2,0) + IfNull(SalesJV_VatBase2,0) - IfNull(SalesJV_DiscountAmount2,0)), 2) As SalesJV_NetTotal2  from temp_salesjv	where SalesJV_Id = " .$SId;
*/
   $resultextractbases=mysql_query($queryExtractBases,$connection) or die(mysql_error());
   while($rows=mysql_fetch_array($resultextractbases)){
	extract($rows);
   }
 
		$val1 =  round($SalesJV_NetTotal,$DecimalBase);
		$val2 =  round($SalesJV_NetTotal2,$DecimalBase2);
		
		//;
 	
		$val1 = "Total: " .number_format($val1 . "" ,$DecimalBase)  .$base1;
		$val2 = "Total: " .number_format($val2 . "" ,$DecimalBase2) .$base2;
		
		
	} 
	else {
		$val1 = '';
		$val2 = '';
	}
	echo "[BRK]";
	echo  $val1;// data 3

	echo "[BRK]";

	echo $val2;
    echo "[BRK]";	//data 4
	      //_rodolphe   
exit;	
} 

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

	$AllowDelete = 0;
	$message  = '';

	//Check User Access For Date Modification/ Lock Period
	$MainCompanyName=explode('_',$_SESSION['dbName']);

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

	$sub_result = mysql_query($sub_query,$connection) or die(mysql_error());
	$rowsperiod = mysql_num_rows($sub_result);

	while($sub_rows=mysql_fetch_array($sub_result)){
		extract($sub_rows);
	}	
	if ($rowsperiod > 0 && $AllowLockedPeriod == 1) {
		$query = "SELECT date_format(SalesJV_Date,'%d/%m/%Y') FROM SalesJV WHERE SalesJV_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.';
	}

	//Check If SalesJV Is Posted
	$query = "SELECT ifNull(SalesJV_Posted,0) As SalesJVPosted FROM SalesJV WHERE SalesJV_ID = ".$SId;
	$result = selectData($connection, $query);
	$SalesJVPosted = $result[0];

	if ($SalesJVPosted == 1 ){
		$message  = 'Delete not allowed, Transaction posted.';
		$AllowDelete = 1;
	}

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

		$sub_query = " Select Journal_Id From SalesJV Where SalesJV_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 SalesJVDt For Selected Record
		$query = " DELETE FROM SalesJVDt ".
				 " WHERE SalesJV_ID = ".$SId;

		if (updateData($connection, $query, true)) {
			
			$query = " DELETE FROM salesJvRemarkdt ".
					 " WHERE salesJv_id = ".$SId;

			if (!updateData($connection, $query, true))		 
				$message  = mysql_error();
			
			// Delete From SalesJV For Selected Record
			$query = " DELETE FROM SalesJV ".
					 " WHERE SalesJV_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_SalesJVDt For Selected Record
	$query = " DELETE FROM Temp_SalesJVDt ".
			 " WHERE SalesJV_ID = ".$SId;

	if (updateData($connection, $query, true)) {
		
		$query = " DELETE FROM temp_salesJvRemarkdt ".
				 " WHERE salesJv_id = ".$SId;
				 //" And Logged_Code = '".$_SESSION['useraccount']."' ";

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

		if (!updateData($connection, $query, true))		 
			$message  = mysql_error(); 
	}
	else
		$message  = mysql_error(); 	

}

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

	$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO Temp_SalesJV (SalesJV_ID, SalesJV_Reference, SalesJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesJV_Posted, SalesJV_Edit, Sales_Mode, SalesJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, ".
			 " SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, SalesJV_VAT, SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_DiscountPer, ".
			 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, SalesJV_VatAccount, SalesJV_DiscountAccount, SalesJv_ManualNo, ".
			 " SalesJv_VatPrefix, User_Account, Logged_Code  , SalesJv_CashAmmount1,SalesJv_BankAmmount1, SalesJv_CreditCardAmmount1 , SalesJv_CashAmmount2 , ".
			 " SalesJv_BankAmmount2,SalesJv_CreditCardAmmount2 , SalesJV_BankAccount1,SalesJV_BankAccount2,SalesJV_CashAccount1,SalesJV_CashAccount2,SalesJV_CreditCardAccount1,".
			 " SalesJV_CreditCardAccount2, SalesJV_PaymentTerms,salejv_gitledger,salejv_expledger,salejv_expamount,salejv_expjournal) ".
			 " SELECT SalesJV_ID, SalesJV_Reference, SalesJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesJV_Posted, SalesJV_Edit, Sales_Mode, SalesJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, ".
			 " SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, SalesJV_VAT, SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_DiscountPer, ".
			 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, SalesJV_VatAccount, SalesJV_DiscountAccount, SalesJv_ManualNo, ".
			 " SalesJv_VatPrefix, User_Account, '".$_SESSION['useraccount']."' ,  SalesJv_CashAmmount1,SalesJv_BankAmmount1, SalesJv_CreditCardAmmount1 , ".
			 " SalesJv_CashAmmount2 , SalesJv_BankAmmount2,SalesJv_CreditCardAmmount2, SalesJV_BankAccount1,SalesJV_BankAccount2,SalesJV_CashAccount1,SalesJV_CashAccount2,SalesJV_CreditCardAccount1, ".
			 " SalesJV_CreditCardAccount2, SalesJV_PaymentTerms,salejv_gitledger,salejv_expledger,salejv_expamount,salejv_expjournal ".
			 " FROM SalesJV ".
			 " WHERE SalesJV_ID = ".$SId;

	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}  

	if ($ErrorExists == 0) {
		$query = " INSERT INTO temp_salesJvRemarkdt (salesJvRemarkdt_id, salesJv_id, Remarkdt_id, salesJvRemarkdt_chk) ".
				 " SELECT salesJvRemarkdt_id, salesJv_id, Remarkdt_id, salesJvRemarkdt_chk ".
				 " FROM salesJvRemarkdt ".
				 " WHERE salesJv_id = ".$SId;
		if (!updateData($connection, $query, true))
			$message  = mysql_error(); 	
		
		//echo $message.$query; exit;				 
		$query = " INSERT INTO Temp_SalesJVDt (SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesJVDt_Description, SalesJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, ".
				 " SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDTCalcTotal, SalesJVDt_VAT, Journal_Type, SalesJvDt_ManualNo, cost, costbase1, costbase2, costaccount, supplieraccount, ".
				 " RelatedDt_ID, Logged_Code ,ledger_numbercredit ,ledger_numberdebit,expencesamt )  ".
				 " SELECT SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesJVDt_Description, SalesJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, ".
				 " SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDTCalcTotal, SalesJVDt_VAT, Journal_Type, SalesJvDt_ManualNo, cost, costbase1, costbase2, costaccount, supplieraccount, ".
				 " RelatedDt_ID, '".$_SESSION['useraccount']."'  ,ledger_numbercredit ,ledger_numberdebit,expencesamt  ".
				 " FROM SalesJVDt ".
				 " WHERE SalesJV_ID = ".$SId;

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

	}
}

else if($mainmode == "loadSorderjv" && $SelectedRec != ''){
	$ErrorExists = 0;
	$message  = '';
	
	fbegin();	
	$vSalesJVId = get_nextsequence('Salesjv_id','',$connection);	
	fcommit();
	
	fbegin();
	$query = "INSERT INTO temp_salesjv (SalesJV_Id, SalesJV_Reference, SalesJV_Date, Client_Code, Currency_Code, Project_Code, Costcenter_Code, JournalDt_ValueDate, journal_type, salesjv_edit, salesjv_posted, 
			SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, salesjv_discountamount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, Sales_Remark, Salesman_Code, sales_mode, User_Account, 
			SalesJV_VAT, SalesJV_VatBase1, SalesJV_VatBase2, salesjv_vatcheck, salesjv_taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, salesjv_nonetaxable, SalesJV_NoneTaxableBase1, 
			SalesJV_NoneTaxableBase2, salesjv_paid, SalesJv_amountpaid, SalesJv_amountpaidbase1, SalesJv_amountpaidbase2, SalesJv_unpaidamnt, SalesJv_unpaidamntbase1, SalesJv_unpaidamntbase2, 
			SalesJV_JvRef, SalesJV_Goods, SalesJV_Declaration, SalesJV_Packs, SalesJV_Weight, SalesJV_ValueGoods, Salesjv_paymentMode, SalesJV_Bank, SalesJV_chkdate, SalesJV_CheckNo, Table_id, 
			salesjv_type, SalesJV_PaidDate, area_code, SalesJV_BelongsToGroup, SendReceive_Reference, salesjv_downpayment, SalesJV_DownPaymentBase1, SalesJV_DownPaymentBase2, SalesJV_VatAccount, 
			SalesJV_SettledAmount, SalesJV_SettledAmount1, SalesJV_SettledAmount2, generatedinvoice_ref, salesjv_DiscountPer, Synchronized, SalesJV_Maxdiscountper, SalesJV_DiscountAccount, 
			salesJV_formalityName, salesJV_blnno, salesJV_PortOfLoading, salesJV_PortOfDischarge, salesJV_VesselName, salesJV_ContainerNo, salesJV_Bulletin, salesJV_Commodity, salesJV_ShippingLine, 
			salesJV_CustomReceipt, salesJV_CustomDate, salesJV_Freight, salesJV_ImportExport, salesJV_PakingOfGrossWeight, salesJV_ValueOfGoods, salesjv_Reservation, salesjv_CheckIn, salesjv_CheckOut, 
			salesjv_RoomType, salesJV_formalitydate, salesJV_formalityvalue, BRANCH_CODE, SalesJv_ManualNo, Logged_Code, SalesJv_VatPrefix, SalesJV_PaymentTerms)
			SELECT $vSalesJVId, Null, now(), Client_Code, Currency_Code, Project_Code, Costcenter_Code, JournalDt_ValueDate, journal_type, salesOrderjv_edit, salesOrderjv_posted,
			SalesOrderJV_Total, SalesOrderJV_TotalBase1, SalesOrderJV_TotalBase2, salesOrderjv_discountamount, SalesOrderJV_DiscountAmount1, SalesOrderJV_DiscountAmount2,Sales_Remark, Salesman_Code, sales_mode, '".$_SESSION['useraccount']."',
			SalesOrderJV_VAT, SalesOrderJV_VatBase1, SalesOrderJV_VatBase2, salesOrderjv_vatcheck, salesOrderjv_taxable, SalesOrderJV_TaxableBase1, SalesOrderJV_TaxableBase2, salesOrderjv_nonetaxable, SalesOrderJV_NoneTaxableBase1, 
			SalesOrderJV_NoneTaxableBase2, salesOrderjv_paid, SalesOrderJv_amountpaid, SalesOrderJv_amountpaidbase1, SalesOrderJv_amountpaidbase2, SalesOrderJv_unpaidamnt, SalesOrderJv_unpaidamntbase1, SalesOrderJv_unpaidamntbase2, 
			SalesOrderJV_JvRef, SalesOrderJV_Goods, SalesOrderJV_Declaration, SalesOrderJV_Packs, SalesOrderJV_Weight, SalesOrderJV_ValueGoods, SalesOrderjv_paymentMode, SalesOrderJV_Bank, SalesOrderJV_chkdate, SalesOrderJV_CheckNo, Table_id, 
			salesOrderJV_type, SalesOrderJV_PaidDate, area_code, SalesOrderJV_BelongsToGroup, SendReceive_Reference, salesOrderjv_downpayment, SalesOrderJV_DownPaymentBase1, SalesOrderJV_DownPaymentBase2, SalesOrderJV_VatAccount, 
			SalesOrderJV_SettledAmount, SalesOrderJV_SettledAmount1, SalesOrderJV_SettledAmount2, generatedinvoice_ref, salesOrderjv_DiscountPer, Synchronized, SalesOrderJV_Maxdiscountper, SalesOrderJV_DiscountAccount, 
			salesOrderJV_formalityName, salesOrderJV_blnno, salesOrderJV_PortOfLoading, salesOrderJV_PortOfDischarge, salesOrderJV_VesselName, salesOrderJV_ContainerNo, salesOrderJV_Bulletin, salesOrderJV_Commodity, salesOrderJV_ShippingLine, 
			salesOrderJV_CustomReceipt, salesOrderJV_CustomDate, salesOrderJV_Freight, salesOrderJV_ImportExport, salesOrderJV_PakingOfGrossWeight, salesOrderJV_ValueOfGoods, salesOrderjv_Reservation, salesOrderjv_CheckIn, salesOrderjv_CheckOut, 
			salesOrderjv_RoomType, salesOrderJV_formalitydate, salesOrderJV_formalityvalue, BRANCH_CODE, SalesOrderJv_ManualNo, '".$_SESSION['useraccount']."', SalesOrderJv_VatPrefix, salesOrderjv_PaymentTerms
			FROM salesorderjv
			WHERE SalesOrderJV_Id = $SelectedRec ";
	//echo $query;exit;
	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error($connection); 	
		frollback();
	} else {
		fcommit();
		$SId = $vSalesJVId;
	}
	
	if ($ErrorExists == 0) {
		$queryRemark = "INSERT INTO temp_salesJvRemarkdt (salesJvRemarkdt_id, salesJv_id, Remarkdt_id, salesJvRemarkdt_chk) 
						SELECT sorderJvRemarkdt_id, sorderJv_id, Remarkdt_id, sorderJvRemarkdt_chk
						FROM sorderJvRemarkdt
						WHERE sorderJv_id = $SelectedRec ";
		$results = mysql_query($queryRemark,$connection);				
						
		$querys = " select SalesOrderJVDt_Id, SalesOrderJV_Id, Client_Code, Currency_Code, Ledger_Number, SalesOrderJVDt_Description, Project_Code, Costcenter_Code, salesOrderjvdt_quantity, salesOrderjvdt_price, ".
				  " SalesOrderJVDt_PriceBase1, SalesOrderJVDt_PriceBase2, salesOrderjvdt_DiscountPer, SalesOrderJVDt_DiscountAmount, SalesOrderJVDt_DiscountAmount1, SalesOrderJVDt_DiscountAmount2, Warehouse_Code, ".
				  " SalesOrderJVDt_ExpireDate, SalesOrderJVDt_Posted, journal_type, SalesOrderJVDt_VAT, SalesOrderJvDt_Description2, Clientip_id, Salesman_Code, Area_code, Synchronized, SalesOrderJVDTCalcTotal, ".
				  " salesOrderjvdt_tax, salesOrderjvdt_taxbase1, salesOrderjvdt_taxbase2, SalesOrderJvDt_ManualNo ".
				  " from salesorderjvdt ".
				  " where SalesOrderJV_Id = $SelectedRec"; //echo $querys."<br>";
		$results = mysql_query($querys,$connection);
		while($rows = mysql_fetch_array($results)){	
			extract($rows);
			
			$querydate = "select SalesJV_Date from temp_salesjv where SalesJV_Id = $vSalesJVId";
			$resdate = mysql_query($querydate, $connection);
			$rowdate = mysql_fetch_row($resdate);
			$SalesJV_Date = $rowdate[0];
			
			fbegin();
				$vSalesJVDtId = get_nextsequence('Salesjvdt_id','',$connection);	
			fcommit();
			
			fbegin();
			$query = " insert into temp_salesjvdt (SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Client_Code, Currency_Code, Ledger_Number, SalesJVDt_Description, Project_Code, Costcenter_Code, ".
					 " salesjvdt_quantity, salesjvdt_price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, salesjvdt_DiscountPer, SalesJVDt_DiscountAmount, SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, ".
					 " Warehouse_Code, SalesJVDt_ExpireDate, SalesJVDt_Posted, journal_type, SalesJVDt_VAT, SalesJvDt_Description2, Clientip_id, Salesman_Code, Area_code, Synchronized, SalesJVDTCalcTotal, ".
					 " salesjvdt_tax, salesjvdt_taxbase1, salesjvdt_taxbase2, SalesJvDt_ManualNo, Logged_Code,  RelatedDt_ID)".
					 " values('$vSalesJVDtId', '$vSalesJVId', '$SalesJV_Date', ".GetSQLValueString($Client_Code,'text').", ".GetSQLValueString($Currency_Code,'text').", ".GetSQLValueString($Ledger_Number,'text').", ".
					 " ".GetSQLValueString($SalesOrderJVDt_Description,'text').", ".GetSQLValueString($Project_Code,'text').", ".GetSQLValueString($Costcenter_Code,'text').", ".GetSQLValueString($salesOrderjvdt_quantity,'double').", ".	
					 " ".GetSQLValueString($salesOrderjvdt_price,'double').", ".GetSQLValueString($SalesOrderJVDt_PriceBase1,'double').", ".GetSQLValueString($SalesOrderJVDt_PriceBase2,'double').", ".
					 " ".GetSQLValueString($salesOrderjvdt_DiscountPer,'double').", ".GetSQLValueString($SalesOrderJVDt_DiscountAmount,'double').", ".GetSQLValueString($SalesOrderJVDt_DiscountAmount1,'double').", ".
					 " ".GetSQLValueString($SalesOrderJVDt_DiscountAmount2,'double').", ".GetSQLValueString($Warehouse_Code,'text').", ".GetSQLValueString($SalesOrderJVDt_ExpireDate,'text').", ".
					 " ".GetSQLValueString($SalesOrderJVDt_Posted,'int').", ".GetSQLValueString($journal_type,'text').", ".GetSQLValueString($SalesOrderJVDt_VAT,'text').", ".
					 " ".GetSQLValueString($SalesOrderJvDt_Description2,'text').", ".GetSQLValueString($Clientip_id,'double').", ".GetSQLValueString($Salesman_Code,'text').", ".GetSQLValueString($Area_code,'text').",".
					 " ".GetSQLValueString($Synchronized,'int').", ".GetSQLValueString($SalesOrderJVDTCalcTotal,'double').", ".GetSQLValueString($salesOrderjvdt_tax,'double').", ".GetSQLValueString($salesOrderjvdt_taxbase1,'double').",".
					 " ".GetSQLValueString($salesOrderjvdt_taxbase2,'double').", ".GetSQLValueString($SalesOrderJvDt_ManualNo,'text').", '".$_SESSION['useraccount']."', '$SalesOrderJVDt_Id' ".
					 ")";
					 
			//echo $query;exit;
			if (!updateData($connection, $query, true)) {
				$ErrorExists = 1;
				$message  = mysql_error($connection); 	
				frollback();
			} else {
				fcommit();
			}
		}
		
		
	}
}

else if($mainmode == "postsalesjv") {
	$serverName = "93.186.115.223,1433";
	$connectionInfo = array("Database"=>"PerpaxTravelTrainingBase", "UID"=>"utp", "PWD"=>"ptp");
	$conn = sqlsrv_connect($serverName, $connectionInfo);	
	$query="select PerPaxSyncDataItemID,InvoiceDtTm, PartnerSalesChannel,InvoiceNumber,DocketNo,InvoiceDtTm,CreatedDtTm,Service,BillingCustomerName,PassengerName,Total,SupplierCurrency, 
			Route, TravelDtTm, CreatedBy,TRNumber from tabPerPaxSyncDataItems   ";
	$result=sqlsrv_query($conn,$query) or die(sqlsrv_errors());	
	extract($rows);

	$manualnbr = $InvoiceNumber."-".$DocketNo;
	$query_check = "select 1 from salesjv where SalesJv_ManualNo <> '$manualnbr'";
	$res_check 	 = mysql_query($query_check,$connection);
	$numcheck 	 = mysql_num_rows($res_check);

	$checkexists = 1;		
	$temp = explode("--",$TRNumber);
	$query_prjct = "select 1 from projects where project_code = '$temp[0]'";
	$res_prjct   = mysql_query($query_prjct,$connection);
	$num_prjct	 = mysql_num_rows($res_prjct);
	if($num_prjct == 0) $checkexists = 0;

	$query_cst = "select 1 from costcent where Costcent_name = '$PartnerSalesChannel'";
	$res_cst   = mysql_query($query_cst,$connection);
	$num_cst	 = mysql_num_rows($res_cst);
	if($num_cst == 0) $checkexists = 0;

	$query_client = "select 1 from clients where Ledger_name = '$BillingCustomerName'";
	$res_client   = mysql_query($query_client,$connection);
	$num_client	 = mysql_num_rows($res_client);
	if($num_client == 0) $checkexists = 0;

	$query_salesmen = "select 1 from salesmen where Ledger_name = '$CreatedBy'";
	$res_salesmen   = mysql_query($query_salesmen,$connection);
	$num_salesmen	 = mysql_num_rows($num_salesmen);
	if($num_salesmen == 0) $checkexists = 0;

  if($numcheck > 0 && $checkexists == 1){	

	$InvoiceDtTm = $InvoiceDtTm->format('Y-m-d H:i:s');
	$TravelDtTm	 = $TravelDtTm->format('Y-m-d H:i:s');

	$Totalbase1 = ConvertCurrency($SupplierCurrency, $base1, $InvoiceDtTm, $Total, $connection);;
	$Totalbase2 = ConvertCurrency($SupplierCurrency, $base2, $InvoiceDtTm, $Total, $connection);;
	fbegin();	
	$vSalesJVId = get_nextsequence('SalesJV_Id','',$connection);	
	fcommit();
	fbegin();

	$query = " INSERT INTO SalesJV (SalesJV_ID, SalesJV_Reference, SalesJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesJV_Posted, SalesJV_Edit, Sales_Mode, SalesJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, ".
			 " SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, SalesJV_VAT, SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_DiscountPer, ".
			 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, SalesJV_VatAccount, SalesJV_DiscountAccount, SalesJv_ManualNo, ".
			 " User_Account, Logged_Code ) ".
			 " select ".$vSalesJVId.", Null, '".$InvoiceDtTm."', '".$TravelDtTm."', clients.Ledger_number , ".
			 "          salesmen.Ledger_number, '".ereg_replace("'", "\'", trim($PassengerName))."', '".$SupplierCurrency."', Project_Code, Costcent_code, ".
			 "          0, 0, 0, $FI_BelongsToGrp, 'JS', Null, $Total, $Totalbase1, $Totalbase2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, ".
			 "          '".ereg_replace("'", "\'", trim($manualnbr))."', '".$_SESSION['useraccount']."', '".$_SESSION['useraccount']."' ".
			 " left join clients on clients.Ledger_name = '$BillingCustomerName'".
			 " left join costcent on costcent.Costcent_name = '$PartnerSalesChannel'".
			 " left join project on project.Project_Name = '$temp[0]'".
			 " left join salesmen on salesmen.Ledger_name = '$CreatedBy' ";

	$result=mysql_query($query,$connection);
	//echo $query."<br>";exit;	

	if ($result){
		$SId = $vSalesJVId;
		fcommit();
	}else{
		$SId = "";
		$ErrorExists = 1;
		$message  = mysql_error(); 
		frollback();
	}
	if($SId != ''){
		fbegin();
		$vSalesJVDtId = get_nextsequence('SalesJVDt_Id','',$connection);	
		fcommit();

		fbegin();
		$query = " INSERT INTO SalesJVDt (SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesJVDt_Description, SalesJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, ".
				 " SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDTCalcTotal, SalesJVDt_VAT, Journal_Type, SalesJvDt_ManualNo, Logged_Code )  ".
				 "  ".$vSalesJVDtId.", ".$SId.", '".$InvoiceDtTm."', '".$SupplierCurrency."', clients.Ledger_number, ".
				 "  salesmen.Ledger_number, clients.Ledger_number, '".ereg_replace("'", "\'", trim($Route))."', ".
				 "          '".ereg_replace("'", "\'", trim($txtDescription2))."', Project_Code, Costcent_code, 1, $Total, $Totalbase1, $Totalbase2, 0, ".
				 "          0, 0, 0, $Total, 0, 'JS', Null, '".$_SESSION['useraccount']."'	 ".
				 " left join clients on clients.Ledger_name = '$BillingCustomerName'".
				 " left join costcent on costcent.Costcent_name = '$PartnerSalesChannel'".
				 " left join project on project.Project_Name = '$temp[0]'".
				 " left join salesmen on salesmen.Ledger_name = '$CreatedBy' ";

		//echo $query."<br>";exit;				
		$result=mysql_query($query,$connection);

		if ($result){
			fcommit();
		} else{
			$txtDtId = "";
			$ErrorExists = 1;
			$message  = mysql_error(); 
			frollback();
		}

	}

  }
}
//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;

	echo $disableenable;

	if (empty($txtCostCentCode))	$CostCentCode = 'Null';
	else		$CostCentCode = "'".$txtCostCentCode."'";

	if (empty($txtProjectCode))		$ProjectCode = 'Null';
	else		$ProjectCode = "'".$txtProjectCode."'";      

	if (empty($txtSalesmanCode))	$SalesmanCode = 'Null';
	else	$SalesmanCode = "'".ereg_replace("'", "\'", trim($txtSalesmanCode))."'";		

	$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 Client, Salesman, Project and Costcenter Codes Before Insert
	if ($txtCostCentCode != '') {
		$sub_query = " Select Count(Costcent_code) From Costcent ".
					 " Where Costcent_code = '".$txtCostCentCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	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 ($txtClientCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Clients ".
					 " Where Ledger_Number = '".$txtClientCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}
	if ($txtSalesmanCode != '') {
		$sub_query = " Select Count(Ledger_Number) From Salesmen ".
					 " Where Ledger_Number = '".$txtSalesmanCode."'";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) $ErrorExists = 1;
	}	

	//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($salesjv_paymentmode == 1 && $ErrorExists == 0)
	{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$totalPaymB1 = round($cashcurrency1 + $bankcurrency1 + $creditcardcurrency1,$DecimalBase);
		$totalPaymB2 = round($cashcurrency2 + $bankcurrency2 + $creditcardcurrency2,$DecimalBase2);

/* $queryc="select Currency_Code , SalesJV_TotalBase1, Round((ifNull(SalesJV_Total,0) + IfNull(SalesJV_VAT,0) - IfNull(SalesJV_DiscountAmount,0)), 2) As SalesJV_NetTotal  from Temp_SalesJV  Where SalesJV_ID = " .$SId; */

$queryc="select Currency_Code , SalesJV_TotalBase1, Round((ifNull(SalesJV_Totalbase1,0) + IfNull(salesjv_vatbase1,0) - IfNull(SalesJV_DiscountAmount1,0)), 2) As SalesJV_NetTotal  from Temp_SalesJV  Where SalesJV_ID = " .$SId;


//trigger_error($queryc);
$queryresultc=mysql_query($queryc,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($queryresultc)){
extract($rows);
}

	$totalPaymB1    = ConvertCurrency($cashcur, $base1,  insertMySQLDate($txtDate), $totalPaymB1 , $connection);
    $totalPaymB2    = ConvertCurrency($cashcur2, $base1, insertMySQLDate($txtDate),  $totalPaymB2 , $connection);

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$totalPaymB1 = round($totalPaymB1,$DecimalBase);
		$totalPaymB2 = round($totalPaymB2,$DecimalBase);	
		
		
 



/* Round((ifNull(SalesJV_Total,0) + IfNull(SalesJV_VAT,0) - IfNull(SalesJV_DiscountAmount,0)), 2) As SalesJV_NetTotal */
		if(abs($totalPaymB1+$totalPaymB2-$SalesJV_NetTotal)>$TipsMaxBase1)
		{
		// echo ($totalPaymB1+$totalPaymB2) ;echo " csdfdsfds       ";exit;	
			// update only payment mode 

			$sub_query = " UPDATE Temp_SalesJV SET ".

					  " SalesJv_CashAmmount1="        . GetSQLValueString($cashcurrency1,"double") ."".
					  ",SalesJv_BankAmmount1="        .GetSQLValueString($bankcurrency1,"double")."".
					  ",SalesJv_CreditCardAmmount1="  .GetSQLValueString($creditcardcurrency1,"double")."".
					  ",SalesJv_CashAmmount2="        . GetSQLValueString($cashcurrency2,"double")."".
					  ",SalesJv_BankAmmount2="        . GetSQLValueString($bankcurrency2,"double")."".
					  ",SalesJv_CreditCardAmmount2="  .GetSQLValueString($creditcardcurrency2,"double")."". 

					  " WHERE SalesJV_ID = $SId ";
		$sub_query = mysql_query($sub_query,$connection) or die(mysql_error());
			//
		$SaveAllowed = 0;   $ErrorExists = 1; $totalcurracurrb =   round($totalPaymB1 + $totalPaymB2,$DecimalBase);
/* 		$message="Invoice net total not equal to payment mode total - Net Total :  $SalesJV_NetTotal $base1 Payment Total $totalcurracurrb $base1  " ; */

		$message = "Invoice net total not equal to payment mode total Net Total :" .number_format($SalesJV_NetTotal . "" ,$DecimalBase1) ." " .$base1;
		$message = $message. " Payment Total :" .number_format($totalcurracurrb ."",$DecimalBase1) ." " .$base1;
		
		}

	}	

	if ($SaveAllowed == 1 && $ErrorExists == 0 && $ExceedLockPeriod == 0) {

		$sub_query = " Select SalesJVDt_Id, Currency_Code, ifNull(SalesJVDt_Price,0), ifNull(SalesJVDt_PriceBase1,0), ifNull(SalesJVDt_PriceBase2,0), ".
					 " ifNull(SalesJVDt_DiscountAmount,0), ifNull(SalesJVDt_DiscountAmount1,0), ifNull(SalesJVDt_DiscountAmount2,0), ifNull(SalesJVDTCalcTotal,0) ".
					 " From Temp_SalesJVDt ".
					 " Where SalesJV_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_SalesJVDt SET  ".
							  " SalesJVDt_Price = $vDtPrice, SalesJVDt_PriceBase1 = $vDtPriceBase1, SalesJVDt_PriceBase2 = $vDtPriceBase2, ".
							  " SalesJVDt_DiscountAmount = $vDtDiscAmt, SalesJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesJVDt_DiscountAmount2 = $vDtDiscAmtBase2, ".
							  " SalesJVDTCalcTotal = $vDtTotal ".
							  " Where SalesJVDt_Id = ".$sub_row[0];

							//////  $sub_query1 = "";

				//echo $sub_query1; exit;	
				if (!updateData($connection, $sub_query1, true))		 
					$message  = mysql_error(); 

			}
		}

		$sub_query2 = " UPDATE Temp_SalesJVDt SET ".
					  " Currency_Code = '".$txtCurr."', SalesJV_Date = '".insertMySQLDate($txtDate)."', ".
					  " Client_Code = '".ereg_replace("'", "\'", trim($txtClientCode))."' ";

		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 SalesJV_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(SalesJVDt_Quantity,0)*ifNull(SalesJVDt_Price,0))-((ifNull(SalesJVDt_Quantity,0)*ifNull(SalesJVDt_Price,0)*ifNull(SalesJVDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_SalesJVDt ".
					  " Where SalesJV_Id = ".$SId;
		$sub_result3 = selectData($connection, $sub_query3);
		$vTotal   = $sub_result3[0];	
		$vDisAmt  = $txtDiscountAmt;

		$sub_query4 = " Select SalesJVDt_Id,  ".
					  " ((ifNull(SalesJVDt_Quantity,0)*ifNull(SalesJVDt_Price,0))-((ifNull(SalesJVDt_Quantity,0)*ifNull(SalesJVDt_Price,0)*ifNull(SalesJVDt_DiscountPer,0))/100)) As Total ".
					  " From Temp_SalesJVDt As SalesJVDt  ".
					  " Where SalesJVDt.SalesJV_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_SalesJVDt SET ".
						 " SalesJVDt_DiscountAmount = $vDtDiscAmt, SalesJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesJVDt_DiscountAmount2 = $vDtDiscAmtBase2  ";

						  $queryupd =  $queryupd . " , SalesJv_CashAmmount1 = $cashcurrency1 ,";
			            $queryupd =  $queryupd . " , SalesJv_BankAmmount1 = $bankcurrency1 ,";
						            $queryupd =  $queryupd . " , SalesJv_CreditCardAmmount1 = $cardcurrency1 ,";
									            $queryupd =  $queryupd . " , SalesJv_CashAmmount2 = $cashcurrency2 ,";
												            $queryupd =  $queryupd . " , SalesJv_BankAmmount2 = $bankcurrency2 ,";
															            $queryupd =  $queryupd . " , SalesJv_CreditCardAmmount2 = $cardcurrency2  ";

						 $queryupd = $queryup." Where SalesJVDt_Id = ".$vDtId;
						 //" And Logged_Code = '".$PLoggedCode."' "; */

						 $queryupd =  " UPDATE Temp_SalesJVDt SET ".
						 " SalesJVDt_DiscountAmount = $vDtDiscAmt, SalesJVDt_DiscountAmount1 = $vDtDiscAmtBase1, SalesJVDt_DiscountAmount2 = $vDtDiscAmtBase2  ".
						 " Where SalesJVDt_Id = ".$vDtId;
						 //" And Logged_Code = '".$PLoggedCode."' ";
			//echo $queryupd; exit;
			if (!updateData($connection, $queryupd, true))
				$error  = mysql_error(); 

		}

		//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;

		$Acc_Query = " SELECT VATAccountNonStock, DiscountAccount FROM salessetup ";
		$Acc_Result = selectData($connection, $Acc_Query);

		//$vVatAccount = $Acc_Result[0];
		if (empty($txtVatPrefix)) $vVatAccount = $Acc_Result[0];
		else $vVatAccount = $txtVatPrefix;

		$sub_queryVat = " SELECT GetVATAccount('".$txtClientCode."','".$vVatAccount."') from dual ";
		$sub_resultVat = selectData($connection, $sub_queryVat);
		if ($sub_resultVat[0] != '') $vVatAccount = $sub_resultVat[0];


		$queryexp = "select salejv_gitledger,salejv_expledger,salejv_expamount,Project_Code from temp_salesjv  WHERE SalesJV_ID = $SId ";
		$resultexp = mysql_query($queryexp,$connection);
		$rowexp = mysql_fetch_array($resultexp);

		$oldgit = $rowexp[0];
		$oldexp = $rowexp[1];
		$oldexpamt = $rowexp[2];
		$oldproj = $rowexp[3];
		/////update
		

		$sub_query5 = " UPDATE Temp_SalesJV SET ".
					  " SalesJV_Date = '".insertMySQLDate($txtDate)."' , SalesJv_ManualNo = '".ereg_replace("'", "\'", trim($txtManualNo))."', ".
					  " JournalDt_ValueDate = '".insertMySQLDate($txtMaturityDate)."' , ".
					  " Sales_Remark = '".ereg_replace("'", "\'", trim($txtRemark))."', Client_Code = '".ereg_replace("'", "\'", trim($txtClientCode))."', ".
					  " Salesman_Code = $SalesmanCode, Currency_Code = '".$txtCurr."', Project_Code = $ProjectCode, Costcenter_code = $CostCentCode,  ".
					  " SalesJv_VatPrefix = '".trim($txtVatPrefix)."', SalesJV_VatAccount =  '".$vVatAccount."' ".
					  ",SalesJv_CashAmmount1=" . GetSQLValueString($cashcurrency1,"double") ."".
					  ",SalesJv_BankAmmount1=" .GetSQLValueString($bankcurrency1,"double")."".
					  ",SalesJv_CreditCardAmmount1=" .GetSQLValueString($creditcardcurrency1,"double")."".
					  ",SalesJv_CashAmmount2=" . GetSQLValueString($cashcurrency2,"double")."".
					  ",SalesJv_BankAmmount2=" . GetSQLValueString($bankcurrency2,"double")."".
					  ",SalesJv_CreditCardAmmount2=" .GetSQLValueString($creditcardcurrency2,"double")." ". 
					  ",SalesJV_PaymentTerms = " .GetSQLValueString($txtterms,'text') ."  ".
					  ",salejv_gitledger = " .GetSQLValueString($txtGitLedger,'text') ."  ".
					  ",salejv_expledger = " .GetSQLValueString($txtExpLedger,'text') ."  ".
					  ",salejv_expamount = " .GetSQLValueString($expamt,'text') ."  ".
					  " WHERE SalesJV_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 SalesJV WHERE SalesJV_ID = $SId ";
			$result  = selectData($connection, $query);
			$vOldProjCode  	  = $result[0];
			$vOldCostCentCode = $result[1];

			$query = "Select Count(*) From Temp_SalesJV where SalesJV_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 SalesJvExist from salesjv where SalesJv_Id = '$SId'";
					$result_checkDelivery = mysql_query($query_checkDelivery, $connection); 
					$row_checkDelivery    = mysql_fetch_array($result_checkDelivery);
					extract($row_checkDelivery);
					if($SalesJvExist > 0){
						$transType = "U";
					}
					else{
						$transType = "I";
					}
					$company = explode("_", $_SESSION['dbName']);
					$currCompany = strtoupper($company[0]);
					$query = " SELECT CopyData_TempSalesJV('".$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 SalesJV_Reference, Costcenter_code, Project_Code FROM SalesJV WHERE SalesJV_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];
					}
					$sendEmail = 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('SalesJV_Reference',$vProjCostCent,$connection);	
						fcommit();

						$query = " UPDATE SalesJV SET ".
								 " SalesJV_Reference = $vRef ".
								 " WHERE SalesJV_ID = $SId ";

						if (!updateData($connection, $query, true)) 
							$message  = mysql_error();
						else $sendEmail = 1;

					}	

					if ($sendEmail == 1){
						$emails = '';
						$queryEmails = "select client_email, ledger_name from clients where ledger_number = '".ereg_replace("'", "\'", trim($txtClientCode))."' ";
						$resEmails = mysql_query($queryEmails, $connection);
						$rw = mysql_fetch_row($resEmails);
						$emails 	 = $rw[0];
						$ledger_name = $rw[1];//echo$emails;exit;
						if ($emails != ''){
							$Subject="Sales JV Reference: ".$vRef." created ";
							$Body="<table><tr><td>Date : ".$txtDate."</td></tr>\n";
							$Body=$Body."<tr><td>Sales JV with Reference ".$rowbody[0]." was submitted by '".$_SESSION['username']."' ";
							$Body=$Body."</td></tr>\n";
							$Body=$Body."<tr><td>For Client ".$txtClientCode." - $ledger_name ";
							$Body=$Body."</td></tr>\n";
							$Body=$Body." </table> \n";
							$mail=sendmail($Subject,$Body,$emails,$PRqstid,$connection);	
						}						
					}
					if ($Module_PostToJournal == 1) {
						$message = Create_SalesJVJv($SId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username'], $FI_BelongsToGrp); 
					}	

					if($module_shipmentclosing==1 && ($oldgit!=$txtGitLedger || $oldexp !=$txtExpLedger || $oldexpamt != $expamt || $oldproj != $ProjectCode)){
						$message = Create_ExpencesJv($SId, $_SESSION['dbName'], $_SESSION['dbLabel'], $_SESSION['useraccount'], $_SESSION['username'], $FI_BelongsToGrp); 
					}

				} else{
					$ErrorExists = 1;
					//$message  = mysql_error(); 
					$message  = 'Error In CopyData_TempSalesJV Function.'; 
					frollback();
				}

			}

			if($config['log_file'] == 1){
						$query_insertToHistory  = "call ".$config['dbName_history'].".InsertToHistory('$transType', '$SId', '".$_SESSION['useraccount']."', now(), '".$_SESSION['dbName']."', 'salesjv', '$currCompany')";
					//echo $query_insertToHistory;exit;
					$result_insertToHistory = mysql_query($query_insertToHistory, $connection);
						}

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

	}
	else {
		if ($ErrorExists == 1)	{/*	$message = 'Save not allowed. Please check for Client/Salesman/Project/Costcenter Code.';*/}

		else if ($ExceedLockPeriod == 1)
			$message = 'Save not allowed. Exceed Lock Period.';

	}
}

	if($mainmode == "editfromreport"){
		$ErrorExists = 0;
	//Copy Data From Main Tables To Temp Tables
	$query = " INSERT INTO Temp_SalesJV (SalesJV_ID, SalesJV_Reference, SalesJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesJV_Posted, SalesJV_Edit, Sales_Mode, SalesJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, ".
			 " SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, SalesJV_VAT, SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_DiscountPer, ".
			 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, SalesJV_VatAccount, SalesJV_DiscountAccount, SalesJv_ManualNo, ".
			 " SalesJv_VatPrefix, User_Account, Logged_Code,SalesJv_CashAmmount1,SalesJv_BankAmmount1, SalesJv_CreditCardAmmount1  ,SalesJv_CashAmmount2,SalesJv_BankAmmount2, SalesJv_CreditCardAmmount2  ,SalesJV_BankAccount1,SalesJV_BankAccount2,SalesJV_CashAccount1,SalesJV_CashAccount2,SalesJV_CreditCardAccount1,SalesJV_CreditCardAccount2 ) ".
			 " SELECT SalesJV_ID, SalesJV_Reference, SalesJV_Date, JournalDt_ValueDate, Client_Code, Salesman_Code, Sales_Remark, ".
			 " Currency_Code, Project_Code, Costcenter_Code, SalesJV_Posted, SalesJV_Edit, Sales_Mode, SalesJV_BelongsToGroup, Journal_Type, Journal_Id, ".
			 " SalesJV_Taxable, SalesJV_TaxableBase1, SalesJV_TaxableBase2, SalesJV_NoneTaxable, SalesJV_NoneTaxableBase1, SalesJV_NoneTaxableBase2, ".
			 " SalesJV_Total, SalesJV_TotalBase1, SalesJV_TotalBase2, SalesJV_VAT, SalesJV_VatBase1, SalesJV_VatBase2, SalesJV_VatCheck, SalesJV_DiscountPer, ".
			 " SalesJV_DiscountAmount, SalesJV_DiscountAmount1, SalesJV_DiscountAmount2, SalesJV_VatAccount, SalesJV_DiscountAccount, SalesJv_ManualNo, ".
			 " SalesJv_VatPrefix, User_Account, '".$_SESSION['useraccount']."' ,SalesJv_CashAmmount1,SalesJv_BankAmmount1, SalesJv_CreditCardAmmount1 , SalesJv_CashAmmount2 , SalesJv_BankAmmount2,SalesJv_CreditCardAmmount2 , SalesJV_BankAccount1,SalesJV_BankAccount2,SalesJV_CashAccount1,SalesJV_CashAccount2,SalesJV_CreditCardAccount1,SalesJV_CreditCardAccount2 ".
			 " FROM SalesJV ".
			 " WHERE SalesJV_ID = ".$SId;

	if (!updateData($connection, $query, true)) {
		$ErrorExists = 1;
		$message  = mysql_error(); 	
	}  

	if ($ErrorExists == 0) {
		//echo $message.$query; exit;				 
		$query = " INSERT INTO Temp_SalesJVDt (SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesJVDt_Description, SalesJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, ".
				 " SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDTCalcTotal, SalesJVDt_VAT, Journal_Type, SalesJvDt_ManualNo, Logged_Code ,ledger_numbercredit ,ledger_numberdebit,expencesamt )  ".
				 " SELECT SalesJVDt_Id, SalesJV_Id, SalesJV_Date, Currency_Code, Client_Code, Salesman_Code, Ledger_Number, SalesJVDt_Description, SalesJVDt_Description2, ". 
				 " Project_Code, Costcenter_Code, SalesJVDt_Quantity, SalesJVDt_Price, SalesJVDt_PriceBase1, SalesJVDt_PriceBase2, SalesJVDt_DiscountPer, SalesJVDt_DiscountAmount, ".
				 " SalesJVDt_DiscountAmount1, SalesJVDt_DiscountAmount2, SalesJVDTCalcTotal, SalesJVDt_VAT, Journal_Type, SalesJvDt_ManualNo, '".$_SESSION['useraccount']."'   ,ledger_numbercredit ,ledger_numberdebit,expencesamt  ".
				 " FROM SalesJVDt ".
				 " WHERE SalesJV_ID = ".$SId;

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

	}

	header ("Location: ./Form_SalesJV.php?actionmode=&mainaction=edit&txtSalesJVId=".$SId);
	}

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

$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_SalesJV.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PrId=".$SId."&PrRef=".$vRef);
	else
		header ("Location: ./Form_SalesJV.php?actionmode=submitrecord&mainaction=".$mainmode."&message=".$message."&txtSalesJVId=".$SId);
}	
else if ($mode == "" && $mainmode == "delete" )	
	header ("Location: ./Form_SalesJVSearch.php?message=".$message);
else if ($mode == "" && $mainmode == "deletepending")	
	header ("Location: ./Form_SalesJVSearchPending.php?message=".$message);
else if ($mode == "deletedt" )		
	header ("Location: ./Form_SalesJV.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&txtSalesJVId=".$SId);	
else if ($mode == "editdt")		
	header ("Location: ./Form_SalesJVDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&message=".$message."&PId=".$SId."&PDate=".$PDate."&PDtId=".$PDtId);
else if ($mode == "" && $mainmode == "search" )		
	header ("Location: ./Form_SalesJVSearch.php?PMode=1&message=".$message);
else if ($mode == "" && $mainmode == "postsalesjv" )		
	header ("Location: ./Form_SalesJVPost.php?message=".$message);
else if ($mode == "submitrecord" ){
    header ("Location: ./Form_SalesJVDetail.php?actionmode=".$mode."&mainaction=".$mainmode."&PId=".$SId."&PDate=".$PDate."&PMaturityDate=".$PMaturityDate.	
			"&PClientCode=".$PClientCode."&PSalesmanCode=".$PSalesmanCode."&PCurr=".$PCurr."&PProjectCode=".$PProjectCode.
			"&PCostCentCode=".$PCostCentCode."&PDiscountPer=".$PDiscountPer."&PDiscountAmt=".$PDiscountAmt."&PVatChkbx=".$PVatChkbx.
			"&PManualNo=".$PManualNo."&PRemark=".$PRemark."&message=".$message);
}
else if( $mode == "" && $mainmode == "loadSorderjv" )
	header ("Location: ./Form_SalesOrderJVPost.php?PMode=1&PrId=$SId&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;

	$vDiscountPer = $PDiscPer;

	// In Case Not Save, Then Get The Vat CheckBox From Table Sorder
	if ($PMode != 'P') {
		$sub_query = "Select ifNull(SalesJV_VatCheck, 0) From Temp_SalesJV Where SalesJV_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(SalesJVDt_Quantity,0)*ifNull(SalesJVDt_Price,0))-((ifNull(SalesJVDt_Quantity,0)*ifNull(SalesJVDt_Price,0)*ifNull(SalesJVDt_DiscountPer,0))/100)) As Total, ".
				 " ifNull(SalesJVDt_VAT,0),  SalesJVDt_Quantity, ifNull(SalesJVDt_DiscountAmount,0) ".
				 " From Temp_SalesJVDt ".
				 " Where SalesJV_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);
		}	
	}

	$vNetTotal         = $vGrossTotal + $vVatAmt - $vDiscountAmt;
	$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;

	fbegin();

	$sub_query1 = " UPDATE Temp_SalesJV SET ".
				  " SalesJV_Taxable = $vTaxable, SalesJV_TaxableBase1 = $vTaxableBase1, SalesJV_TaxableBase2 = $vTaxableBase2, ".
				  " SalesJV_NoneTaxable = $vNoneTaxable, SalesJV_NoneTaxableBase1 = $vNoneTaxableBase1, SalesJV_NoneTaxableBase2 = $vNoneTaxableBase2, ".
				  " SalesJV_DiscountAmount = $vDiscountAmt, SalesJV_DiscountAmount1 = $vDiscountAmtBase1, SalesJV_DiscountAmount2 = $vDiscountAmtBase2, ".
				  " SalesJV_DiscountPer = $vDiscountPer, SalesJV_VAT = $vVatAmt, SalesJV_VatBase1 = $vVatAmtBase1, SalesJV_VatBase2 = $vVatAmtBase2, ".
				  " SalesJV_VatCheck = $PVatChk, ".
				  " SalesJV_Total = $vGrossTotal, SalesJV_TotalBase1 = $vGrossTotalBase1, SalesJV_TotalBase2 = $vGrossTotalBase2 ".
				  " WHERE SalesJV_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 sendmail($Subject,$Body,$emails,$SPreqId,$connection){
 $recipients="";
	error_reporting(E_ALL);
	error_reporting(E_ALL);

	require 'PHPMailer-master/class.phpmailer.php';

	//// Configuration
	$query_mailsetup="select hostname,mailagent,port,SenderEmail,ReceiverEmail,password from configurationemail";
	$result_mailsetup = mysql_query($query_mailsetup, $connection);
	$row_setup=mysql_fetch_row($result_mailsetup); 
	$hostname=$row_setup[0];
	$port=$row_setup[2];
	$sender=$row_setup[3];
	$pswd = $row_setup[5];

	$mail = new PHPMailer;
	$mail->IsSMTP();                                      // Set mailer to use SMTP
	$mail->Host = $hostname; 							// Specify main and backup server
	$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = $sender;                            // SMTP username
	$mail->Password = $pswd;                           // SMTP password
	$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted
	$mail->From = $sender;
	$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
	$mail->Body    =  $Body;
	$mail->IsHTML(true);                                  // Set email format to HTML
	$mail->Subject = $Subject;
	$mail->SMTPDebug = 1;
	$mail->Port = $row_setup[2]; 
	//exit;

		$emailtechs = explode(';',$emails);
		foreach($emailtechs as $emailtech){
		$mail->AddAddress($emailtech, '');  // Add a recipient
		$recipients = $recipients." $emailtech,";

		}

	if(!$mail->Send()) { 
	  $error = $mail->ErrorInfo;
		return false;	

	}

	return true;
}

function Create_ExpencesJv($PId, $DbName, $DbLabel, $UserAccount, $UserName, $BelongsToGrp) {

	include("config.inc.php");
	
	$conn = mysql_connect($config['dbServer'],$config['dbUser'],$config['dbPass'],true,65536) or die("Could not connect to DB");
	mysql_select_db($DbName, $conn) or die("Could not find DB");

	$closingquery = "call shipmentclosingfromsalesjv('".$PId."','".$DbName."','".$DbLabel."','".$UserAccount."','".$UserName."',$BelongsToGrp,@id)";
	$resultclosing = mysql_query($closingquery,$conn);

	$error = mysql_error();

	Return $error;
	

}

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

HERE;

?>