<?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);
}
set_time_limit(0);

if($txtValueDate == "") { $txtValueDate = "Null"; } else { $txtValueDate = "'".insertMySQLDate($txtValueDate)."'"; }
//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, Ledger_ValidateProject 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_AcctrxPostPV,0) As Module_AcctrxPostPV, ifNull(Module_AcctrxPostRV,0) As Module_AcctrxPostRV, ".
			 " ifNull(Module_AcctrxPostDV,0) As Module_AcctrxPostDV, ifNull(Module_AcctrxPostCV,0) As Module_AcctrxPostCV, ".
			 " ifNull(Module_AcctrxPostCT,0) As Module_AcctrxPostCT, ifNull(Module_AcctrxPost,0) As Module_AcctrxPost, ".
			 " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_UniqueManualNo,0) As Module_UniqueManualNo, ".
			 " ifNull(Module_Project,0) As Module_Project, ifNull(Module_Costcenter,0) As Module_CostCenter, ".
			 " ifNull(Module_ProjectDt,0) As Module_ProjectDt, ifNull(Module_CostCenterDt,0) As Module_CostCenterDt, ".
			 " ifNull(Module_InvoiceGrid,0) As Module_InvoiceGrid, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent ".
			 " From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}
$query_cashtypecode  = "select CashType_Code as CashTypeCode, ledgernumber as PrePaymentLedgerNumber from cashtype where Auto = '$txtCashType'";
$result_cashtypecode = mysql_query($query_cashtypecode, $connection); 
$row_cashtypecode    = mysql_fetch_array($result_cashtypecode);
extract($row_cashtypecode);

if($TransType == "PV"){
$querytrans=" select ledgernumber as PreReceipt_Acc from cashtype where Auto = '$txtCashType' ";
}
else{
	$querytrans=" select ledgernumber as PreReceipt_Acc from cashtype where journal_type = '$TransType' and cashtype_code = '$CashTypeCode' limit 1; ";
}
//echo $querytrans;exit;
$restrans=mysql_query($querytrans,$connection) or die(mysql_error());
while($rowtrans=mysql_fetch_array($restrans)){
	extract($rowtrans);
}

$vMainCompanyName=explode('_',$_SESSION['dbName']);  
$DirCompany  = $vMainCompanyName[0];
$DirYear	 = $vMainCompanyName[1]; 
	
	
$mode 		    = $_POST['mode']; if ($mode == ""){$mode = $_GET["mode"];}
$mainmode       = $_GET['mainmode'];if ($mainmode == ""){$mainmode = $_POST["mainmode"];}


