<?php

session_start();

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']) or die("Could not connect to DB");
mysql_select_db($_SESSION['dbName'],$connection) or die("Could not find DB");

//Read From Setup Table							
$querysetup= " select DecimalBase, DecimalBase1, DecimalBase2, base1, base2 from setup ";

$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}


$PInvoicesID = $_POST['PInvoicesID']; 	if($PInvoicesID == '') 	$PInvoicesID = $_GET['PInvoicesID'];
$PReceiptsID = $_POST['PReceiptsID']; 	if($PReceiptsID == '') 	$PReceiptsID = $_GET['PReceiptsID'];
$referer = $_POST['referer']; 	if($referer == '') 	$referer = $_GET['referer'];



// echo "<br><br><br>PReceiptsID:";
// echo "<pre>";
// var_dump($PReceiptsID);
// echo "</pre>";


$message='';

$vInvoices = explode(',', $PInvoicesID);
$vReceipts = explode(',', $PReceiptsID);

$AmountSavedB1 = 0;
$AmountSavedB2 = 0;
$AmountSaved   = 0;

$detaillink_id  = $vReceipts[0];
$detaillink_id1 = $vReceipts[0];
$AmountRV	 = 'AmountRV'.$detaillink_id;	

if($mode == 'convertAmount'){
	$amount 	= $_GET['amount'];
	$transDate 	= $_GET['transDate'];
	$opt 		= $_GET['opt'];
		
	$ndate = explode('-',$transDate);
	$transDate = $ndate[2]."-".$ndate[1]."-".$ndate[0];
		
		if($opt == 1){
			$fromCurr = $base1;
			$toCurr = $base2;
		} else if($opt == 2){
			$fromCurr = $base2;
			$toCurr = $base1;
		}
			
		$query = "select convertcurFunc('$fromCurr', '$toCurr', '$transDate', 0, 0, '', '', $amount)";
		$result = mysql_query($query,$connection);
		$row = mysql_fetch_row($result);
		$amount2 = $row[0];
		echo "[BRK]";
		echo round($amount2,$DecimalBase);
		exit;
}
if($mode == 'formatNumber'){
	$amount = $_GET['amount'];
	
	echo "[BRK]";
	echo number_format($amount, $DecimalBase);
	exit;
}
// echo $querysetup;
// echo "<br> Starting : Allocation Mode On $$ ( {$$AmountRV})<br>";
		
