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

$fromdate   =$_POST["fromdate"];
$todate     =$_POST["todate"];

if ($fromdate == '')
	$fromdate = date('01/m/Y');

if ($todate == '')
	$todate =  date('d/m/Y');

if ($perpage == '' ) $perpage = $config['trowlimit'][0];

$querylog=" SELECT FI_Tender as loginaccess, login_belongstogrp, ifNull(FI_TenderDel,0) as FI_TenderDel, ifNull(FI_TenderMod,0) as FI_TenderMod, ifNull(FI_TenderApp,0) as FI_TenderApp, Language 
            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);
	}

if ($loginaccess=='' or $loginaccess==0)
	header("location:menu.php");


//Access Mode On Insert/Edit/Delete
$DelMode  = $FI_TenderMod;
$EditMode = $FI_TenderDel;

$EditHint = '';
$DelHint = '';

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

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

$queryperiod= " Select ifNull(LockViewPeriod,0) As LockViewPeriod, ViewPeriodDate, ifNull(ViewLockDaily,0) As ViewLockDaily, ViewNumberOfDays ".
              " From ".$_SESSION['dbLabel'].".ListUserDir  ".
			  " Where Usercode='".$_SESSION['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);
}	
			  
//Read From Module Table
$querymodule=" Select ifNull(Module_Project,0) As Module_Project, ifNull(Module_ProjectParent,0) As Module_ProjectParent From Module";
$resultmodule=mysql_query($querymodule,$connection) or die(mysql_error());
while($rowmodule=mysql_fetch_array($resultmodule)){
	extract($rowmodule);
}	


$queryproject=" select distinct project.project_code, project_name ".
              " from project left join ".$_SESSION['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='".$_SESSION['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);	


//Get Default Project
$querydflproject="select project_code as defaultproject from ".$_SESSION['dbLabel'].".loginstk where user_account='".$_SESSION['useraccount']."' and default_project=1 ";
$resultdflproject=mysql_query($querydflproject,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultdflproject)){
	extract($rows);
}
	
$PProjectCode = "".$PProjectCode;


if ((!isset($PProjectCode)) && $Module_Project == 1)
	$PProjectCode = $defaultproject;

if (empty($orderby)) $orderby = 1;
if (empty($searchby)) $searchby = 2;

if ($startrange=='')
	$startrange = 0;
if ($perpage=='')
	$perpage = $config['trowlimit'][0];
	
print <<<HERE
<head>

<link rel="stylesheet" type="text/css" media="all" href="css/style.css">
<script type="text/javascript" src="js/grid/jquery-1.9.1.js"></script>
<title>Search Tender</title>
<script type="text/javascript" language="javascript">

function clearform()
{
  document.search.keyword.value='';
  document.search.PProjectCode.value='';
  document.search.PClientCode.value='';
  document.search.fromdate.value = '';
  document.search.todate.value = '';

  document.search.action='Form_TenderSearch.php';
  document.search.submit();

}


