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

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


if(	$_SESSION['encodingmode'] == 'utf8' || $_SESSION['encodingmode'] == 'utf-8'){
	mysql_query("SET NAMES 'utf8'"); 
	mysql_query('SET CHARACTER SET utf8'); 
	mysql_set_charset('utf8', $connection);
}
$queryledger= " select distinct ledger_number, ledger_include ".
              " from ".$_SESSION['dbLabel'].".ledgerstk  ".
			  " where user_account='".$_SESSION['useraccount']."' ".
			  " 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];

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

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


$index 	   	= $_GET['index']; if ($index == ""){$index = $_POST["index"];}
$CashBank  	= $_GET['CashBank']; if ($CashBank == ""){$CashBank = $_POST["CashBank"];}
$TransType 	= $_GET['TransType']; if ($TransType == ""){$TransType = $_POST["TransType"];}

$str   		= $_GET['str']; if ($str == ""){$str = $_POST["str"];}
$startrange = $_GET['startrange'];if ($startrange == ""){$startrange = $_POST["startrange"];}
$perpage  	= $_GET['perpage'];if ($perpage == ""){$perpage = $_POST["perpage"];}

$PRef   = $_POST["PRef"]; if ($PRef == ""){$PRef = $_GET["PRef"];}  
$PMode  = $_POST["PMode"]; if ($PMode == ""){$PMode = $_GET["PMode"];}  


if($str=='4' || $str=='5' || $str=='6' || $str ==8 || $str ==9 || $str ==10 || $str ==11 || $str ==12 || $str ==13 || $str ==14 || $str ==15 || $str ==16 || $str ==17 || $str ==22 || $str ==23 || $str ==26) {
	$title='Search Ledgers';
	$label='List of Ledgers';
}

else {
	$title='Search Agents';
	$label='List of Agents';
}
		


if ($TransType == 'PV') {
	$ModuleCashBank = $Module_CashBankPV;
}	 
else if ($TransType == 'RV') {
	$ModuleCashBank = $Module_CashBankRV;
}	
else {
	$ModuleCashBank = 0;
}

print <<<HERE
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>$title</title>
<script type="text/javascript" language="javascript">