if($mode == "AllocateInvoices" && ($vInvoices != ''  && $vReceipts != '')){
	$ledger_type = $_GET['ledger_type'];
	$ct=0;
	//get the trans
	$querys = " select relation_id, trans_reference, journal_type, currency_code, ledger_number, Detaillink_date , amountbase1,transQuery.OriginalAmount as orgAmnt from ".$_SESSION['dbLabel'].".detaillink 
		  left join
			  (select trans.trans_date,trans_type,transdt_id, transdt_amount1 as OriginalAmount from transdt left join trans on transdt.trans_id = trans.trans_id ) as transQuery
									on detaillink.journal_type = transQuery.trans_type  and detaillink.relation_id = transQuery.transdt_id
		  where Detaillink_id = $detaillink_id  ";
	// echo $querys;
	$results = mysql_query($querys,$connection);
	$rows = mysql_fetch_row($results);
	$vrelation_id      = $rows[0];	
	$vtrans_reference   = $rows[1];
	$vdetaillink_type   = $rows[2];
	$vdetaillink_cur    = $rows[3];
	$vdetaillink_ledger = $rows[4];
	$vdetaillink_date   = $rows[5];
	$vdetailAmount   = $rows[6];
	$vorgAmnt   = $rows[7];
	if($referer == 'SR'){
		$queryrelation = "select deliveries.journal_id,journal.Amnt1_cd from deliveries left join journal on deliveries.journal_id = journal.Journal_id  where deliveries.journal_type = 'DR' and Delivery_Reference = $vtrans_reference";
		$resultsrel = mysql_query($queryrelation,$connection);
		$resultsrel = mysql_fetch_row($resultsrel);
		$vrelation_id = $resultsrel[0];
		$query = " update ".$_SESSION['dbLabel'].".detaillink set relation_id = $vrelation_id where detaillink_id = $detaillink_id ";
		$resultsrel = mysql_query($query,$connection);
	}
	//get the original amount = detaillink amount
	// if(abs($vorgAmnt) != abs($vdetailAmount)){
	// 	// echo "<br> geting old line with <br> $getoldDetail";
	// 	$remAmountDetail = "insert into ".$_SESSION['dbLabel'].".Detaillink (
	// 						Detaillink_date,year,id,company,journal_type,form_id,ledger_number,project_code,costcent_code,amount,amountbase1,amountbase2,currency_code,remark,related_journalType,saleman_number,relation_id,reference,trans_reference,description,value_date,manual_no,link_belongToGoup)
	// 						select Detaillink_date,year,id,company,journal_type,form_id,ledger_number,project_code,costcent_code,{$$AmountRV}/(amountbase1/amount),{$$AmountRV},{$$AmountRV}/(amountbase1/amountbase2),currency_code,remark,related_journalType,saleman_number,relation_id,reference,trans_reference,description,
	// 						value_date,manual_no,link_belongToGoup   from ".$_SESSION['dbLabel'].".detaillink where Detaillink_id = $detaillink_id";
							
	// 	$resultx = mysql_query($remAmountDetail,$connection);
	// 	// echo "<br> inserting new values <br> $remAmountDetail";
	// 	 $detaillink_id = mysql_insert_id();	
	// 	// exit;
	// }
	$querys = " select relation_id, trans_reference, journal_type, currency_code, ledger_number, Detaillink_date ".
		  " from ".$_SESSION['dbLabel'].".detaillink where Detaillink_id = $detaillink_id  ";
	//  echo $querys."<br>";
	$results = mysql_query($querys,$connection);
	$rows = mysql_fetch_row($results);
	$relation_id      = $rows[0];	
	$trans_reference   = $rows[1];
	$detaillink_type   = $rows[2];
	$detaillink_cur    = $rows[3];
	$detaillink_ledger = $rows[4];
	$detaillink_date   = $rows[5];
	

	//  echo " Starting For Each  <br><br>";
	foreach($vInvoices as $headerlink_id){
		
		$AmountSI 	 = 'AmountSI'.$headerlink_id;
		$AmountSIb2  = 'AmountSIb2'.$headerlink_id;
		
		$querys = " select headerlink_date, currency_code ".
				  " from ".$_SESSION['dbLabel'].".headerlink where headerlink_id = $headerlink_id "; 
		// echo $querys."<br>";
		$results = mysql_query($querys,$connection);
		$rows = mysql_fetch_row($results);
		$headerdate = $rows[0];	
		$currencycode = $rows[1];
		// echo  " Original  Amount RV === > ".$AmountRV . " $$ =====> " . $$AmountRV;
		// echo  " Original  Amount SI === > ".$AmountSI . " $$ =====> " . $$AmountSI;
		// echo "<br>";
		// echo "<br>";
		// echo "<br>";
		// echo "<br>";
		if(abs($$AmountRV) > 0){
			// echo "<br>";
			// echo "<br>";
			// echo "<br>";
			// ($$AmountRV <=  $$AmountSI) ?   $xxx ='true' : $xxx =' false' ;

			// echo "------------ {( " . $xxx ." )} ----------";
			// echo "<br>";
			// echo "<br>";
			// echo "<br>";
			if(abs($$AmountRV) <=  abs($$AmountSI)){
				$AmountSavedB1 = $$AmountRV;
				$$AmountRV = 0;
				
				// echo "<br>";
				// echo "<br>";
				// echo "1 -  new RV Amount ================> {$$AmountRV}";
				// echo "<br>";
				// echo "<br>";
				
			} else if (abs($$AmountRV) > abs($$AmountSI)){
				$AmountSavedB1 = $$AmountSI;
				$$AmountRV = $$AmountRV - $$AmountSI; 
				// echo "<br>";
				// echo "<br>";
				// echo " 2-  new RV Amount ================> {$$AmountRV}";
				// echo "<br>";
				// echo "<br>";
				// echo "<br>";
			}
			$AmountSaved   = ConvertCurrency($base1, $currencycode, $headerdate, $AmountSavedB1, $connection);
			$AmountSavedB2 = ConvertCurrency($base1, $base2, $headerdate, $AmountSavedB1, $connection);
			
			if($ct == 0){
				//  echo " CT  # --- $ct-- ";
				$query = " update ".$_SESSION['dbLabel'].".detaillink as detaillink, ".$_SESSION['dbLabel'].".headerlink as headerlink ".
						 " set Detaillink_date = headerlink_date, detaillink.year = headerlink.year, detaillink.id = headerlink.id, detaillink.company = headerlink.company, ".
						 " detaillink.form_id = headerlink.form_id, detaillink.ledger_number = headerlink.ledger_number, detaillink.project_code = headerlink.project_code, ".
						 " detaillink.costcent_code = headerlink.costcent_code, detaillink.amount = $AmountSaved, detaillink.amountbase1 = $AmountSavedB1, detaillink.amountbase2 = $AmountSavedB2, ".
						 " detaillink.currency_code = headerlink.currency_code, detaillink.remark = headerlink.remark, detaillink.related_journalType = headerlink.journal_type, ".
						 " detaillink.saleman_number = headerlink.saleman_number, detaillink.reference = headerlink.reference".
						 " where Detaillink_id = $detaillink_id and headerlink_id = $headerlink_id  "; 
								// echo $query;echo"<br>";
				$result = mysql_query($query,$connection);

			} else {
				$query = " select ifnull(max(detailid),0) from ( ".
						 " select max(d1.detaillink_id) as detailid from ".$_SESSION['dbLabel'].".detaillink as d1 ".
						 " union ".
						 " select max(d2.detaillink_id) as detailid from ".$_SESSION['dbLabel'].".temp_detaillink as d2 ".
						 " ) as Q";
							//	echo $query;echo"<br>";
				$res = mysql_query($query,$connection);
				$rw = mysql_fetch_row($res);
				$detaillink_id = $rw[0] + 1;
				
				$query = " insert into ".$_SESSION['dbLabel'].".detaillink (Detaillink_id, Detaillink_date, year, id, company, journal_type, form_id, ledger_number, project_code, costcent_code,".
						 " amount, amountbase1, amountbase2, currency_code, remark, related_journalType, saleman_number, relation_id, reference, trans_reference) ".
						 " select $detaillink_id, headerlink_date, year, id, company, '$detaillink_type', form_id, ledger_number, project_code, costcent_code, ".
						 " $AmountSaved, $AmountSavedB1, $AmountSavedB2, currency_code, remark, journal_type, saleman_number,'$relation_id',reference,'$trans_reference' ".
						 " from ".$_SESSION['dbLabel'].".headerlink where headerlink_id = $headerlink_id ";
						// echo $query;echo"<br>";
			    $result = mysql_query($query,$connection);
			}
		}
		$ct++;
	}
 
//  echo "<br>";
//  echo "<br>";
//  echo "<br>";
//  echo "<br>";
//  echo "<br>";
//  echo "<br>";
//  echo "Second Step Accessed";
 
//  echo "<br>";
//  echo "<br>";
//  echo "<br>";
	if($$AmountRV > 0){
		$query = " select ifnull(max(detailid),0) from ( ".
				 " select max(d1.detaillink_id) as detailid from ".$_SESSION['dbLabel'].".detaillink as d1 ".
				 " union ".
				 " select max(d2.detaillink_id) as detailid from ".$_SESSION['dbLabel'].".temp_detaillink as d2 ".
				 " ) as Q";
						// echo $query;echo"<br>";
		$res = mysql_query($query,$connection);
		$rw = mysql_fetch_row($res);
		$detaillink_id = $rw[0] + 1;	
		
		$querydt = " select transdt.Trans_Date, transdt.Ledger_number,transdt.Currency_code,relation_id, trans_reference ".
				   " from ".$_SESSION['dbLabel'].".detaillink as detaillink ".
				   " inner join transdt on transdt.transdt_id = detaillink.relation_id ".
				   " where detaillink_id = $detaillink_id1 ;"; //echo $querydt;
		//  echo $querydt;echo"<br>";
		$resdt = mysql_query($querydt,$connection);
		$rowdt = mysql_fetch_row($resdt);
		
		$AmountSavedB1 = $$AmountRV;
		$AmountSaved   = ConvertCurrency($base1, $detaillink_cur, $headerdate, $AmountSavedB1, $connection);
		$AmountSavedB2 = ConvertCurrency($base1, $base2, $headerdate, $AmountSavedB1, $connection);
		
		$vMainCompanyName=explode('_',$_SESSION['dbName']);  
		$DirCompany  = $vMainCompanyName[0];
		preg_match_all('!\d+!', $vMainCompanyName[1] ,$DirYears );
		$DirYear =  $DirYears[0][0];  
						
		$query = " insert into ".$_SESSION['dbLabel'].".detaillink (Detaillink_id, Detaillink_date, year, company, journal_type, ledger_number, ".
				 " amount, amountbase1, amountbase2, currency_code, relation_id, trans_reference) ".
				 " values ($detaillink_id, '$detaillink_date','$DirYear', '$DirCompany', '$detaillink_type', '$detaillink_ledger', $AmountSaved, $AmountSavedB1, $AmountSavedB2,".
				 " '$detaillink_cur','$relation_id','$trans_reference' )"; //echo $query;
							 
		$result = mysql_query($query,$connection);
	}

	
	if($referer == 'SR'){
		header("Location: ./Form_ReturnDelivery.php");
	}
	echo "<form name='advAlloc' method='POST' action='Form_AdvancedPaymentAllocation.php'>
			<input type='hidden' name='fromledger' value='$fromledger'>
			<input type='hidden' name='toledger' value='$toledger'> 
			<input type='hidden' name='fromdate' value='01/01/2020'>
			<input type='hidden' name='todate' value='31/12/2020'>
			<input type='hidden' name='actionmode' value='Search'>
			<input type='hidden' name='isAllocated' value='0'>
			<input type='hidden' name='ledgertype' value='$ledger_type'>
		</form>
		<script>
			document.advAlloc.submit();
		</script>";
		exit;
} //exit;

 
if($referer == 'SR'){
	header ("Location: ./Form_ReturnDelivery.php");
}else if($referer == 'PR'){
	header ("Location: ./Form_ReturnDelivery.php");
}else{
	header ("Location: ./Form_AdvancedPaymentAllocation.php");
}





?>