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


$message='';

if(is_array($PInvoicesID))    $vInvoices = implode(',', array_filter($PInvoicesID)); else $vInvoices = $PInvoicesID;
if(is_array($PSalesJVID))     $vSalesJV = implode(',', array_filter($PSalesJVID)); else $vSalesJV = $PSalesJVID;
if(is_array($POtherDBID))     $vOtherDB = implode(',', array_filter($POtherDBID)); else $vOtherDB = $POtherDBID;
if(is_array($PRetInvoicesID)) $vRetInvoices = implode(',', array_filter($PRetInvoicesID)); else $vRetInvoices = $PRetInvoicesID;
if(is_array($PReceiptsID))    $vReceipts = implode(',', array_filter($PReceiptsID)); else $vReceipts = $PReceiptsID;
if(is_array($PCredNotesID))   $vCredNotes = implode(',', array_filter($PCredNotesID)); else $vCredNotes = $PCredNotesID;
if(is_array($PJournalsID))    $vJournals = implode(',', array_filter($PJournalsID)); else $vJournals = $PJournalsID;

$vInvoices    = trim($vInvoices,','); 
$vSalesJV     = trim($vSalesJV,',');
$vOtherDB     = trim($vOtherDB,',');
$vRetInvoices = trim($vRetInvoices,','); 
$vReceipts    = trim($vReceipts,','); 
$vCredNotes   = trim($vCredNotes,','); 
$vJournals    = trim($vJournals,','); 