function fillfield(value1,value2,value3,value4,value5){

	var str     = document.search.str.value;
	var vIndex	= document.search.index.value; 

	if(str=='1'){
		opener.document.clientdt.agent_code.value=value1;
		opener.document.clientdt.agent_name.value=value2;
		
	}

	if(str=='2'){
		opener.document.AccType.ledger_code.value=value1;
		opener.document.AccType.ledger_name.value=value2;
	}
	
	if(str=='3'){
		opener.document.AccType.ledger_number.value=value1;
	}

	if(str=='4'){
		opener.document.journal.ledger_number.value=value1;
		opener.document.journal.ledger_name.value=value2;
		opener.document.journal.message.value='';
		opener.document.journal.submit();
	}
	
	if(str=='5'){
		opener.document.transdt.txtLedgerNo.value=value1;
		opener.document.transdt.txtLedgerName.value=value2;
	}
	
	if(str=='6'){
		opener.document.FinancialReportDt.ledgerNbr.value=value1;
		opener.document.FinancialReportDt.ledgerName.value=value2;
	}
	if(str=='7'){
		opener.document.salesman.client_code.value=value1;
		opener.document.salesman.client_name.value=value2;
	}
	if(str=='8'){
		opener.document.Grouping.vat_account.value=value1;
		opener.document.Grouping.vat_accountname.value=value2;
	}
	if(str=='9'){
		opener.document.Grouping.rawmat_account.value=value1;
		opener.document.Grouping.rawmat_accountname.value=value2;
	}
	if(str=='10'){
		opener.document.Grouping.nonrawmat_account.value=value1;
		opener.document.Grouping.nonrawmat_accountname.value=value2;
	}
	if(str=='11'){
		opener.document.Grouping.rawmatttc_account.value=value1;
		opener.document.Grouping.rawmatttc_accountname.value=value2;
	}
	if(str=='12'){
		opener.document.Grouping.nonrawmatttc_account.value=value1;
		opener.document.Grouping.nonrawmatttc_accountname.value=value2;
	}
	if(str=='13'){
		opener.document.Grouping.rawmat_account2.value=value1;
		opener.document.Grouping.rawmat_accountname2.value=value2;
	}
	if(str=='14'){
		opener.document.Grouping.nonrawmat_account2.value=value1;
		opener.document.Grouping.nonrawmat_accountname2.value=value2;
	}
	if(str=='15'){
		opener.document.Grouping.debit_account.value=value1;
		opener.document.Grouping.debit_accountname.value=value2;
	}
	if(str=='16'){
		opener.document.Grouping.credit_account.value=value1;
		opener.document.Grouping.credit_accountname.value=value2;
	}
	if(str=='17'){
		opener.document.Grouping.disc_account.value=value1;
		opener.document.Grouping.disc_accountname.value=value2;
	}
	if(str=='25'){
		opener.document.Grouping.tips_account.value=value1;
		opener.document.Grouping.tips_accountname.value=value2;
	}
	if(str=='18'){
		opener.document.bank.ledger_number.value=value1;
		opener.document.bank.ledger_name.value=value2;
	
	}
	if(str=='19'){
		opener.document.clientdt.profit_code.value=value1;
		opener.document.clientdt.profit_name.value=value2;
	}
	if(str=='20'){
		opener.document.useraccess.ledger_code.value=value1;
		opener.document.useraccess.ledger_name.value=value2;
	}
	if(str=='21'){
		opener.document.useraccess.ledgerrep_code.value=value1;
		opener.document.useraccess.ledgerrep_name.value=value2;
	}
	if (str == 22){
		opener.document.getElementById('ledgernumber['+vIndex+']').value=value1;
		opener.document.getElementById('ledgername['+vIndex+']').value=value2;
		opener.document.getElementById('currencycode['+vIndex+']').value=value4;
		opener.document.getElementById('journaldtactivity['+vIndex+']').value=value5;
		opener.document.getElementById('ledgernumber['+vIndex+']').focus();
	}
	if (str == 23){
		opener.document.getElementById('ledgernumber2['+vIndex+']').value=value1;
		opener.document.getElementById('ledgername2['+vIndex+']').value=value2;
		opener.document.getElementById('currencycode2['+vIndex+']').value=value4;
		opener.document.getElementById('ledgernumber2['+vIndex+']').focus();
	}
	if(str == 24){
		opener.document.cashpay.txtLedgerNo.value=value1;
		opener.document.cashpay.txtLedgerName.value=value2;
	}
	if(str == 26){
		opener.document.salesman.salesman_cashaccount.value=value1;
		opener.document.salesman.salesman_cashdesc.value=value2;
	}

	self.close();
}

function clearform()
{
  document.search.PRef.value='';
  document.search.action='List_Agents_orderbycode.php';
  document.search.submit();

}

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

}

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

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




function Viewclient(value1,value2){



opener.document.clientdt.agent_code.value=value1;
opener.document.clientdt.agent_name.value=value2;
opener.document.clientdt.keepcompany.value=1;
opener.clientdt.submit();


self.close();
}
function chkFilterByPer(){
	if(document.getElementById('chk_filter_by_per').checked){
		document.getElementById('filter_by_per').value = 1;
	}
	else{
		document.getElementById('filter_by_per').value = 0;
	}
}