if($mainmode == 'Post'){
	if (!isset($txtCurr))   $txtCurr = $base1;
	   
	if (empty($txtCashType))	$txtCashType = 'Null';
	else		$txtCashType = "'".$txtCashType."'";	
	
	$ErrorExists = 0;
	
	$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 ($fromledgernb != '') {
		$sub_query = " Select Count(Ledger_Number) From Ledger ".
					 " Where Ledger_Number = '".$fromledgernb."' and ifNull(Ledger_grpdet,0) = 0";
		$sub_result = selectData($connection, $sub_query);
		if ($sub_result[0] == 0) {
			$ErrorExists = 1;
			$message = 'Insert not allowed. Please check for Ledger Number.';
		}	
	}
	if($PreReceipt_Acc == '') {
		$ErrorExists = 1;
		$message = 'Insert not allowed. Please check for Pre-Receipt Account.';
	}
		$sub_query = " Select  ifNull(Ledger.Ledger_Activity,0) From Ledger  Where Ledger_Number = '".$PreReceipt_Acc."' ";
								  
		//echo $sub_query;
		$sub_result = selectData($connection, $sub_query);
		$LedgerActivity   = $sub_result[0];
		
	
	if ($ErrorExists == 0){
	
		$TransAmount1 = ConvertCurrency($txtCurr, $base1, GetSQLValueString(insertMySQLDate($txtDate)), $txtTotalAmount, $connection); 
		$TransAmount2 = ConvertCurrency($txtCurr, $base2, GetSQLValueString(insertMySQLDate($txtDate)), $txtTotalAmount, $connection); 	
				
		fbegin();	
		$vTransId = get_nextsequence('trans_id','',$connection);	
		fcommit();
		
		
						 
		if ($Module_ReferenceByCostcenter == 1)   $vProjCostCent = $vCostCentCode;
		else if ($Module_ReferenceByProject == 1) $vProjCostCent = $vProjectCode;
		else $vProjCostCent = '';
					
		if ($TransType == 'PV') 	 $RefField = 'Payment_RefGovernment';
		else if ($TransType == 'RV') $RefField = 'Receipt_RefGovernment';
		else if ($TransType == 'DV') $RefField = 'Dbtnote_RefGovernment';
		else if ($TransType == 'CV') $RefField = 'Crdnote_RefGovernment';
		else if ($TransType == 'CT') $RefField = 'Contra_RefGovernment';
			
		fbegin();
		$vTransRef = get_nextsequence($RefField,$vProjCostCent,$connection);	
		fcommit();
		
		fbegin();
		$query = " INSERT INTO trans (Trans_ID, Trans_Reference, Trans_Date, Trans_SysDate, Trans_Remark, Trans_Type, Trans_Representative, ".
				 " Currency_Code, Trans_CashReference, CashType_code, Trans_Posted, Journal_Id, ".
				 " Trans_AmountDb1, Trans_AmountDb2, Trans_Amountcd1, Trans_Amountcd2, Trans_BelongsToGroup, Synchronized, User_Account, AdvancePayment ) ".
				 " VALUES ( ".GetSQLValueString($vTransId,'double').", $vTransRef, ".GetSQLValueString(insertMySQLDate($txtDate),'date').", now(), ".
				 "          ".GetSQLValueString($txtRemark,'text').", ".GetSQLValueString($TransType,'text').", ".GetSQLValueString($txtRepresent,'text').", ".
				 "          ".GetSQLValueString($txtCurr,'text').", Null, '".$CashTypeCode."', 0, Null, $TransAmount1, $TransAmount2, $TransAmount1, $TransAmount2,  ".
				 "          ".GetSQLValueString($FI_BelongsToGrp,'double').", 0, ".GetSQLValueString($_SESSION['useraccount'],'text').",  0 )";
				 
		 //echo$query;exit;
		$result=mysql_query($query,$connection);
		
		
		if ($result){
			fcommit();
		} else{
			$ErrorExists = 1;
			$message  = mysql_error($connection); 
			frollback();
		}
		
	 	if ($ErrorExists == 0 && $vTransId != ''){
			fbegin();
			$vTransDtId = get_nextsequence('transdt_id','',$connection);	
			fcommit();
		    if($TransType == "RV") { $TransDt_dbcd = "C"; }
			if($TransType == "PV") { $TransDt_dbcd = "D"; }
			fbegin();
			if($config['disableprepaymentacc'] == 1 && $TransType == "PV" && $fromledgernb == ""){
				$query = " INSERT INTO transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
					 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Synchronized, User_Account)  ".
					 " VALUES ( ".$vTransDtId.", ".$vTransId.", ".GetSQLValueString($txtCurr,'text').", '".insertMySQLDate($txtDate)."', ".
					 "          '".$PrePaymentLedgerNumber."', '', Null, '".insertMySQLDate($txtDate)."' , ".
					 "          $txtTotalAmount, $TransAmount1, $TransAmount2, '$TransDt_dbcd', '+', NULL, 0, '".$_SESSION['useraccount']."') ";
			}
		    else{
			$query = " INSERT INTO transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
					 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Synchronized, User_Account)  ".
					 " VALUES ( ".$vTransDtId.", ".$vTransId.", ".GetSQLValueString($txtCurr,'text').", '".insertMySQLDate($txtDate)."', ".
					 "          '".$fromledgernb."', '".ereg_replace("'", "\'", trim($fromledgerdesc))."', Null, '".insertMySQLDate($txtDate)."' , ".
					 "          $txtTotalAmount, $TransAmount1, $TransAmount2, '$TransDt_dbcd', '+', NULL, 0, '".$_SESSION['useraccount']."') ";
			}	 
			//echo $query."<br>";exit;			
			$result=mysql_query($query,$connection);
			if($result){
				fcommit();
			} else{
				$ErrorExists = 1;
				$message  = mysql_error($connection); 
				frollback();
			}	
		} 
		if ($ErrorExists == 0 && $vTransId != ''){
			fbegin();
			$vTransDtId = get_nextsequence('transdt_id','',$connection);	
			fcommit();
		    if($TransType == "RV") { $TransDt_dbcd = "D"; }
			if($TransType == "PV") { $TransDt_dbcd = "C"; }
			fbegin();
			$query = " INSERT INTO transdt (TransDt_Id, Trans_id, Currency_Code, Trans_Date, Ledger_number, TransDt_Description, TransDt_Description2, ". 
					 " TransDt_ValueDate, Transdt_Amount, Transdt_Amount1, Transdt_Amount2, TransDt_dbcd, TransDt_Sign, TransDt_ManualNo, Synchronized, User_Account)  ".
					 " VALUES ( ".$vTransDtId.", ".$vTransId.", ".GetSQLValueString($txtCurr,'text').", '".insertMySQLDate($txtDate)."', ".
					 " '".$PreReceipt_Acc."', NULL, Null, ".$txtValueDate." , $txtTotalAmount, $TransAmount1, $TransAmount2, '$TransDt_dbcd', '+', NULL, 0, '".$_SESSION['useraccount']."') ";
				 
			//echo $query."<br>";	exit;		
			$result=mysql_query($query,$connection);
			if($result){
				fcommit();
			} else{
				$ErrorExists = 1;
				$message  = mysql_error($connection); 
				frollback();
			}	 
		
			if($ErrorExists == 0 && $vTransDtId != '' && ($chknbr != '' || $bankname != '')){
				if($LedgerActivity==1 && $TransDtdbcd=='D')
					$vChkJourDtType = 'A'; 
				else $vChkJourDtType = 'C';
				fbegin();
				$query = " INSERT INTO chkjourdt (TransDt_Id, Chk_number, Chk_bank, Chk_ValueDate, Currency_Code, Chk_Amount, Chk_Amount1, Chk_Amount2, ".
						 " Ledger_Number, Chk_Type, Synchronized, User_Account ) ". 
						 " VALUES ( ".$vTransDtId.", '".ereg_replace("'", "\'", trim($chknbr))."', '".ereg_replace("'", "\'", trim($bankname))."', ".$txtValueDate.", ".
						 "          '".$txtCurr."', $txtTotalAmount, $TransAmount1, $TransAmount2, '".$PreReceipt_Acc."', '".$vChkJourDtType."', 0, '".$_SESSION['useraccount']."'	) ";
						 
				//echo $query."<br>";exit;				
				$result=mysql_query($query,$connection);
					
				if ($result){
					fcommit();
				} else{
					$ErrorExists = 0;
					$message  = mysql_error(); 
					frollback();
				}
			}
		}
	}
	//echo $message;
	//exit;
}
else
	if($actionmode == "currbank"){
		$query_cashtype  = "select banks.bank_name as BankName, cashtype.currency_code as CurrencyCode
		                   from cashtype left join banks on banks.bank_id = cashtype.bank_id
						   where Auto = '$txtCashType'";
		$result_cashtype = mysql_query($query_cashtype, $connection);
		$row_cashtype    = mysql_fetch_array($result_cashtype);
		extract($row_cashtype);
		echo $BankName;
		echo "[BRK]";
		echo $CurrencyCode;
		echo "[BRK]";
		exit;
	}
	else
		if($actionmode == "chknumberexists"){
			$ledger_number = $_GET['ledger_number'];
			$TransType     = $_GET['TransType'];
			$query_selectExists  = "select ledger_number, ledger_name
			                        from ledger
								    where ledger_number = '$ledger_number' and Ledger_grpdet = 0";
			$result_selectExists = mysql_query($query_selectExists, $connection);
			$row_selectExists    = mysql_fetch_array($result_selectExists);
			extract($row_selectExists);
			if($ledger_name == ""){
				$response = 0;
			}
			else{
				$response = 1;
			}
			echo $response;
			echo "[BRK]";
			echo $ledger_number;
			echo "[BRK]";
			echo $ledger_name;
			echo "[BRK]";
			exit;
		}

if($message !='' && $ErrorExists == 1)
header ("Location: ./Form_PreTrans.php?mainaction=Cancel&message=".$message."&TransType=".$TransType);
else header ("Location: ./Form_PreTrans.php?mainaction=done&TransId=".$vTransId."&TransType=".$TransType."&print_check=".$print_check."&bankname2=".$bankname2);


?>