if($mode == "AllocateInvoices" && ($vInvoices != '' || $vSalesJV != '' || $vOtherDB != '')){

	$SaveAllowed = 1;
	$ErrorExists = 0;
	
	
	$vLinkRef      = '';
	$vLinkType     = '';
	$vJournalType  = '';
	$vSaleNetTotal         = 0;
	$vSaleNetTotalBase1    = 0;
	$vSaleNetTotalBase2    = 0;
	$vSalePaidAmnt         = 0;
	$vSalePaidAmntBase1    = 0;
	$vSalePaidAmntBase2    = 0;
	$vSaleRemainAmnt       = 0;
	$vSaleRemainAmntBase1  = 0;
	$vSaleRemainAmntBase2  = 0;
	

	if ($vInvoices != "") {
		$vInvoices = explode(',', $vInvoices);
		$vInvoicesID = $vInvoices[0];
		$DirSchemaSI = $vInvoices[1];
		
		$vMainCompanyName=explode('_',$DirSchemaSI);  
		$DirCompany  = $vMainCompanyName[0];
		$DirYear	 = $vMainCompanyName[1];
		
		if($Module_Delivery == 0 ) {
			$sub_query = " Select Deliveries.Delivery_Id As InvoiceId, Deliveries.Delivery_Reference As SalesRefer, 'SI' As JournalType, ".
						 " (ifNull(Deliveries.Delivery_Total,0) - ifNull(Deliveries.Delivery_DiscountAmount,0) + ifNull(Deliveries.Delivery_Vat,0)) As SalesTotal, ".
						 " (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As SalesTotalBase1, ".
						 " (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As SalesTotalBase2, ".
						 " ((ifNull(Deliveries.Delivery_Total,0) - ifNull(Deliveries.Delivery_DiscountAmount,0) + ifNull(Deliveries.Delivery_Vat,0)) - Sum(ifNull(AccLink.Sale_PaidAmnt,0) + ifNull(AccLink.Sale_ReturnAmnt,0))) As SalesRem, ".
						 " ((ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
						 " ((ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2 ".
						 " From $DirSchemaSI.Deliveries As Deliveries ".
						 //" Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Reference = Acclink.Link_Ref And Acclink.Link_Type In ('DI','SI') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
						 " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Id = Acclink.Link_ID And Acclink.Link_Type In ('DI','SI') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
						 " Where Deliveries.journal_Type = 'DI' ".
						 " And Deliveries.Delivery_Id = '".$vInvoicesID."' ".
						 " And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
						 " Group By Deliveries.Delivery_Id  ";
		} else {
			$sub_query = " Select Sales.Sale_Id As InvoiceId, Sales.Sale_Reference As SalesRefer, 'SI' As JournalType, ".
						 " (ifNull(Sales.Sale_Total,0) - ifNull(Sales.Sale_DiscountAmount,0) + ifNull(Sales.Sale_VAT,0)) As SalesTotal, ".
						 " (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As SalesTotalBase1, ".
						 " (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As SalesTotalBase2, ".
						 " ((ifNull(Sales.Sale_Total,0) - ifNull(Sales.Sale_DiscountAmount,0) + ifNull(Sales.Sale_VAT,0)) - Sum(ifNull(AccLink.Sale_PaidAmnt,0) + ifNull(AccLink.Sale_ReturnAmnt,0))) As SalesRem, ".
						 " ((ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
						 " ((ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2 ".
						 " From $DirSchemaSI.Sales As Sales ".
						 //" Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Sales.Sale_Reference = Acclink.Link_Ref And Acclink.Link_Type In ('DI','SI') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
						 " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Sales.Sale_Id = Acclink.Link_ID And Acclink.Link_Type In ('DI','SI') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
						 " Where Sales.journal_Type = 'SI' ".
						 " And Sales.Sale_Id = '".$vInvoicesID."' ".
						 " And IfNull(Sales.Sale_OldData,0) = 0 ".
						 " Group By Sales.Sale_Id  ";
		}
		
	} 
	else if ($vSalesJV != "") { 
		$vSalesJV = explode(',', $vSalesJV);
		$vSalesJVID  = $vSalesJV[0];
		$DirSchemaJS = $vSalesJV[1];
		
		$vMainCompanyName=explode('_',$DirSchemaJS);  
		$DirCompany  = $vMainCompanyName[0];
		$DirYear	 = $vMainCompanyName[1];
		
		$sub_query = " Select SalesJV.SalesJV_Id As InvoiceId, SalesJV.SalesJV_Reference As SalesRefer, SalesJV.journal_Type As JournalType, ".
					 " (ifNull(SalesJV.SalesJV_Total,0) - ifNull(SalesJV.SalesJV_DiscountAmount,0) + ifNull(SalesJV.SalesJV_Vat,0)) As SalesTotal, ".
					 " (ifNull(SalesJV.SalesJV_TotalBase1,0) - ifNull(SalesJV.SalesJV_DiscountAmount1,0) + ifNull(SalesJV.SalesJV_VatBase1,0)) As SalesTotalBase1, ".
					 " (ifNull(SalesJV.SalesJV_TotalBase2,0) - ifNull(SalesJV.SalesJV_DiscountAmount2,0) + ifNull(SalesJV.SalesJV_VatBase2,0)) As SalesTotalBase2, ".
					 " ((ifNull(SalesJV.SalesJV_Total,0) - ifNull(SalesJV.SalesJV_DiscountAmount,0) + ifNull(SalesJV.SalesJV_Vat,0)) - Sum(ifNull(AccLink.Sale_PaidAmnt,0) + ifNull(AccLink.Sale_ReturnAmnt,0))) As SalesRem, ".
					 " ((ifNull(SalesJV.SalesJV_TotalBase1,0) - ifNull(SalesJV.SalesJV_DiscountAmount1,0) + ifNull(SalesJV.SalesJV_VatBase1,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
					 " ((ifNull(SalesJV.SalesJV_TotalBase2,0) - ifNull(SalesJV.SalesJV_DiscountAmount2,0) + ifNull(SalesJV.SalesJV_VatBase2,0)) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2 ".
					 " From $DirSchemaJS.SalesJV As SalesJV ".
					 //" Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on SalesJV.SalesJV_Reference = Acclink.Link_Ref And Acclink.Link_Type = 'JS' And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					 " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on SalesJV.SalesJV_Id = Acclink.Link_ID And Acclink.Link_Type = 'JS' And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					 " Where SalesJV.journal_Type = 'JS' ".
					 " And SalesJV.SalesJV_Id = '".$vSalesJVID."' ".
					 " And IfNull(SalesJV.SalesJv_OldData,0) = 0 ".
					 " Group By SalesJV.SalesJV_Id  ";
	}
	else if ($vOtherDB != "") {
		$vOtherDB = explode(',', $vOtherDB);
		$vOtherDBID  = $vOtherDB[0];
		$DirSchemaDB = $vOtherDB[1];
		
		$vMainCompanyName=explode('_',$DirSchemaDB);  
		$DirCompany  = $vMainCompanyName[0];
		$DirYear	 = $vMainCompanyName[1];
		
		$sub_query = " Select JournalDt.JournalDt_Id As InvoiceId, Journal.Journal_refgovernment As SalesRefer, Journal.Journal_Type As JournalType, ".
					 " ifNull(Journaldt_amount,0) As SalesTotal, ifNull(Journaldt_amount1,0) As SalesTotalBase1, ifNull(Journaldt_amount2,0) As SalesTotalBase2, ".
					 " (ifNull(Journaldt_amount,0) - Sum(ifNull(AccLink.Sale_PaidAmnt,0) + ifNull(AccLink.Sale_ReturnAmnt,0))) As SalesRem, ".
					 " (ifNull(Journaldt_amount1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
					 " (ifNull(Journaldt_amount2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2 ".
					 " From $DirSchemaDB.JournalDt As JournalDt ".
					 " Inner join $DirSchemaDB.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
					 " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Acclink.Link_ID = JournalDt.JournalDt_Id And Acclink.Link_Type = Journal.Journal_Type And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					 " Where JournalDt.Journaldt_dbcd = 'D' ".
					 " And Journal.Journal_Type Not In ('CV','SI','SR') ".
					 " And JournalDt.JournalDt_Id = '".$vOtherDBID."' ".
					 " And IfNull(JournalDt.JournalDt_OldData,0) = 0 ".
					 " Group By JournalDt.JournalDt_Id  ";
	
	}
	
	//echo $sub_query; exit;
					
	$sub_result = selectData($connection, $sub_query);
	
	$vLinkID    	    = $sub_result[0];
	$vLinkRef    	    = $sub_result[1];
	$vLinkType   	    = $sub_result[2];
	$vSaleNetTotal      = $sub_result[3];
	$vSaleNetTotalBase1 = $sub_result[4];
	$vSaleNetTotalBase2 = $sub_result[5];
	$vSaleNetRemainAmnt       = $sub_result[6];
	$vSaleNetRemainAmntBase1  = $sub_result[7];
	$vSaleNetRemainAmntBase2  = $sub_result[8];		
	

	
	//echo $sub_query;exit;					
						
	if ($ErrorExists == 0) {
		
		
		if (empty($vSaleNetTotal))   	 $vSaleNetTotal = 0;
		if (empty($vSaleNetTotalBase1))  $vSaleNetTotalBase1 = 0;
		if (empty($vSaleNetTotalBase2))  $vSaleNetTotalBase2 = 0;
				
				
		//Return Invoices
		if ($vRetInvoices != "") { 
			$vRetInvoices = explode('-', $vRetInvoices);
			foreach($vRetInvoices as $vRetInvoice) {
				$vRetInvoice = explode(',', $vRetInvoice);
				$vRetInvoicesID = $vRetInvoice[0];
				$DirSchemaSR    = $vRetInvoice[1];
				
				$vMainCompanyName=explode('_',$DirSchemaSR);  
				$DirYearSR  = $vMainCompanyName[1];
				
				
				$vTransRef 		 	    = '';
				$vTransJourType  	    = '';
				$vTransDate 	 	    = '';
				$vTransValueDate 	    = '';
				$vTransDesc		 	    = '';
				$vTransPaidAmnt         = 0;
				$vTransPaidAmntBase1    = 0;
				$vTransPaidAmntBase2    = 0;
				$vTransRemainAmnt       = 0;
				$vTransRemainAmntBase1  = 0;
				$vTransRemainAmntBase2  = 0;
				
				
				if($Module_Delivery == 0 ) {
					$sub_query1 = " Select Deliveries.Delivery_Id As InvoiceId, Deliveries.Delivery_Reference As SalesRefer, 'SR' As JournalType, ".
								  " Deliveries.Delivery_Date As SalesDate, Deliveries.JournalDt_ValueDate As SalesValueDate, Deliveries.Delivery_Remark As SalesRemark,  ".
								  " (ifNull(Deliveries.Delivery_Total,0) - ifNull(Deliveries.Delivery_DiscountAmount,0) + ifNull(Deliveries.Delivery_Vat,0)) As SalesTotal, ".
								  " (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As SalesTotalBase1, ".
								  " (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As SalesTotalBase2, ".
								  " ((ifNull(Deliveries.Delivery_Total,0) - ifNull(Deliveries.Delivery_DiscountAmount,0) + ifNull(Deliveries.Delivery_Vat,0)) - Sum(ifNull(AccLink.Sale_ReturnAmnt,0))) As SalesRem, ".
								  " ((ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) - Sum(ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
								  " ((ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) - Sum(ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2 ".
								  " From $DirSchemaSR.Deliveries As Deliveries ".
								  //" Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Reference = Acclink.Return_Ref And Acclink.Return_Type In ('DR','SR') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.DirYear) = upper('".$DirYearSR."') ".
								  " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Deliveries.Delivery_Id = Acclink.Return_ID And Acclink.Return_Type In ('DR','SR') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.DirYear) = upper('".$DirYearSR."') ".
								  " Where Deliveries.journal_Type = 'DR' ".
								  " And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
								  " And Deliveries.Client_Code between ifNull('".$fromledger."',Deliveries.Client_Code) and ifNull('". $toledger."',Deliveries.Client_Code) ".
								  " And Deliveries.Delivery_Id In (".$vRetInvoicesID.") ".
								  " Group By Deliveries.Delivery_Id  ";
				} else {
					$sub_query1 = " Select Sales.Sale_Id As InvoiceId, Sales.Sale_Reference As SalesRefer, 'SR' As JournalType, ".
								  " Sales.Sale_Date As SalesDate, Sales.JournalDt_ValueDate As SalesValueDate, Sales.Sale_Remark As SalesRemark,  ".
								  " (ifNull(Sales.Sale_Total,0) - ifNull(Sales.Sale_DiscountAmount,0) + ifNull(Sales.Sale_VAT,0)) As SalesTotal, ".
								  " (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As SalesTotalBase1, ".
								  " (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As SalesTotalBase2, ".
								  " ((ifNull(Sales.Sale_Total,0) - ifNull(Sales.Sale_DiscountAmount,0) + ifNull(Sales.Sale_VAT,0)) - Sum(ifNull(AccLink.Sale_ReturnAmnt,0))) As SalesRem, ".
								  " ((ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) - Sum(ifNull(AccLink.Sale_ReturnAmntBase1,0))) As SalesRemBase1, ".
								  " ((ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) - Sum(ifNull(AccLink.Sale_ReturnAmntBase2,0))) As SalesRemBase2 ".
								  " From $DirSchemaSR.Sales As Sales ".
								  //" Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Sales.Sale_Reference = Acclink.Return_Ref And Acclink.Return_Type In ('DR','SR') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.DirYear) = upper('".$DirYearSR."') ".
								  " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Sales.Sale_Id = Acclink.Return_ID And Acclink.Return_Type In ('DR','SR') And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.DirYear) = upper('".$DirYearSR."') ".
								  " Where Sales.journal_Type = 'SR' ".
								  " And IfNull(Sales.Sale_OldData,0) = 0 ".
								  " And Sales.Client_Code between ifNull('".$fromledger."',Sales.Client_Code) and ifNull('". $toledger."',Sales.Client_Code) ".
								  " And Sales.Sale_Id In (".$vRetInvoicesID.") ".
								  " Group By Sales.Sale_Id  ";
				}
					//echo $sub_query1; exit;			
				$sub_result1=mysql_query($sub_query1,$connection) or die(mysql_error($connection));
				while($sub_rows1=mysql_fetch_row($sub_result1)){
				
					$vTransID 		 	    = $sub_rows1[0];
					$vTransRef 		 	    = $sub_rows1[1];
					$vTransJourType  	    = $sub_rows1[2];
					$vTransDate 	 	    = $sub_rows1[3];
					$vTransValueDate 	    = $sub_rows1[4];
					$vTransDesc		 	    = $sub_rows1[5];
					
					if ($sub_rows1[10] <= $vSaleNetRemainAmntBase1) {
						$vTransPaidAmnt         = $sub_rows1[9];
						$vTransPaidAmntBase1    = $sub_rows1[10];
						$vTransPaidAmntBase2    = $sub_rows1[11];
					} else 	{
						$vTransPaidAmnt         = $vSaleNetRemainAmnt;
						$vTransPaidAmntBase1    = $vSaleNetRemainAmntBase1;
						$vTransPaidAmntBase2    = $vSaleNetRemainAmntBase2;
					}
					
					$vTransRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vTransRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vTransRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;		
					
					$vSaleNetRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vSaleNetRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vSaleNetRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;
				
					fbegin();
					$query = " INSERT INTO ".$_SESSION['dbLabel'].".AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Return_ID, Return_Ref, Return_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_ReturnAmnt, Sale_ReturnAmntbase1, ".
							 " Sale_ReturnAmntbase2, Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Return_Date, Return_ValueDate, Return_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
							 " VALUES ( Null, '".$vLinkID."', '".$vLinkRef."', '".$vLinkType."', '".$vTransID."', '".$vTransRef."', '".$vTransJourType."', $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, $vTransPaidAmnt, ".
							 "          $vTransPaidAmntBase1, $vTransPaidAmntBase2, $vTransRemainAmnt, $vTransRemainAmntBase1, $vTransRemainAmntBase2, $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, ".
							 "          Null, Null, '".$vTransDate."', '".$vTransValueDate."', Null, '".$DirCompany."', '".$DirYearSR."', '".$DirYear."', '".$_SESSION['useraccount']."') ";
								 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
							
					if ($result){
						fcommit();
					} else{
						$message  = mysql_error(); 
						frollback();
					}
				
				}
			}	
		}

		//Receipts
		if ($vReceipts != "") { 
			$vReceipts = explode('-', $vReceipts);
			foreach($vReceipts as $vReceipt) {
				$vReceipt = explode(',', $vReceipt);
				$vReceiptsID = $vReceipt[0];
				$DirSchemaRV = $vReceipt[1];
				
				$vMainCompanyName=explode('_',$DirSchemaRV);  
				$DirYearRV  = $vMainCompanyName[1];
				
			
				$vTransRef 		 	    = '';
				$vTransJourType  	    = '';
				$vTransDate 	 	    = '';
				$vTransValueDate 	    = '';
				$vTransDesc		 	    = '';
				$vTransPaidAmnt         = 0;
				$vTransPaidAmntBase1    = 0;
				$vTransPaidAmntBase2    = 0;
				$vTransRemainAmnt       = 0;
				$vTransRemainAmntBase1  = 0;
				$vTransRemainAmntBase2  = 0;
				
				
				$sub_query2 = " Select Trans.Trans_Id As InvoiceId, Trans.Trans_Reference As SalesRefer, Trans.Trans_Type As JournalType, ".
							  " Trans.Trans_Date As SalesDate, TransDt.TransDt_ValueDate As SalesValueDate, TransDt.TransDt_Description As SalesRemark,  ".
							  " ifNull(TransDt.Transdt_Amount,0) As SalesTotal, ifNull(TransDt.Transdt_Amount1,0) As SalesTotalBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesTotalBase2, ".
							  " (ifNull(TransDt.Transdt_Amount,0) - Sum(ifNull(AccLink.Sale_PaidAmnt,0))) As SalesRem, ".
							  " (ifNull(TransDt.Transdt_Amount1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0))) As SalesRemBase1, ".
							  " (ifNull(TransDt.Transdt_Amount2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0))) As SalesRemBase2, ".
							  " TransDt.TransDt_Id As InvoiceDtId ".
							  " From $DirSchemaRV.TransDt As TransDt ".
							  " Inner Join $DirSchemaRV.Trans As Trans on TransDt.Trans_Id = Trans.Trans_Id ".
							  " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Acclink.Journal_Id = TransDt.TransDt_Id And Acclink.Journal_Type = 'RV' And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.DirYear) = upper('".$DirYearRV."') ".
							  " Where Trans.Trans_Type = 'RV' ".
							  " And TransDt.TransDt_dbcd = 'C' ".
							  " And IfNull(TransDt.TransDt_OldData,0) = 0 ".
							  " And TransDt.Ledger_number between ifNull('".$fromledger."',TransDt.Ledger_number) and ifNull('". $toledger."',TransDt.Ledger_number) ".
							  " And TransDt.TransDt_Id In (".$vReceiptsID.") ".
							  " Group By Trans.Trans_Id  ";
				//echo $sub_query2."<br>"; exit;
				$sub_result2=mysql_query($sub_query2,$connection) or die(mysql_error($connection));
				while($sub_rows2=mysql_fetch_row($sub_result2)){
				
					$vTransDtID		 	    = $sub_rows2[12];
					$vTransRef 		 	    = $sub_rows2[1];
					$vTransJourType  	    = $sub_rows2[2];
					$vTransDate 	 	    = $sub_rows2[3];
					$vTransValueDate 	    = $sub_rows2[4];
					$vTransDesc		 	    = $sub_rows2[5];
					
					if ($sub_rows2[10] <= $vSaleNetRemainAmntBase1) {
						$vTransPaidAmnt         = $sub_rows2[9];
						$vTransPaidAmntBase1    = $sub_rows2[10];
						$vTransPaidAmntBase2    = $sub_rows2[11];
					} else 	{
						$vTransPaidAmnt         = $vSaleNetRemainAmnt;
						$vTransPaidAmntBase1    = $vSaleNetRemainAmntBase1;
						$vTransPaidAmntBase2    = $vSaleNetRemainAmntBase2;
					}
					
					$vTransRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vTransRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vTransRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;
					
					$vSaleNetRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vSaleNetRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vSaleNetRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;
				
					fbegin();
					$query = " INSERT INTO ".$_SESSION['dbLabel'].".AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
							 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
							 " VALUES ( ".$vTransDtID.", '".$vLinkID."', '".$vLinkRef."', '".$vLinkType."', '".$vTransJourType."', $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, $vTransPaidAmnt, ".
							 "          $vTransPaidAmntBase1, $vTransPaidAmntBase2, $vTransRemainAmnt, $vTransRemainAmntBase1, $vTransRemainAmntBase2, $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, ".
							 "          ".$vTransDtID.", '".$vTransRef."', '".$vTransDate."', '".$vTransValueDate."', '".$vTransDesc."', '".$DirCompany."', '".$DirYearRV."', '".$DirYear."', '".$_SESSION['useraccount']."'	) ";
								 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
							
					if ($result){
						fcommit();
					} else{
						$message  = mysql_error($connection); 
						frollback();
					}
				} 
			}
		}	
			  
		//Credit Notes
		if ($vCredNotes != "") {
			$vCredNotes = explode('-', $vCredNotes);
			foreach($vCredNotes as $vCredNote) {
				$vCredNote = explode(',', $vCredNote);
				$vCredNotesID = $vCredNote[0];
				$DirSchemaCV  = $vCredNote[1];
				
				$vMainCompanyName=explode('_',$DirSchemaCV);  
				$DirYearCV  = $vMainCompanyName[1];
				
				$vTransRef 		 	    = '';
				$vTransJourType  	    = '';
				$vTransDate 	 	    = '';
				$vTransValueDate 	    = '';
				$vTransDesc		 	    = '';
				$vTransPaidAmnt         = 0;
				$vTransPaidAmntBase1    = 0;
				$vTransPaidAmntBase2    = 0;
				$vTransRemainAmnt       = 0;
				$vTransRemainAmntBase1  = 0;
				$vTransRemainAmntBase2  = 0;

				
				$sub_query3 = " Select Trans.Trans_Id As InvoiceId, Trans.Trans_Reference As SalesRefer, Trans.Trans_Type As JournalType, ".
							  " Trans.Trans_Date As SalesDate, TransDt.TransDt_ValueDate As SalesValueDate, TransDt.TransDt_Description As SalesRemark,  ".
							  " ifNull(TransDt.Transdt_Amount,0) As SalesTotal, ifNull(TransDt.Transdt_Amount1,0) As SalesTotalBase1, ifNull(TransDt.Transdt_Amount2,0) As SalesTotalBase2, ".
							  " (ifNull(TransDt.Transdt_Amount,0) - Sum(ifNull(AccLink.Sale_PaidAmnt,0))) As SalesRem, ".
							  " (ifNull(TransDt.Transdt_Amount1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0))) As SalesRemBase1, ".
							  " (ifNull(TransDt.Transdt_Amount2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0))) As SalesRemBase2, ".
							  " TransDt.TransDt_Id As InvoiceDtId ".
							  " From $DirSchemaCV.TransDt As TransDt ".
							  " Inner Join $DirSchemaCV.Trans As Trans on TransDt.Trans_Id = Trans.Trans_Id ".
							  " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Acclink.Journal_Id = TransDt.TransDt_Id And Acclink.Journal_Type = 'CV' And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.DirYear) = upper('".$DirYearCV."') ".
							  " Where Trans.Trans_Type = 'CV' ".
							  " And IfNull(TransDt.TransDt_OldData,0) = 0 ".
							  " And TransDt.Ledger_number between ifNull('".$fromledger."',TransDt.Ledger_number) and ifNull('". $toledger."',TransDt.Ledger_number) ".
							  " And TransDt.TransDt_Id In (".$vCredNotesID.") ".
							  " Group By Trans.Trans_Id  ";
							  
				$sub_result3=mysql_query($sub_query3,$connection) or die(mysql_error($connection));
				while($sub_rows3=mysql_fetch_row($sub_result3)){
				
					$vTransDtID		 	    = $sub_rows3[12];
					$vTransRef 		 	    = $sub_rows3[1];
					$vTransJourType  	    = $sub_rows3[2];
					$vTransDate 	 	    = $sub_rows3[3];
					$vTransValueDate 	    = $sub_rows3[4];
					$vTransDesc		 	    = $sub_rows3[5];
					
					if ($sub_rows3[10] <= $vSaleNetRemainAmntBase1) {
						$vTransPaidAmnt         = $sub_rows3[9];
						$vTransPaidAmntBase1    = $sub_rows3[10];
						$vTransPaidAmntBase2    = $sub_rows3[11];
					} else 	{
						$vTransPaidAmnt         = $vSaleNetRemainAmnt;
						$vTransPaidAmntBase1    = $vSaleNetRemainAmntBase1;
						$vTransPaidAmntBase2    = $vSaleNetRemainAmntBase2;
					}
					
					$vTransRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vTransRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vTransRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;
					
					$vSaleNetRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vSaleNetRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vSaleNetRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;
				
					fbegin();
					$query = " INSERT INTO ".$_SESSION['dbLabel'].".AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
							 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
							 " VALUES ( ".$vTransDtID.", '".$vLinkID."', '".$vLinkRef."', '".$vLinkType."', '".$vTransJourType."', $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, $vTransPaidAmnt, ".
							 "          $vTransPaidAmntBase1, $vTransPaidAmntBase2, $vTransRemainAmnt, $vTransRemainAmntBase1, $vTransRemainAmntBase2, $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, ".
							 "          ".$vTransDtID.", '".$vTransRef."', '".$vTransDate."', '".$vTransValueDate."', '".$vTransDesc."', '".$DirCompany."', '".$DirYearCV."', '".$DirYear."', '".$_SESSION['useraccount']."'	) ";
								 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
							
					if ($result){
						fcommit();
					} else{
						$message  = mysql_error(); 
						frollback();
					}
				
				}
			}
		}
		
		
		//Other Types
		if ($vJournals != "") {
			$vJournals = explode('-', $vJournals);
			foreach($vJournals as $vJournal) {
				$vJournal = explode(',', $vJournal);
				$vJournalsID = $vJournal[0];
				$DirSchemaJV = $vJournal[1];
				
				$vMainCompanyName=explode('_',$DirSchemaJV);  
				$DirYearJV  = $vMainCompanyName[1];
				
		
				$vTransRef 		 	    = '';
				$vTransJourType  	    = '';
				$vTransDate 	 	    = '';
				$vTransValueDate 	    = '';
				$vTransDesc		 	    = '';
				$vTransPaidAmnt         = 0;
				$vTransPaidAmntBase1    = 0;
				$vTransPaidAmntBase2    = 0;
				$vTransRemainAmnt       = 0;
				$vTransRemainAmntBase1  = 0;
				$vTransRemainAmntBase2  = 0;
				

				$sub_query4 = " Select Journal.Journal_Id As InvoiceId, Journal.Journal_refgovernment As SalesRefer, Journal.Journal_Type As JournalType, ".
							  " JournalDt.Journal_date As SalesDate, JournalDt.Journaldt_ValueDate As SalesValueDate, JournalDt.Journaldt_desc As SalesRemark,  ".
							  " ifNull(Journaldt_amount,0) As SalesTotal, ifNull(Journaldt_amount1,0) As SalesTotalBase1, ifNull(Journaldt_amount2,0) As SalesTotalBase2, ".
							  " (ifNull(JournalDt.Journaldt_amount,0) - Sum(ifNull(AccLink.Sale_PaidAmnt,0))) As SalesRem, ".
							  " (ifNull(JournalDt.Journaldt_amount1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0))) As SalesRemBase1, ".
							  " (ifNull(JournalDt.Journaldt_amount2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0))) As SalesRemBase2, ".
							  " JournalDt.JournalDt_Id As InvoiceDtId ".
							  " From $DirSchemaJV.JournalDt As JournalDt ".
							  " Inner join $DirSchemaJV.Journal As Journal on JournalDt.Journal_id = Journal.Journal_id ".
							  " Left Join ".$_SESSION['dbLabel'].".Acclink As Acclink on Acclink.Journal_Id = JournalDt.JournalDt_Id And Acclink.Journal_Type = Journal.Journal_Type And upper(Acclink.CompanyName) = upper('".$DirCompany."') And upper(Acclink.DirYear) = upper('".$DirYearJV."') ".
							  " Where Journal.Journal_Type Not In ('RV','CV','SI','SR','OP') ".
							  " And IfNull(JournalDt.JournalDt_OldData,0) = 0 ".
							  " And JournalDt.Ledger_number between ifNull('".$fromledger."',JournalDt.Ledger_number) and ifNull('". $toledger."',JournalDt.Ledger_number) ".
							  " And JournalDt.Journaldt_dbcd = 'C' ".
							  " And JournalDt.JournalDt_Id In (".$vJournalsID.") ".
							  " Group By Journal.Journal_Id  ";
				//echo $sub_query4; exit;
				$sub_result4=mysql_query($sub_query4,$connection) or die(mysql_error($connection));
				while($sub_rows4=mysql_fetch_row($sub_result4)){
				
					$vTransDtID		 	    = $sub_rows4[12];
					$vTransRef 		 	    = $sub_rows4[1];
					$vTransJourType  	    = $sub_rows4[2];
					$vTransDate 	 	    = $sub_rows4[3];
					$vTransValueDate 	    = $sub_rows4[4];
					$vTransDesc		 	    = $sub_rows4[5];
					
					if ($sub_rows4[10] <= $vSaleNetRemainAmntBase1) {
						$vTransPaidAmnt         = $sub_rows4[9];
						$vTransPaidAmntBase1    = $sub_rows4[10];
						$vTransPaidAmntBase2    = $sub_rows4[11];
					} else 	{
						$vTransPaidAmnt         = $vSaleNetRemainAmnt;
						$vTransPaidAmntBase1    = $vSaleNetRemainAmntBase1;
						$vTransPaidAmntBase2    = $vSaleNetRemainAmntBase2;
					}
					
					$vTransRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vTransRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vTransRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;
					
					$vSaleNetRemainAmnt       = $vSaleNetRemainAmnt - $vTransPaidAmnt;
					$vSaleNetRemainAmntBase1  = $vSaleNetRemainAmntBase1 - $vTransPaidAmntBase1;
					$vSaleNetRemainAmntBase2  = $vSaleNetRemainAmntBase2 - $vTransPaidAmntBase2;
				
					fbegin();
					$query = " INSERT INTO ".$_SESSION['dbLabel'].".AccLink (Journal_Id, Link_ID, Link_Ref, Link_Type, Journal_Type, Sale_NetTotal, Sale_NetTotalBase1, Sale_NetTotalBase2, Sale_PaidAmnt, Sale_PaidAmntbase1, Sale_PaidAmntbase2, ".
							 " Sale_RemainAmnt, Sale_RemainAmntBase1, Sale_RemainAmntBase2, Sale_NetToPay, Sale_NetToPayBase1, Sale_NetToPayBase2, TraJournal_ID, Trans_Ref, Trans_Date, Trans_ValueDate, Trans_Description, CompanyName, DirYear, Link_DirYear, User_Account ) ".
							 " VALUES ( ".$vTransDtID.", '".$vLinkID."', '".$vLinkRef."', '".$vLinkType."', '".$vTransJourType."', $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, $vTransPaidAmnt, ".
							 "          $vTransPaidAmntBase1, $vTransPaidAmntBase2, $vTransRemainAmnt, $vTransRemainAmntBase1, $vTransRemainAmntBase2, $vSaleNetTotal, $vSaleNetTotalBase1, $vSaleNetTotalBase2, ".
							 "          ".$vTransDtID.", '".$vTransRef."', '".$vTransDate."', '".$vTransValueDate."', '".$vTransDesc."', '".$DirCompany."', '".$DirYearJV."', '".$DirYear."', '".$_SESSION['useraccount']."'	) ";
								 
					//echo $query."<br>";exit;				
					$result=mysql_query($query,$connection);
							
					if ($result){
						fcommit();
					} else{
						$message  = mysql_error(); 
						frollback();
					}
				
				}
			}	
		}
	}
	
}


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

//echo $mode.$message; exit;

header ("Location: ./Form_InvoicesAllocation.php?actionmode=Search&fromledger=".$fromledger."&toledger=".$toledger."&fromdate=".$fromdate."&todate=".$todate."&message=".$message);



?>