function SetNextPage(startrange,perpage){

	document.search.action='Form_TenderSearch.php?keyword=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}

function SetPrvPage(startrange,perpage){

	document.search.action='Form_TenderSearch.php?keyword=&startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}


function DeleteRecord(tender_id, Ref){
	var vAdjustType = document.search.AdjustType.value;
	
	if (tender_id != '') {
		if (confirm ( "Are you sure you want to Delete this record with reference = "+Ref+" ?") )
		{
			document.search.action="Form_Adjustment_Actions.php?actionmode=delete&tenderid="+tender_id;
			document.search.submit();
		}
	}
	
}

function UpdateRecord(tenderid){
	
	opener.document.tender.tenderid.value=tenderid;
	opener.document.tender.actionmode.value='editmode';
	opener.document.tender.submit();
	self.close();
}


function SelectOrderBy()
{
  document.search.keyword.value='';

  document.search.action='Form_TenderSearch.php';
  document.search.submit();

}

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

function SubmitForm()
{	
  document.search.action='Form_TenderSearch.php?startrange=0';
  document.search.submit();
}

function kd(e)
{
	x=document.search;
    var intKey = (window.Event) ? e.which : e.keyCode;
	
    if (intKey == 13) { //enter key
        x.btnSubmit.click();
		return false;
    }
    return true;
}

function showlistProject(str){

  window.open('List_SorProject.php?frm=6&item='+str,'mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function showlistClient(){
	window.open('List_SorClient.php?frm=17','mywindow','width=850,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function RefreshPage()
{
   document.search.action='Form_TenderSearch.php?startrange=0';
  document.search.submit();

}

function SetFirstPage(startrange,perpage){
	document.search.action='Form_TenderSearch.php?startrange=0&perpage='+perpage;
	document.search.submit();
}

function SetLastPage(perpage,totalrows){
	var result=totalrows % perpage;
	if (result == 0) result = perpage;
	startrange=totalrows-result;
	document.search.action='Form_TenderSearch.php?startrange='+startrange+'&perpage='+perpage;
	document.search.submit();
}
</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;
}

.style12 {
	font-size: 9px;
	color: #999999;
	font-weight: bold;
}

.style16 {
	font-size: 16px;
	color: #FF0000;
	font-weight: bold;
	font-family: "Times New Roman", Times, serif;
}
.style17 {font-size: 9px}

.style26 {color: #FF0000}
.style27 {color: #999999 ;font-size: 10px;}
.style28 {color: #000000 ;font-size: 10px;}

</style>
<link type="text/css" rel="stylesheet" href="dhtmlgoodies_calendar.css?random=20051112" media="screen"></LINK>
<SCRIPT type="text/javascript" src="dhtmlgoodies_calendar.js?random=20060118"></script>
</head>
<body class='bodybackground'>
<form name='search' method='post' action=''>
HERE;



$PRef = GetSQLValueString($keyword, 'text');

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

			 
$querysearch=" select tender_id, tender_reference, tenders.project_code as project_code, project_name, client_code, ledger_name, date_format(tender_receivedDate,'%d/%m/%Y') as receivedDate,
				date_format(tender_submitDate,'%d/%m/%Y') as submitDate, date_format(tender_dueDate,'%d/%m/%Y') as dueDate, tender_statusAt, tender_amount, tender_directCost, tender_margin
				from tenders
				inner join clients on Ledger_number = client_code
				inner join project on project.Project_Code = tenders.project_code ";  
			 
if ($projectexist >	0)
  $querysearch= $querysearch." Inner join ( select distinct project_code from ".$_SESSION['dbLabel'].".loginstk ".
							 "			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
							 "             and (project_code is not null and project_code != '') ".
							 "			 ) Q1 on (($Module_ProjectParent=1 and tenders.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and tenders.project_code = Q1.project_code )) ";
			 
 $querysearch= $querysearch.											 
			 " Where (($searchby = 2 and tender_reference Like Concat(ifNull($PRef, tender_reference),'%')) Or ".
			 "        ($searchby = 1 and Date_Format(tender_receivedDate,'%Y-%m-%d') = ifNull(Date_Format($PRef,'%Y-%m-%d'), Date_Format(tender_receivedDate,'%Y-%m-%d'))) )  ".
			 " And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(tender_receivedDate,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',tender_receivedDate),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
             "                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(tender_receivedDate,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ";
			 
			  
			 
if ($PProjectCode != '')
	$querysearch= $querysearch." And tenders.project_code like concat('".$PProjectCode."','%') ";
if ($PClientCode != '')
	$querysearch= $querysearch." And tenders.client_code like concat('".$PClientCode."','%') ";	

if ($fromdate != '' && $todate !='' )
	$querysearch = $querysearch." And Date_Format(tender_receivedDate,'%Y-%m-%d') between '".explodeword($fromdate)."' and '".explodeword($todate)."' ";
			 

if ($orderby == 1)
	$querysearch= $querysearch." Order By tender_receivedDate Desc, tender_reference Desc ";
else if ($orderby == 2)
	$querysearch= $querysearch." Order By tender_reference Desc ";	
	
			 
//echo $querysearch;			 

$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());
$totalrows = mysql_num_rows($resultsearch);

		
$querysearch = $querysearch." limit ".$startrange.",".$perpage;

$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());		

echo"<table cellpadding='0' cellspacing='0' border='0'  align='left' style='table-layout:fixed' width='930px'>";
echo"<tr>
		<td id='search-top1' style='height:34px; width:31px;'>&nbsp;</td>
	  	<td id='search-top2' style='height:34px; ' align='center' valign='middle'>
			<table border='0'>
			<tr><td><span class='style3'>List of Tenders
			</span></td></tr>
			</table>
		</td>
		<td id='search-top3' style='height:34px; width:31px;'>&nbsp;</td>
	</tr>";

echo"<tr><td id='search-content1' style='width:31px;'>&nbsp;</td>
		 <td id='search-content2' >";
		 

echo"<table border='0' cellspacing='1'  style='table-layout:fixed'>
	  <col width=100>
	  <col width=180>
	  <col width=340>
	  <col width=100>
	  <col width=180>		     
	
	  <tr height='30px' class='Search-header-bg'>";
	  
if ($Module_Project == 1) {
	echo" <td align='left' ><span class='style4'>Project</span></td>
	      <td align='left' ><span class='style4'>
		    <input type='text' name='PProjectCode' id='PProjectCode' value='$PProjectCode' size='14' maxlength='20' onkeydown=\"return kd(event);\" /></span>
		    <label><span class='style4'><img src='img/btnopen.jpg' title=' Select Project ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\" onClick='showlistProject(1); '  /></span></label></td>";
} else {
	echo" <td align='left' ><input type='hidden' name='PProjectCode' id='PProjectCode' value='$PProjectCode' /></td>";

}			
echo" <td ><span class='style4'>From&nbsp;</span><input type='text' name='fromdate' id='fromdate' value='$fromdate' maxlength='10' style='width:80px;'>
		<A HREF=\"#\" onClick=\"displayCalendar(document.search.fromdate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span>
&nbsp; &nbsp;<span class='style4'>To&nbsp;</span><input type='text' name='todate' id='todate' value='$todate' maxlength='10' style='width:80px;'>
		<A HREF=\"#\" onClick=\"displayCalendar(document.search.todate,'dd/mm/yyyy',this); return false;\" NAME=\"anchor1\" ID=\"anchor1\"><image src='./img/cal.gif' border=0 align=center></image></A></span></td>";

echo" <td align='right'><span class='style4'>Client</span></td>		
		  <td align='left' ><span class='style4'>
		    <input type='text' name='PClientCode' id='PClientCode' value='$PClientCode' size='17' maxlength='20' onkeydown=\"return kd(event);\" /></span>
		    <label><span class='style4'><img src='img/btnopen.jpg' title=' Select Client ' width='15' height='20' border='0' onMouseOver=\"style.cursor='hand'\"  onClick=\"showlistClient();\" /></span></label></td>";
echo" </tr>
	  <tr height='30px'  class='Search-header-bg'>	  
	    <td align='left'><span class='style4'>Search By</span></td>
		<td align='left' colspan='2'><span class='style4'><input type='text' name='keyword' id='keyword' value='$keyword' size='15' maxlength='30' onkeydown='return kd(event)'/><input type='hidden' name='PMode' id='PMode' value='$PMode' size='15' maxlength='30'/></span>
		
			<select name='searchby' id='searchby' value='$searchby' onchange='SelectSearchBy();'>";
		
			if ($searchby==1)		$s21 = 'selected';
			else if ($searchby==2)	$s22 = 'selected';
				
			echo"<option ".$s21." value='1'>Date (yyyy-mm-dd)</option>
				 <option ".$s22." value='2'>Reference</option>";
			echo"</select>";	
				 
echo"	   <button type='button' id='btnSubmit' name='btnSubmit' onclick='SubmitForm(); return false;' title='Find'><span><span>Find</span></span></button>
			<button type='button' id='btnCancel' name='btnCancel' onclick='clearform();return false;' title='Cancel'><span><span>Cancel</span></span></button></td>";
echo" <td align='right' ><span class='style4'>Order By</span></td>		
	  <td align='left' ><span class='style4'><select name='orderby' id='orderby' value='$orderby' onchange='SelectOrderBy();'>";
		
		if ($orderby==1)
			$s11 = 'selected';
		else if ($orderby==2)
			$s12 = 'selected';
			
		echo"<option ".$s11." value='1'>Date</option>
			 <option ".$s12." value='2'>Reference</option>
			 </select></span></td>";		
			 


echo" </tr>
</table>
		</td>
		<td id='search-content3' style='width:31px;'>&nbsp;</td>"; 
echo" </tr>";

	  echo"<tr>
		<td  id='search-content1' style='height:34px;width:31px;'>&nbsp;</td>
		<td  id='search-content2' style='height:34px;width:1025px;'>
		<table width='100%' border=0>
		<tr>
			<td align='right' style='width:380px;'><span class='style4'>Per Page </span><span class='style4'><select name='perpage' id='perpage' value='$perpage' onchange=\"RefreshPage();\">";
              
            $perpages = $config['trowlimit'];
			foreach ($perpages as $val){
			echo" <option value = '$val' "; if ($perpage ==$val) echo "selected"; 
			echo" >$val</option> ";
			}
	echo'	
				 </select></span></td>
			<td  style="width:74px;border-right:1px solid #000000;text-align:right;">';
			
			if($startrange > 0)
				echo"<img src='img/firstpage.png' title='First Page' onMouseOver=\"style.cursor='hand'\" onclick=SetFirstPage('".$startrange."','".$perpage."')>";

			$diff= $startrange - $perpage;
				
			if (($diff) >= 0 ){
				$prvstartrange = $startrange - $perpage;
				echo"&nbsp;&nbsp;<img src='img/arrowleft.png' title='Previous' onMouseOver=\"style.cursor='hand'\"  onclick=SetPrvPage('".$prvstartrange."','".$perpage."')>";
			}
			else
				echo "&nbsp;";
		
echo"		</td><td  align='left' style='width:74px;'>";
		
		
			if ($startrange <= $totalrows){
				$startrange1 = $startrange + $perpage;
				if  ($startrange1 < $totalrows){
					echo"<img src='img/arrowright.png' title='Next' onMouseOver=\"style.cursor='hand'\" onclick=SetNextPage('".$startrange1."','".$perpage."')>";
					echo"&nbsp;&nbsp;<img src='img/lastpage.png' title='Last Page' onMouseOver=\"style.cursor='hand'\" onclick=SetLastPage('".$perpage."','".$totalrows."')>";	
				}
			} else
				echo "&nbsp;";
				
			
echo"		</td><td style='width:380px;'>&nbsp;</td>
		</tr>";
echo"	</table></td>
		<td id='search-content3' style='width:31px;'>&nbsp;</td>";
echo"</tr>";			


	
	echo"<tr><td id='search-content1' style='width:31px;'>&nbsp;</td>
		<td id='search-content2'>
			<div style='overflow:scroll;height:400px;width:870px;'>
			<table border='0'  cellpadding='0' cellspacing='1' style='width:1220px;'>
			  <col width=20>
			  <col width=20>
			  <col width=70>
			  <col width=90>
			  <col width=250>
			  <col width=250>
			  <col width=90>
			  <col width=90>
			  <col width=120>
			  <col width=120>
			  <col width=100>";

	 
	if($message!=''){
		echo"<tr class='Search-header-bg'>
				<td height='15' align='center' colspan='11' class='searchmessage'>".$message."</td>
			</tr>";
	}
	 
	echo" <tr class='Search-Label-bg'>
			<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
			<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
			<td  height='25' align='left'><span class='style4'>Reference </span></td>
			<td  height='25' align='center'><span class='style4'>Received Date </span></td>
			<td  height='25' align='center'><span class='style4'>Client</span></td>
			<td  height='25' align='center'><span class='style4'>Project</span></td>
			<td  height='25' align='center'><span class='style4'>Submission Due Date</span></td>
			<td  height='25' align='center'><span class='style4'>Date Submitted	</span></td>
			<td  height='25' align='center'><span class='style4'>Tender Amount</span></td>
			<td  height='25' align='center'><span class='style4'>Direct Cost</span></td>
			<td  height='25' align='center'><span class='style4'>Margin</span></td>
		  </tr>";
		

	


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."'";	

	
	$EditHint = 'Edit Record';
	$DelHint  = 'Delete Record';
	
	echo'<tr '.$Color.'>';

	if($EditMode==1)
		echo'<td align="center"><span class="style5"><img src="img/edit.png" onMouseOver="style.cursor=\'hand\'" onclick="UpdateRecord('.$tender_id.');" title="'.$EditHint.'"  style="width: 20px; height: 20px; "></span></td>';
	else 
		echo'<td align="center">&nbsp;</td>';   	 	
		
	if($DelMode==1)
		echo'<td align="center"><span class="style5"><img src="img/delete.png" onMouseOver="style.cursor=\'hand\'" onclick="DeleteRecord('.$tender_id.', \''.$tender_reference.'\');" title="'.$DelHint.'" '.$DelMode.' style="width: 20px; height: 20px; "></span></td>';
	else 
		echo'<td align="center">&nbsp;</td>';  
		
	echo'	<td align="left"><span class="style5">'.$tender_reference.'</span></td>
			<td align="center"><span class="style5">'.$receivedDate.'</span></td>';
			
	
	echo'	<td align="left"><span class="style5">'.$project_code.' - '.$project_name.'</span></td>
			<td align="left"><span class="style5">'.$client_code.' - '.$ledger_name.'</span></td>
			<td align="left"><span class="style5">'.$dueDate.'</span></td>
			<td align="center"><span class="style5">'.$submitDate.'</span></td>
			<td align="right" ><span class="style5">'.number_format($tender_amount, $DecimalBase).'</span></td>
			<td align="right"><span class="style5">'.number_format($tender_directCost, $DecimalBase).'</span></td>
			<td align="right"><span class="style5">'.number_format($tender_margin, $DecimalBase).'</span></td>
		</tr>';
		
		
}
							

			
echo"</table></div></td><td id='search-content3' style='width:31px;'>&nbsp;</td></tr>";		
		
echo"	<tr >
		<td id='search-bottom1' style='height:34px; width:31px;'>&nbsp;</td>
		<td id='search-bottom2' style='height:34px; width:920px;' valign='top'><table width='100%' border=0 height=28px>
		<tr><td style='width:280px;'>&nbsp;</td><td align='right' style='width:74px;border-right:1px solid #000000;'>";
		
			if($startrange > 0)
				echo"<img src='img/firstpage.png' title='First Page' onMouseOver=\"style.cursor='hand'\" onclick=SetFirstPage('".$startrange."','".$perpage."')>";
				
		//$diff= $startrange - $perpage;
		
		if (($diff) >= 0 ){
			//$prvstartrange = $startrange - $perpage;
			echo"<img src='img/arrowleft.png' title='Previous' onMouseOver=\"style.cursor='hand'\"  onclick=SetPrvPage('".$prvstartrange."','".$perpage."')>";
		}
		else
			echo "&nbsp;";
		
		echo"</td><td width='150' align='left'>";
		
		
		if ($startrange <= $totalrows){
			//$startrange = $startrange + $perpage;
			if  ($startrange1 < $totalrows){
				echo"<img src='img/arrowright.png' title='Next' onMouseOver=\"style.cursor='hand'\" onclick=SetNextPage('".$startrange1."','".$perpage."')>";
				echo"&nbsp;&nbsp;<img src='img/lastpage.png' title='Last Page' onMouseOver=\"style.cursor='hand'\" onclick=SetLastPage('".$perpage."','".$totalrows."')>";	
			}	
		} else
			echo "&nbsp;";
			
		echo"</td><td width='170'>&nbsp;</td></tr>";
		echo"</table></td><td id='search-bottom3' style='height:34px; width:31px;'>&nbsp;</td>";

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


          

		  

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

HERE;

function explodeword($date)
{

$trim = explode('/',$date);
$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
return $trim;
}

?>