<?php

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


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

set_time_limit(0);

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

$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, Base1, Base2, grid_color1, grid_color2 from setup";
$resultsetup=mysql_query($querysetup,$connection) or die(mysql_error());
while($rowsetup=mysql_fetch_array($resultsetup)){
	extract($rowsetup);
}

//Read From SalesSetup Table
$querySalesSetup="Select SalesTTC From SalesSetup";
$resultSalesSetup=mysql_query($querySalesSetup,$connection) or die(mysql_error());
while($rowSalesSetup=mysql_fetch_array($resultSalesSetup)){
	extract($rowSalesSetup);
}

//Read From Module Table
$querymodule=" Select ifNull(Module_Delivery,0) As Module_Delivery, ".
			 " 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);
}

$MainCompanyName=explode('_',$HTTP_SESSION_VARS['dbName']);

$queryperiod= " Select ifNull(LockViewPeriod,0) As LockViewPeriod, ViewPeriodDate, ifNull(ViewLockDaily,0) As ViewLockDaily, ViewNumberOfDays ".
              " From ".$HTTP_SESSION_VARS['dbLabel'].".ListUserDir  ".
			  " Where Usercode='".$HTTP_SESSION_VARS['useraccount']."' ".
			  " And Upper(CompanyName) = Upper('".$MainCompanyName[0]."') ".
			  " And Upper(Diryear) = Upper('".$MainCompanyName[1]."') ";
			  
$resultperiod = mysql_query($queryperiod,$connection) or die(mysql_error());
$rowsperiod   = mysql_num_rows($resultperiod);

while($rows=mysql_fetch_array($resultperiod)){
	extract($rows);
}	
			  
//echo $queryperiod;	

$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on (($Module_ProjectParent=1 and project.project_code like concat(ifnull(loginstk.project_code,project.project_code),'%')) or ($Module_ProjectParent=0 and project.project_code = loginstk.project_code )) ".
			  " where user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
			  " and (loginstk.project_code is not null and loginstk.project_code != '') ".
			  " order by project.project_code";
$projectresult = mysql_query($queryproject,$connection) or die(mysql_error());
$projectexist  = mysql_num_rows($projectresult);		  

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$HTTP_SESSION_VARS['dbLabel'].".loginstk on (($Module_CostCenterParent=1 and costcent.costcent_code like concat(ifnull(loginstk.costcent_code,costcent.costcent_code),'%')) or ($Module_CostCenterParent=0 and costcent.costcent_code = loginstk.costcent_code )) ".
			   " where user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
			   " and (loginstk.costcent_code is not null and loginstk.costcent_code != '') ".
			   " order by costcent.costcent_code";
$costcentresult = mysql_query($querycostcent,$connection) or die(mysql_error());
$costcentexist  = mysql_num_rows($costcentresult);	  

$queryledger= " select distinct ledger_number, ledger_include ".
              " from ".$HTTP_SESSION_VARS['dbLabel'].".ledgerstk  ".
			  " where user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
			  " and (ledger_number is not null and ledger_number != '') ".
			  " order by ledger_number";
$ledgerresult = mysql_query($queryledger,$connection) or die(mysql_error());
$ledgerexist  = mysql_num_rows($ledgerresult);	
$rows=mysql_fetch_array($ledgerresult) ;
$ledgerinclude = $rows[1];


//Select Data From TransDt For Selected Record
$sub_query = " Select TransDt.Ledger_Number, TransDt.Currency_Code, TransDt.Trans_Date, ifNull(Transdt_Amount1,0), ifNull(Transdt_Amount2,0) ".
			 " From Temp_TransDt As TransDt ".
	         " Where TransDt.TransDt_ID = '".$PTransDtId."' ";
					      
//echo $sub_query;
$sub_result = selectData($connection, $sub_query);

$LedgerNumber    = $sub_result[0];
$TransDtCurr     = $sub_result[1];
$TransDtDate     = $sub_result[2];
$TransDtAmountB1 = $sub_result[3];
$TransDtAmountB2 = $sub_result[4];


print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="default.css" type="text/css" />
<title>List of Invoices</title>
<script type="text/javascript" language="javascript">

function RefreshPage()
{
	document.search.submit();
}

function ClearForm()
{
	document.search.PRef.value='';
	document.search.SelectedRows.value = '';
	document.search.action='Form_Trans_ListInvoices.php';
	document.search.submit();
}