</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:visited {
	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 >
<form name='search' method='post' action=''>
<input type='hidden' name='str'  value='$str'>

HERE;

echo"<input type='hidden' name='index' value='".$index."'>";
echo"<input type='hidden' name='CashBank' value='".$CashBank."'>";
echo"<input type='hidden' name='TransType' value='".$TransType."'>";
if($filter_by_per == "") { 
$filter_by_per = 1;
}
if($filter_by_per == 1){
	$checked = "checked";
}
else{
	$checked = "";
}
echo"<table border='0' style='table-layout:fixed'>

	  <col width=3%>
	  <col width=15%>
	  <col width=76%>
	
		     
	  <tr bgcolor='#DDDDDD'>
	    <td align='center' colspan='3'><span class='style16'>$label</span></td></tr>
	  <tr bgcolor='#DDDDDD' height=30px>
	    <td align='left' colspan='2'><span class='style11'>Search by Code/Name</span></td>
		<td align='left' colspan='1'><span class='style11'><input type='hidden' name='filter_by_per' id='filter_by_per' value='$filter_by_per' /><input type='checkbox' name='chk_filter_by_per' id='chk_filter_by_per' onclick=\"chkFilterByPer()\" $checked /> % <input type='text' name='PRef' id='PRef' value='$PRef' size='15' autofocus maxlength='30'/><input type='hidden' name='PMode' id='PMode' value='$PMode' size='15' maxlength='30'/></span>
		    <input type='submit' name='Submit' 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;'/></td>
		";
echo" </tr>
	  <tr bgcolor='#DDDDDD'>
		<td height='15' align='center' colspan='3'><font size='1' color='#FF0000' face='Verdana'><b>".$message."</b></font></td>
	  </tr>	
	  <tr bgcolor='#CCD8E6'>
	  
	
		<td  height='25' align='left' width=10% colspan=2><span class='style25'>Code </span></td>
		<td  height='25' align='center'><span class='style25'>Name </span></td>
		
	  </tr>";
		

	
if ($str == 4 || $str==5) {
	$querysearch="select ledger.ledger_number,ledger_name,Ledger_grpdet, ledger.currency_code, ledger_activity from ledger";
	
	
	/*if($ledgerinclude== 1)
		$querysearch=$querysearch." inner join ( select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk ".
								  " where ledgerstk.user_account='".$_SESSION['useraccount']."') Q1 on ledger.ledger_number like concat(Q1.ledger_number,'%')";*/
	
	//	if($ledgerinclude== 0)
	//	$querysearch=$querysearch." inner join ( select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk ".
	//									  " where ledgerstk.user_account='".$_SESSION['useraccount']."') Q1 on ledger.ledger_number <> concat(Q1.ledger_number,'%')";
	
	
	$querysearch=$querysearch." where Ledger_grpdet=0";
	
	if ($Module_BelongsToGroup == 1)			 
		$querysearch= $querysearch." And ifNull(ledger.Ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
		
	if($ledgerinclude== 1)
		$querysearch=$querysearch." And Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								  "              where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								  "              and ledger.ledger_number like concat(ledgerstk.ledger_number,'%') ".
								  "            ) ";

	if($ledgerinclude== 0)
		$querysearch=$querysearch." And Not Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								  "                  where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								  "                  and ledger.ledger_number like concat(ledgerstk.ledger_number,'%') ".
								  "                ) ";
	
	$querysearch=$querysearch." And ((ifNull(ledger.Ledger_inactive,0) = 0 and 1 = 1) Or (ifNull(ledger.Ledger_inactive,0) = 1 and ifNull(Date_Format(ledger.Ledger_inactivedate,'%Y%m%d'), Date_Format(now(),'%Y%m%d')) >= Date_Format(now(),'%Y%m%d')) )  ";
	$querysearch=$querysearch." and (ledger_number like ".GetSQLValueString('%'.$PRef.'%','text')." or ledger_name like ".GetSQLValueString('%'.$PRef.'%','text').") order by ledger_number";
}
	
else{
	if ($str == 1 || $str==7)
		$querysearch="select ledger_number,ledger_name from ledger where Ledger_grpdet=0 and ledger_type=1";
	else if ($str == 2 || $str == 3  || $str ==18 || $str ==19 )
		$querysearch="select ledger_number,ledger_name,ledger_type from ledger where Ledger_grpdet=1 ";	
	else if ($str == 22 || $str == 27 || $str == 24 || $str == 26 || $str ==8 || $str ==9 || $str ==10 || $str ==11 || $str ==12 || $str ==13 || $str ==14 || $str ==15 || $str ==16 || $str ==17 || $str ==25)
		$querysearch="select ledger_number,ledger_name,ledger_type,ledger.currency_code, ledger_activity from ledger where Ledger_grpdet=0 ";
	else if ($str == 6 || $str==20 || $str==21)
		$querysearch="select ledger_number,ledger_name from ledger where 1 = 1 ";
	else if ($str == 23) {
		$querysearch="select ledger_number,ledger_name,ledger_type,ledger.currency_code from ledger ";
		
		if ($ModuleCashBank == 1 && $CashBank != "" && $TransType != "") {
			$querysearch .= " Inner Join JourTypeButton on Ledger.Ledger_Number Between JourTypeButton.Ledger_NumberFrom and JourTypeButton.Ledger_NumberTo ".
							" And JourType_code = '".$TransType."' ".
							" And ifNull(JourTypeButton_CashBank,0) = $CashBank ";
		}
		
		$querysearch .= " where Ledger_grpdet=0 ";
	}

	if ($Module_BelongsToGroup == 1)			 
		$querysearch= $querysearch." And ifNull(ledger.Ledger_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
		
	if($ledgerinclude== 1)
		$querysearch=$querysearch." And Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								  "              where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								  "              and ledger.ledger_number like concat(ledgerstk.ledger_number,'%') ".
								  "            ) ";

	if($ledgerinclude== 0)
		$querysearch=$querysearch." And Not Exists ( select 1 from ".$_SESSION['dbLabel'].".ledgerstk ".
								  "                  where ledgerstk.user_account='".$_SESSION['useraccount']."' ".
								  "                  and ledger.ledger_number like concat(ledgerstk.ledger_number,'%') ".
								  "                ) ";	
	
	$querysearch=$querysearch." And ((ifNull(ledger.Ledger_inactive,0) = 0 and 1 = 1) Or (ifNull(ledger.Ledger_inactive,0) = 1 and ifNull(Date_Format(ledger.Ledger_inactivedate,'%Y%m%d'), Date_Format(now(),'%Y%m%d')) >= Date_Format(now(),'%Y%m%d')) )  ";
	if($filter_by_per == 1){
	$querysearch=$querysearch." and (ledger_number like ".GetSQLValueString('%'.$PRef.'%','text')." or ledger_name like ".GetSQLValueString('%'.$PRef.'%','text').") order by ledger_number";
	}
	else{
		$querysearch=$querysearch." and (ledger_number = '$PRef' or ledger_name = '$PRef') order by ledger_number";
	}


}
//echo$querysearch;
$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());
$totalrows = mysql_num_rows($resultsearch);
	
if ($startrange=='')
	$startrange = 0;
if ($perpage=='')
	$perpage = 20;
		
$querysearch = $querysearch." limit ".$startrange.",".$perpage;
$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());		


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

	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
			




$desc=ereg_replace("'","%27",$rows[1]);

  echo"<tr $Color>";
  
  print<<<HERE
      <td align='left' colspan=2><a onclick="fillfield('$rows[0]','$desc','$rows[2]','$rows[3]','$rows[4]');" href='#'>$rows[0]</a></td>
	  
      <td ><a onclick="fillfield('$rows[0]','$desc','$rows[2]','$rows[3]','$rows[4]');" href='#'>$rows[1]</a></td>
     
    </tr>

HERE;
}
							
//<td height="20" align="left"><a href="#" onClick="SelectRef('.$Purchase_ID.');" class="style15"><span class="style15 style17" style="text-decoration:underline;">'.$Purchase_Reference.'</span></a></td>			
			
		
echo"   <tr><td colspan='3'>&nbsp;</td></tr>
		<tr><td colspan=3><table width='100%' border=0><tr><td width='260'>&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='170'>&nbsp;</td></tr>";
		echo"<table>";

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


          

		  

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

HERE;

?>