function LoadForm() 
{
	x=document.search;
	x.PRef.focus();
	
	ChangeLocation();
}

function SetNextPage(startrange,perpage){ 
	document.search.action='Form_Trans_ListInvoices.php?PRef=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}

function SetPrvPage(startrange,perpage){
	document.search.action='Form_Trans_ListInvoices.php?PRef=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}



function ChangeLocation()
{
    if (document.search.PMode.value == 1) {
	    opener.document.trans.message.value = document.search.message.value;
		opener.document.trans.submit();
		self.close();
	}	
}
function SelectRecord() {
	var f = document.search;
	
	var MasterCheckName, TotalsName1, TotalsName2, vSelectedRows;
	var x, y, z;
	
	vSelectedRows = '';
	vTotalInvRemainB1 = 0; vTotalInvRemainB2 = 0;
	
	for (var i=1; i <= document.search.i.value; i++)
	{
		MasterCheckName='M'+i;
		x = document.getElementById(MasterCheckName);
		
		TotalsName1='InvoiceRemainB1'+i;
		y = document.getElementById(TotalsName1);
		TotalsName2='InvoiceRemainB2'+i;
		z = document.getElementById(TotalsName2);
		
		if (x.checked) {
			vSelectedRows = vSelectedRows + ',' + x.value;	
			vTotalInvRemainB1 = parseFloat(vTotalInvRemainB1) + parseFloat(y.value);
			vTotalInvRemainB2 = parseFloat(vTotalInvRemainB2) + parseFloat(z.value);
		}
	}
	
	vSelectedRows = vSelectedRows.substr(1);
	document.search.SelectedRows.value = vSelectedRows;
	
	f.InvoiceAmountB1.value = vTotalInvRemainB1;
	f.InvoiceAmountB2.value = vTotalInvRemainB2;
	f.RemainAmountB1.value  = parseFloat(f.TransDtAmountB1.value) - parseFloat(vTotalInvRemainB1);
	f.RemainAmountB2.value  = parseFloat(f.TransDtAmountB2.value) - parseFloat(vTotalInvRemainB2);
	
	f.InvoiceAmountB1_D.value = addCommas(formatNumber(vTotalInvRemainB1,2));
	f.InvoiceAmountB2_D.value = addCommas(formatNumber(vTotalInvRemainB2,2));
	f.RemainAmountB1_D.value  = addCommas(formatNumber(parseFloat(f.TransDtAmountB1.value) - parseFloat(vTotalInvRemainB1),2));
	f.RemainAmountB2_D.value  = addCommas(formatNumber(parseFloat(f.TransDtAmountB2.value) - parseFloat(vTotalInvRemainB2),2));
}

function LoadData(){
	var x = document.search;
	var vSelectedRows = x.SelectedRows.value;
	
	if (vSelectedRows != '') {
		var vTransId    = x.PTransId.value;
		var vTransDtId  = x.PTransDtId.value;
		var vTransType  = x.PTransType.value;
		
		var vRemainAmountB1 = x.RemainAmountB1.value;
		var vRemainAmountB2 = x.RemainAmountB2.value;
		
		var vMainMode = x.mainaction.value;
		
		/*if (vRemainAmountB1 < 0) {
			alert('Total Invoice(s) should be less than or equal to receipt amount.');
		} else {*/
			x.PMode.value=1;	
			x.action="Form_Trans_Actions.php?mode=loadinvoices&mainmode="+vMainMode+"&TransType="+vTransType+"&STransId="+vTransId+"&STransDtId="+vTransDtId+"&SAccLinkId="+vSelectedRows;
			x.submit();
		//}	
	} else
		alert ('Please Select an Invoice.');
	
}

function roundNumber(num, dec) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  newnumber = parseFloat(newnumber); 
  
  return newnumber;
}

function formatNumber(num, dec) { // Arguments: number to format, number of decimal places
	return num.toFixed(dec);
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

</script>

<style type="text/css">

body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
}
body {
	margin-top: 2px;
	margin-left: 1px;
}
a:link {
	text-decoration: none;
	color: #0000FF;
}
a:visited {
	text-decoration: none;
	color: #0000FF;
}
a:hover {
	text-decoration: none;
	color: #0000FF;
}
a:active {
	text-decoration: none;
	color: #0000FF;
}
.style11 {color: #999999; font-weight: bold; }
.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}
.style15 {color: #5151FF; }
.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}
.style25 {color: #999999; font-weight: bold; font-size: 10px; }
.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #000000 ;font-size: 10px;}

</style>

</head>
<body onLoad='LoadForm();'>
<form name='search' method='post' action=''>
<input type='hidden' name='SelectedRows' value='$SelectedRows'>
<input type='hidden' name='mainaction' value='$mainaction'>
<input type='hidden' name='actionmode' value='$actionmode'>

<input type='hidden' name='PTransType' value='$PTransType'>
<input type='hidden' name='PTransId' value='$PTransId'>
<input type='hidden' name='PTransDtId' value='$PTransDtId'>
<input type='hidden' name='TransDtAmountB1' value='$TransDtAmountB1'>
<input type='hidden' name='TransDtAmountB2' value='$TransDtAmountB2'>
<input type='hidden' name='RemainAmountB1' value='$RemainAmountB1'>
<input type='hidden' name='RemainAmountB2' value='$RemainAmountB2'>
<input type='hidden' name='InvoiceAmountB1' value='$InvoiceAmountB1'>
<input type='hidden' name='InvoiceAmountB2' value='$InvoiceAmountB2'>
HERE;
echo "<input type='hidden' name='message' value='".htmlspecialchars($message, ENT_QUOTES)."'>";


echo"<table border='0' cellspacing='1' style='table-layout:fixed' align='center'>
	  <col width=25>
	  <col width=70>
	  <col width=80>
	  <col width=110>
	  <col width=110>
	  <col width=110>
	  <col width=110>
	  <col width=110>
	  <col width=110>
	  <col width=400>
		     
	  <tr bgcolor='#DDDDDD'>
	    <td align='center' colspan='10'><span class='style16'>List of Invoices</span></td></tr>
	  <tr bgcolor='#DDDDDD'>
	    <td align='left' colspan='3'><span class='style11'>Search by Reference</span></td>
		<td align='left' colspan='6'><span class='style11'><input type='text' name='PRef' id='PRef' value='$PRef' size='15' maxlength='30'/><input type='hidden' name='PMode' id='PMode' value='$PMode' size='15' maxlength='30'/></span>
		    <input type='submit' name='btnSubmit' value='Find' style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/>
			<input type='button' name='btnCancel' value='Cancel' onclick='ClearForm();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/>
			<input type='button' name='btnLoad' value='Load' onclick='LoadData();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/>
		</td>
		<td align='left' valign='center' ><span class='style11'>Result per page </span><span class='style11'><select name='perpage' id='perpage' value='$perpage' onchange='RefreshPage();'>";
              

        if ($perpage==20)
			$s20 = 'selected';
		else if ($perpage==30)
			$s30 = 'selected';
		else if ($perpage==40)
			$s40 = 'selected';
		else if ($perpage==50)
			$s50 = 'selected';
			
				
        echo'<option '.$s20.' value="20">20</option>
			 <option '.$s30.' value="30">30</option>
			 <option '.$s40.' value="40">40</option>
			 <option '.$s50.' value="50">50</option>
			 </select></span></td>';	
echo" </tr>";
echo" <tr bgcolor='#DDDDDD'><td colspan='10' align='left'>
		<span class='style11'>Total Receipt $Base1</span>
		<input type='text' name='TransDtAmountB1_D' id='TransDtAmountB1_D' value='".number_format($TransDtAmountB1, $DecimalBase1)."' style='width:120px; text-align:right;' readonly/>	
		<span class='style11'>Total Invoice(s) $Base1</span>
		<input type='text' name='InvoiceAmountB1_D' id='InvoiceAmountB1_D' value='".number_format($InvoiceAmountB1, $DecimalBase1)."' style='width:120px; text-align:right;' readonly/>	
		<span class='style11'>Remain Amount $Base1</span>
		<input type='text' name='RemainAmountB1_D' id='RemainAmountB1_D' value='".number_format(($TransDtAmountB1-$InvoiceAmountB1), $DecimalBase1)."' style='width:120px; text-align:right;' readonly/>	
	  </td></tr>";
echo" <tr bgcolor='#DDDDDD'><td colspan='10' align='left'>
		<span class='style11'>Total Receipt $Base2</span>
		<input type='text' name='TransDtAmountB2_D' id='TransDtAmountB2_D' value='".number_format($TransDtAmountB2, $DecimalBase2)."' style='width:120px; text-align:right;' readonly/>	
		<span class='style11'>Total Invoice(s) $Base2</span>
		<input type='text' name='InvoiceAmountB2_D' id='InvoiceAmountB2_D' value='".number_format($InvoiceAmountB2, $DecimalBase2)."' style='width:120px; text-align:right;' readonly/>	
		<span class='style11'>Remain Amount $Base2</span>
		<input type='text' name='RemainAmountB2_D' id='RemainAmountB2_D' value='".number_format(($TransDtAmountB2-$InvoiceAmountB2), $DecimalBase2)."' style='width:120px; text-align:right;' readonly/>	
	  </td></tr>";
	  
	  
//echo" <tr bgcolor='#DDDDDD'><td colspan='10' align='center'><input type='button' name='btnLoad' value='Load' onclick='LoadData();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/></td></tr>";
echo" <tr bgcolor='#DDDDDD'>
		<td height='15' align='center' colspan='10'><font size='1' color='#FF0000' face='Verdana'><b>".$message."</b></font></td>
	  </tr>	
	  <tr bgcolor='#CCD8E6'>
		<td  height='25' align='center'><span class='style25'>&nbsp;</span></td>
		<td  height='25' align='left'><span class='style25'>Reference </span></td>
		<td  height='25' align='center'><span class='style25'>Date </span></td>
		<td  height='25' align='center'><span class='style25'>NetTotal $Base1</span></td>
		<td  height='25' align='center'><span class='style25'>PaidAmount $Base1</span></td>
		<td  height='25' align='center'><span class='style25'>RemainAmount $Base1</span></td>
		<td  height='25' align='center'><span class='style25'>NetTotal $Base2</span></td>
		<td  height='25' align='center'><span class='style25'>PaidAmount $Base2</span></td>
		<td  height='25' align='center'><span class='style25'>RemainAmount $Base2</span></td>
		<td  height='25' align='left'><span class='style25'>Remark</span></td>";
echo" </tr>";
		



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

if (empty($ViewPeriodDate))
   $ViewPeriodDate = 'Null';
if (empty($ViewNumberOfDays))   
   $ViewNumberOfDays = 1;
   

   
$vMainCompanyName=explode('_',$_SESSION['dbName']);  
$DirCompany  = $vMainCompanyName[0];
$DirYear	 = $vMainCompanyName[1];
   
$query = '';
$query = $query." Select InvoiceID, InvoiceDate, OrderInvoiceDate, InvoiceRefer, InvoiceTotalBase1, InvoiceTotalBase2, ".
				" TransPaidBase1, TransPaidBase2, TransRemBase1, TransRemBase2, InvoiceRemark ";
	
$query = $query." From ( ";

if(($PTransType == 'RV' || $PTransType == 'CV') && $Module_Delivery == 0 ) {
	$query = $query." Select Deliveries.Delivery_ID As InvoiceID, date_format(Deliveries.Delivery_Date,'%d/%m/%Y') As InvoiceDate, Deliveries.Delivery_Date As OrderInvoiceDate, Deliveries.Delivery_Reference As InvoiceRefer, ".
					" ifNull(AccLink.Sale_NetTotalBase1,0) As InvoiceTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As InvoiceTotalBase2, ".
					" Sum(ifNull(AccLink.Sale_PaidAmntBase1,0)) As TransPaidBase1, Sum(ifNull(AccLink.Sale_PaidAmntBase2,0)) As TransPaidBase2, ".
					" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As TransRemBase1, ".
					" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As TransRemBase2, ".
					" Deliveries.Delivery_Remark as InvoiceRemark ".
					" From Deliveries ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink on Deliveries.Delivery_ID = Acclink.Link_ID ";
					//" Inner Join TransDt on Acclink.Journal_Id = TransDt.Transdt_Id And Acclink.Journal_Type = '".$PTransType."' ".
					//" Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ";
					
	if ($projectexist >	0) {
		$query = $query." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (project_code is not null and project_code != '') ".
						"			 ) Q1 on (($Module_ProjectParent=1 and Deliveries.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Deliveries.project_code = Q1.project_code )) ";
	}
	if ($costcentexist > 0) {
		$query = $query." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (costcent_code is not null and costcent_code != '') ".
						"			) Q2 on (($Module_CostCenterParent=1 and Deliveries.Costcent_Code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Deliveries.Costcent_Code = Q2.costcent_code )) ";							 
	}				
	
	$query = $query." Where Deliveries.Delivery_Reference Like Concat(ifNull($PRef, Deliveries.Delivery_Reference), '%') ".
					" And Deliveries.Client_Code = '".$LedgerNumber."' ".
					" And Deliveries.Journal_Type = 'DI' ".
					" And Deliveries.Delivery_Date <= '".$TransDtDate."' ".
					" And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
					//" And Trans.Trans_Type In ('RV','CV') ".
					" And Acclink.Journal_Type In ('RV','CV') ".
					" And Acclink.Link_Type In ('DI','SI') ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" And Round(ifNull(AccLink.Sale_RemainAmntBase1,0),0) > 0 ".
					" And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Deliveries.Delivery_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
					"                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ".
					" Group By InvoiceID, InvoiceDate, InvoiceRefer ".
					" Union ".
					" Select Deliveries.Delivery_ID As InvoiceID, date_format(Deliveries.Delivery_Date,'%d/%m/%Y') As InvoiceDate, Deliveries.Delivery_Date As OrderInvoiceDate, Deliveries.Delivery_Reference As InvoiceRefer, ".
					" (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As InvoiceTotalBase1, ".
					" (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As InvoiceTotalBase2, ".
					" 0 As TransPaidBase1, 0 As TransPaidBase2, ".
					" (ifNull(Deliveries.Delivery_TotalBase1,0) - ifNull(Deliveries.Delivery_DiscountBase1,0) + ifNull(Deliveries.Delivery_VatBase1,0)) As TransRemBase1, ".
					" (ifNull(Deliveries.Delivery_TotalBase2,0) - ifNull(Deliveries.Delivery_DiscountBase2,0) + ifNull(Deliveries.Delivery_VatBase2,0)) As TransRemBase2, ".
					" Deliveries.Delivery_Remark as InvoiceRemark ".
					" From Deliveries ";
					
	if ($projectexist >	0) {
		$query = $query." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (project_code is not null and project_code != '') ".
						"			 ) Q1 on (($Module_ProjectParent=1 and Deliveries.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Deliveries.project_code = Q1.project_code )) ";
	}
	if ($costcentexist > 0) {
		$query = $query." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (costcent_code is not null and costcent_code != '') ".
						"			) Q2 on (($Module_CostCenterParent=1 and Deliveries.Costcent_Code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Deliveries.Costcent_Code = Q2.costcent_code )) ";							 
	}
	
	$query = $query." Where Deliveries.Delivery_Reference Like Concat(ifNull($PRef, Deliveries.Delivery_Reference), '%') ".
					" And Deliveries.Client_Code = '".$LedgerNumber."' ".
					" And Deliveries.Journal_Type = 'DI' ".
					" And Deliveries.Delivery_Date <= '".$TransDtDate."' ".
					" And IfNull(Deliveries.Delivery_OldData,0) = 0 ".
					" And Deliveries.Delivery_ID Not In (Select ifNull(Link_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                			         Where Acclink.Link_Type In ('DI','SI') ".
					" 						  			 And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" 				                     And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ".
					" And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Deliveries.Delivery_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
					"                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Deliveries.Delivery_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ";
					
} 
else if(($PTransType == 'RV' || $PTransType == 'CV') && $Module_Delivery == 1 ) {
	$query = $query." Select Sales.Sale_ID As InvoiceID, date_format(Sales.Sale_Date,'%d/%m/%Y') As InvoiceDate, Sales.Sale_Date As OrderInvoiceDate, Sales.Sale_Reference As InvoiceRefer, ".
					" ifNull(AccLink.Sale_NetTotalBase1,0) As InvoiceTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As InvoiceTotalBase2, ".
					" Sum(ifNull(AccLink.Sale_PaidAmntBase1,0)) As TransPaidBase1, Sum(ifNull(AccLink.Sale_PaidAmntBase2,0)) As TransPaidBase2, ".
					" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As TransRemBase1, ".
					" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As TransRemBase2, ".
					" Sales.Sale_Remark as InvoiceRemark ".
					" From Sales ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink on Sales.Sale_ID = Acclink.Link_ID ";
					//" Inner Join TransDt on Acclink.Journal_Id = TransDt.Transdt_Id And Acclink.Journal_Type = '".$PTransType."' ".
					//" Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ";
					
	if ($projectexist >	0) {
		$query = $query." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (project_code is not null and project_code != '') ".
						"			 ) Q1 on (($Module_ProjectParent=1 and Sales.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Sales.project_code = Q1.project_code )) ";
	}
	if ($costcentexist > 0) {
		$query = $query." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (costcent_code is not null and costcent_code != '') ".
						"			) Q2 on (($Module_CostCenterParent=1 and Sales.Costcenter_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Sales.Costcenter_code = Q2.costcent_code )) ";
	}
	
	/* $query = $query." Where Sales.Sale_Reference Like Concat(ifNull($PRef, Sales.Sale_Reference), '%') ".
					" And Sales.Client_Code = '".$LedgerNumber."' ".
					" And Sales.Journal_Type = 'SI' ".
					" And Sales.Sale_Date <= '".$TransDtDate."' ".
					" And IfNull(Sales.Sale_OldData,0) = 0 ".
					//" And Trans.Trans_Type In ('RV','CV') ".
					" And Acclink.Journal_Type In ('RV','CV') ".
					" And Acclink.Link_Type In ('DI','SI') ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" And Round(ifNull(AccLink.Sale_RemainAmntBase1,0),0) > 0 ".
					" And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Sales.Sale_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Sales.Sale_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
					"                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Sales.Sale_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ".
	 */$query = $query.				" Group By InvoiceID, InvoiceDate, InvoiceRefer ".
					" Union ".
					" Select Sales.Sale_ID As InvoiceID, date_format(Sales.Sale_Date,'%d/%m/%Y') As InvoiceDate, Sales.Sale_Date As OrderInvoiceDate, Sales.Sale_Reference As InvoiceRefer, ".
					" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As InvoiceTotalBase1, ".
					" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As InvoiceTotalBase2, ".
					" 0 As TransPaidBase1, 0 As TransPaidBase2, ".
					" (ifNull(Sales.Sale_TotalBase1,0) - ifNull(Sales.Sale_DiscountBase1,0) + ifNull(Sales.Sale_VATBase1,0)) As TransRemBase1, ".
					" (ifNull(Sales.Sale_TotalBase2,0) - ifNull(Sales.Sale_DiscountBase2,0) + ifNull(Sales.Sale_VATBase2,0)) As TransRemBase2, ".
					" Sales.Sale_Remark as InvoiceRemark ".
					" From Sales ";
					
	if ($projectexist >	0) {
		$query = $query." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (project_code is not null and project_code != '') ".
						"			 ) Q1 on (($Module_ProjectParent=1 and Sales.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Sales.project_code = Q1.project_code )) ";
	}
	if ($costcentexist > 0) {
		$query = $query." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (costcent_code is not null and costcent_code != '') ".
						"			) Q2 on (($Module_CostCenterParent=1 and Sales.Costcenter_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Sales.Costcenter_code = Q2.costcent_code )) ";
	}
	
	/* $query = $query." Where Sales.Sale_Reference Like Concat(ifNull($PRef, Sales.Sale_Reference), '%') ".
					" And Sales.Client_Code = '".$LedgerNumber."' ".
					" And Sales.Journal_Type = 'SI' ".
					" And Sales.Sale_Date <= '".$TransDtDate."' ".
					" And IfNull(Sales.Sale_OldData,0) = 0 ".
					" And Sales.Sale_ID Not In ( Select ifNull(Link_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                            Where Acclink.Link_Type In ('DI','SI') ".
					" 							 And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					"                            And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ".
					" And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Sales.Sale_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Sales.Sale_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
					"                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Sales.Sale_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ";
					 */
}
else if ($PTransType == 'PV' || $PTransType == 'DV') {
	$query = $query." Select Purchases.Purchase_ID As InvoiceID, date_format(Purchases.Purchase_Date,'%d/%m/%Y') As InvoiceDate, Purchases.Purchase_Date As OrderInvoiceDate, Purchases.Purchase_Reference As InvoiceRefer, ".
					" ifNull(AccLink.Sale_NetTotalBase1,0) As InvoiceTotalBase1, ifNull(AccLink.Sale_NetTotalBase2,0) As InvoiceTotalBase2, ".
					" Sum(ifNull(AccLink.Sale_PaidAmntBase1,0)) As TransPaidBase1, Sum(ifNull(AccLink.Sale_PaidAmntBase2,0)) As TransPaidBase2, ".
					" (ifNull(AccLink.Sale_NetTotalBase1,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase1,0) + ifNull(AccLink.Sale_ReturnAmntBase1,0))) As TransRemBase1, ".
					" (ifNull(AccLink.Sale_NetTotalBase2,0) - Sum(ifNull(AccLink.Sale_PaidAmntBase2,0) + ifNull(AccLink.Sale_ReturnAmntBase2,0))) As TransRemBase2, ".
					" Purchases.Purchase_Remark as InvoiceRemark ".
					" From Purchases ".
					" Inner Join ".$HTTP_SESSION_VARS['dbLabel'].".Acclink on Purchases.Purchase_ID = Acclink.Link_ID ";
					//" Inner Join TransDt on Acclink.Journal_Id = TransDt.Transdt_Id And Acclink.Journal_Type = '".$PTransType."' ".
					//" Inner Join Trans on TransDt.Trans_Id = Trans.Trans_Id ";
					
	if ($projectexist >	0) {
		$query = $query." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (project_code is not null and project_code != '') ".
						"			 ) Q1 on (($Module_ProjectParent=1 and Purchases.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Purchases.project_code = Q1.project_code )) ";
	}
	if ($costcentexist > 0) {
		$query = $query." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (costcent_code is not null and costcent_code != '') ".
						"			) Q2 on (($Module_CostCenterParent=1 and Purchases.Costcent_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Purchases.Costcent_code = Q2.costcent_code )) ";
	}
	
	$query = $query." Where Purchases.Purchase_Reference Like Concat(ifNull($PRef, Purchases.Purchase_Reference), '%') ".
					" And Purchases.Supplier_Code = '".$LedgerNumber."' ".
					" And Purchases.Journal_Type = 'PI' ".
					" And Purchases.Purchase_Date <= '".$TransDtDate."' ".
					" And IfNull(Purchases.Purchase_OldData,0) = 0 ".
					//" And Trans.Trans_Type In ('PV','DV') ".
					" And Acclink.Journal_Type In ('PV','DV') ".
					" And Acclink.Link_Type = 'PI' ".
					" And upper(Acclink.CompanyName) = upper('".$DirCompany."') ".
					" And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					" And Round(ifNull(AccLink.Sale_RemainAmntBase1,0),0) > 0 ".
					" And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Purchases.Purchase_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Purchases.Purchase_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
					"                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Purchases.Purchase_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ".
					" Group By InvoiceID, InvoiceDate, InvoiceRefer ".
					" Union ".
					" Select Purchases.Purchase_ID As InvoiceID, date_format(Purchases.Purchase_Date,'%d/%m/%Y') As InvoiceDate, Purchases.Purchase_Date As OrderInvoiceDate, Purchases.Purchase_Reference As InvoiceRefer, ".
					" (ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0)) As InvoiceTotalBase1, ".
					" (ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0)) As InvoiceTotalBase2, ".
					" 0 As TransPaidBase1, 0 As TransPaidBase2, ".
					" (ifNull(Purchases.Purchase_TotalBase1,0) - ifNull(Purchases.Purchase_DiscountBase1,0) + ifNull(Purchases.Purchase_VATBase1,0)) As TransRemBase1, ".
					" (ifNull(Purchases.Purchase_TotalBase2,0) - ifNull(Purchases.Purchase_DiscountBase2,0) + ifNull(Purchases.Purchase_VATBase2,0)) As TransRemBase2, ".
					" Purchases.Purchase_Remark as InvoiceRemark ".
					" From Purchases ";
					
	if ($projectexist >	0) {
		$query = $query." Inner join ( select distinct project_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (project_code is not null and project_code != '') ".
						"			 ) Q1 on (($Module_ProjectParent=1 and Purchases.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Purchases.project_code = Q1.project_code )) ";
	}
	if ($costcentexist > 0) {
		$query = $query." Inner join ( select distinct costcent_code from ".$HTTP_SESSION_VARS['dbLabel'].".loginstk ".
						"			   where loginstk.user_account='".$HTTP_SESSION_VARS['useraccount']."' ".
						"              and (costcent_code is not null and costcent_code != '') ".
						"			) Q2 on (($Module_CostCenterParent=1 and Purchases.Costcent_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Purchases.Costcent_code = Q2.costcent_code )) ";
	}
	
	$query = $query." Where Purchases.Purchase_Reference Like Concat(ifNull($PRef, Purchases.Purchase_Reference), '%') ".
					" And Purchases.Supplier_Code = '".$LedgerNumber."' ".
					" And Purchases.Journal_Type = 'PI' ".
					" And Purchases.Purchase_Date <= '".$TransDtDate."' ".
					" And IfNull(Purchases.Purchase_OldData,0) = 0 ".
					" And Purchases.Purchase_ID Not In (Select ifNull(Link_ID,-1) From ".$HTTP_SESSION_VARS['dbLabel'].".Acclink  ".
					"                          		    Where Acclink.Link_Type = 'PI' ".
					" 							    	And upper(Acclink.Link_DirYear) = upper('".$DirYear."') ".
					"                               	And upper(Acclink.CompanyName) = upper('".$DirCompany."') ) ".
					" And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Purchases.Purchase_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Purchases.Purchase_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
					"                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Purchases.Purchase_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ";
}
				
$query = $query." ) As Q1 ";
$query = $query." Order by OrderInvoiceDate, InvoiceRefer  ";
	
//echo $query;
// exit;   

			 

if ($PMode != '1') {
$result=mysql_query($query,$connection) or die(mysql_error());
$totalrows = mysql_num_rows($result);
	
if ($startrange=='' || $PRef != 'Null')
	$startrange = 0;
if ($perpage=='')
	$perpage = 20;
		
$query = $query." limit ".$startrange.",".$perpage;

$result=mysql_query($query,$connection) or die(mysql_error());	
	

$i = 0;

while($rows=mysql_fetch_array($result)){
		
	extract($rows);
	$ct+=1;
	$i = $i + 1;

	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
	
	
	echo'<tr '.$Color.'>';
			
    $SelMaster  = 'M'.$i;
	$$SelMaster = $InvoiceID;

	echo"	<td align='center'><span class='style15'>
				<input type='hidden' name='InvoiceRemainB1$i' id='InvoiceRemainB1$i' value='$TransRemBase1'>
				<input type='hidden' name='InvoiceRemainB2$i' id='InvoiceRemainB2$i' value='$TransRemBase2'>
				<input type='checkbox' name='$SelMaster' id='$SelMaster' value='".$$SelMaster."' onclick=\"SelectRecord();\" /></span>
			</td>";
	echo'	<td align="left"><span class="style15">'.$InvoiceRefer.'</span></td>
			<td align="center"><span class="style15">'.$InvoiceDate.'</span></td>
			<td align="right"><span class="style15">'.number_format($InvoiceTotalBase1, $DecimalBase1).'</span></td>
			<td align="right"><span class="style15">'.number_format($TransPaidBase1, $DecimalBase1).'</span></td>
			<td align="right"><span class="style15">'.number_format($TransRemBase1, $DecimalBase1).'</span></td>
			<td align="right"><span class="style15">'.number_format($InvoiceTotalBase2, $DecimalBase2).'</span></td>
			<td align="right"><span class="style15">'.number_format($TransPaidBase2, $DecimalBase2).'</span></td>
			<td align="right"><span class="style15">'.number_format($TransRemBase2, $DecimalBase2).'</span></td>
			<td align="left"><span class="style15">'.$InvoiceRemark.'</span></td>';
	echo'</tr>';
		

}
							
echo "<input type='hidden' name='i' value='$i'>";

if (!empty($LedgerNumber)) {
	echo"   <tr bgcolor='#DDDDDD'><td colspan='10' align='center'><input type='button' name='btnLoad' value='Load' onclick='LoadData();'style=' background-color:#4069A7; color:#FFFFFF;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:12px;'/></td></tr>";
}			
		
echo"   <tr><td colspan='10'>&nbsp;</td></tr>
		<tr><td colspan='10'><table width='100%' border=0><tr><td width='230'>&nbsp;</td><td width='150' align='center'>";
		
		$diff= $startrange - $perpage;
		
		if (($diff) >= 0 ){
			$prvstartrange = $startrange - $perpage;
			echo"<img src='img/arrowleft.jpg' title='Previous' onMouseOver=\"style.cursor='hand'\"  onclick=SetPrvPage('".$prvstartrange."','".$perpage."')>";
		}
		else
			echo "&nbsp;";
		
		echo"</td><td width='150' align='center'>";
		
		
		if ($startrange <= $totalrows){
			$startrange = $startrange + $perpage;
			if  ($startrange <= $totalrows)
				echo"<img src='img/arrowright.jpg' title='Next' onMouseOver=\"style.cursor='hand'\" onclick=SetNextPage('".$startrange."','".$perpage."')>";
		} else
			echo "&nbsp;";
			
		echo"</td><td width='230'>&nbsp;</td></tr>";
		echo"</table>";
		
}		

echo"</td></tr></table>";
	


print <<<HERE

</form>
</body>

HERE;

?>