<?php

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


include("config.inc.php");
include("function.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($_SESSION['dbName'],$connection) or die("Could not find DB");

$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp,  ".
		  " ifNull(FI_FrmRestrictWarehouse,0) As FI_FrmRestrictWarehouse ".
          " 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);
}

$EditHint = '';
$EditMode = '';

$querysetup="select DecimalBase, DecimalBase1, DecimalBase2, base1, base2, grid_color1, grid_color2, ifNull(Setup_VatPercentage,0) As Setup_VatPercentage 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, ifNull(Sale_MinPendingQty,0) As Sale_MinPendingQty, ifNull(Sale_MaxExceedQty,0) As Sale_MaxExceedQty 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_AdditionalTaxes,0) As Module_AdditionalTaxes, ifNull(Module_Pack,0) As Module_Pack, ".
			 " ifNull(Module_ProjectParent,0) As Module_ProjectParent, ifNull(Module_CostCenterParent,0) As Module_CostCenterParent, ".
			 " ifNull(Module_Delivery,0) As Module_Delivery, ifNull(Module_TransferSorder,0) As Module_TransferSorder  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 ".$_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);
}	
			  
//echo $queryperiod;	

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

$querycostcent=" select distinct costcent.costcent_code, costcent_name ".
               " from costcent left join ".$_SESSION['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='".$_SESSION['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);	

$querywh=" select distinct warehouse.warehouse_code, warehouse_name ".
         " from warehouse inner join ".$_SESSION['dbLabel'].".loginstk on warehouse.warehouse_code = loginstk.warehouse_code ".
		 " where user_account='".$_SESSION['useraccount']."' ".
		 " and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
		 " order by warehouse.warehouse_code";
$whresult = mysql_query($querywh,$connection) or die(mysql_error());
$whexist  = mysql_num_rows($whresult);	  

$queryledger= " select distinct ledger_number, ledger_include ".
              " from ".$_SESSION['dbLabel'].".ledgerstk  ".
			  " where user_account='".$_SESSION['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];


$queryitems = " Select Item_Code, Item_description From Items Where ifNull(Item_Production,0) = 1 Order By Item_Code ";

	
$resultitems= mysql_query($queryitems,$connection) or die(mysql_error());

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" />
<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>List of Pending Sales Order</title>
<script type="text/javascript" language="javascript">

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

}

function clearform()
{
  document.search.keyword.value='';
  document.search.lstItems.value='';
  document.search.action='Form_PreProduction_LoadSorderdt.php';
  document.search.submit();

}

function selectRecord(sorderid){
	opener.loadFromSorder(sorderid);
	self.close();
}

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

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


function SubmitForm()
{	

  //document.search.keyword.value='';
  document.search.action='Form_PreProduction_LoadSorderdt.php?startrange=0';
  document.search.submit();

}

function SetFirstPage(startrange,perpage){
	document.search.action='Form_PreProduction_LoadSorderdt.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_PreProduction_LoadSorderdt.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>

</head>
<body class='bodybackground'>
<form name='search' method='post' action=''>


HERE;
echo "<input type='hidden' name='message' value='".htmlspecialchars($message, ENT_QUOTES)."'>";

	echo "<input type='hidden' name='redirect' value='0'>";
	echo "<input type='hidden' name='SSorId' value=''>";

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

if (empty($ViewPeriodDate))
   $ViewPeriodDate = 'Null';
if (empty($ViewNumberOfDays))   
   $ViewNumberOfDays = 1;
			
$querysearch=" select sorderdt.sorderdt_id as sorderdt_id, sorderdt.item_code as item_code, item_description, sorder_reference, sorder.client_code as client_code, ledger_name, 
				(sorderdt.sorderdt_ProdQty-ifnull(ProdQty,0)-ifnull(tempProdQty,0)) as sorderdt_ProdQty, ifnull(temp_sorderdt.sorderdt_id, -1) tempSorderdt_id
				from sorderdt
				inner join sorder on sorder.sorder_id = sorderdt.sorder_id
				inner join items on items.item_code = sorderdt.item_code
				inner join clients on clients.ledger_number = sorder.client_code 
				left join (
					select preproduction.RelSorderdt_id,sum(ifnull(preproduction.Production_quantity,0)) as ProdQty, sum(ifnull(temp_preproduction.Production_quantity,0)) as tempProdQty
					from preproduction
					left join temp_preproduction on temp_preproduction.RelSorderdt_id = preproduction.RelSorderdt_id
					and temp_preproduction.production_id <> preproduction.production_id
					where ifnull(preproduction.RelSorderdt_id,'') != ''
					group by preproduction.RelSorderdt_id
				) as Q on Q.RelSorderdt_id = sorderdt.sorderdt_id
				left join temp_sorderdt on temp_sorderdt.sorderdt_id = sorderdt.sorderdt_id	";
				
	if ($projectexist >	0)
	$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 Sorder.project_code like concat(Q1.project_code,'%')) or ($Module_ProjectParent=0 and Sorder.project_code = Q1.project_code )) ";				
	if ($costcentexist > 0)
	$querysearch .= " inner join ( select distinct costcent_code from ".$_SESSION['dbLabel'].".loginstk ".
					"			   where loginstk.user_account='".$_SESSION['useraccount']."' ".
					"             and (costcent_code is not null and costcent_code != '') ".
					"			 ) Q2 on (($Module_CostCenterParent=1 and Sorder.costcent_code like concat(Q2.costcent_code,'%')) or ($Module_CostCenterParent=0 and Sorder.costcent_code = Q2.costcent_code )) ";
 
	if ($ledgerexist > 0)
	$querysearch .= " inner join ( select distinct ledger_number from ".$_SESSION['dbLabel'].".ledgerstk ".
					"			    where user_account='".$_SESSION['useraccount']."' ".
					"              and (ledger_number is not null and ledger_number != '') ".
					"			 )  Q3 on (($ledgerinclude = 1 and Sorder.Client_Code like concat(Q3.ledger_number,'%') ) or ($ledgerinclude = 0 and Sorder.Client_Code Not like concat(Q3.ledger_number,'%') ) or Sorder.Client_Code is null) ";							 	

 if ($whexist > 0 && $FI_FrmRestrictWarehouse == 1)
  $querysearch .= " inner join ( select distinct sorderdt.Sorder_Id ".
				" 				from sorderdt inner join ".$_SESSION['dbLabel'].".loginstk on sorderdt.warehouse_code = loginstk.warehouse_code ".
				" 				where loginstk.user_account='".$_SESSION['useraccount']."' ".
				" 				and (loginstk.warehouse_code is not null and loginstk.warehouse_code != '')  ".
				"			 ) Q4 on Sorder.Sorder_Id = Q4.Sorder_Id "; 
				
	$querysearch .=" where Sorder.Sorder_Reference = ifNull($PRef, Sorder.Sorder_Reference) and ifnull(sorderdt.sorderdt_sentProduction,0) = 1 And Sorder.Sorder_Type = 'SO'  
					And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Sorder.Sorder_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Sorder.Sorder_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
				"   and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Sorder.Sorder_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) 
					And ifNull(Sorder.Sorder_BelongsToGrp,0) >= ifNull($FI_BelongsToGrp,0) and (sorderdt.sorderdt_ProdQty-ifnull(ProdQty,0)-ifnull(tempProdQty,0)) > 0 ";
	if ($lstItems != '')
		$querysearch .= " and sorderdt.item_code = '$lstItems' ";
	$querysearch .= " order by sorder_reference, sorderdt.item_code ";
 
 
if ($PMode != '1') {
$resultsearch=mysql_query($querysearch,$connection) or die(mysql_error());
$totalrows = mysql_num_rows($resultsearch);
	
if ($startrange=='' || $PRef != 'Null')
	$startrange = 0;
if ($perpage=='')
	$perpage = 20;
		
$querysearch = $querysearch." limit ".$startrange.",".$perpage;

//echo $querysearch;

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

	  echo"<table cellpadding='0' cellspacing='0' border='0'  align='left' style='table-layout:fixed'  width='1150px'>";
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 Pending Sales Order
			</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=120>
	  <col width=100>
	  <col width=300>
	  <col width=90>
	  <col width=150>
	  <col width=220>
	  <col width=80>
	       

	  <tr class='Search-header-bg'>
	    <td align='left' colspan='1'><span class='style4'>Search by Reference</span></td>
		<td align='left' colspan='6'><span class='style4'><input type='text' name='keyword' id='keyword' value='$keyword' size='15' maxlength='30'/>
		<input type='hidden' name='PMode' id='PMode' value='$PMode' size='15' maxlength='30'/></span>
		    
			<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" </tr>
      <tr class='Search-header-bg'>
	    <td align='left' colspan='1'><span class='style4'>Search by Item</span></td>
		<td align='left' colspan='6'>";
    echo"<select name='lstItems' id='lstItems' style='font-size:11px; width:350px; height:22px;' onchange='RefreshPage();' >";
			echo"<option></option>";
			while($itemf=mysql_fetch_row($resultitems)){
				echo"<option ";
				if ($lstItems==$itemf[0])
					echo " selected ";
				echo" value='$itemf[0]'>$itemf[0] - $itemf[1]</option>";
			}
			
			
	echo"</select></td></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='left' style='width:180px;'></td>
			<td align='right' style='width:200px;'><span class='style4'>Per Page </span><span class='style4'><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>
			<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>";	
 
 if($message!=''){
		echo"	  <tr class='Search-header-bg'>
		<td height='15' align='center' colspan='7' class='searchmessage'>".$message."</td>
		</tr>";
	}
	
 echo"<tr><td id='search-content1' style='width:31px;'>&nbsp;</td>
		<td id='search-content2'>
			<div style='overflow:scroll;height:400px;width:1080px;'>
			<table border='0'  cellpadding='0' cellspacing='1' width='1060px;'>
			  <col width=20>
			  <col width=200>
			  <col width=300>
			  <col width=90>
			  <col width=150>
			  <col width=220>
			  <col width=80>";
			
	echo" 
	  <tr class='Search-Label-bg'>
		<td  height='25' align='center'><span class='style4'>&nbsp;</span></td>
		<td  height='25' align='left'><span class='style4'>Item Code </span></td>
		<td  height='25' align='left'><span class='style4'>Item Description </span></td>
		<td  height='25' align='left'><span class='style4'>Reference </span></td>
		<td  height='25' align='center' colspan='2'><span class='style4'>Client Code/Name </span></td>
		<td  height='25' align='center'><span class='style4'>Quantity</span></td>";
	echo" </tr>";
		



if ($PMode != '1') {	
	

$i = 0;

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

	if($ct%2==0)
		$Color="style='background-color:".$grid_color1."'";
	else			
		$Color="style='background-color:".$grid_color2."'";	
	
	
	
	if ($tempSorderdt_id != -1) { $EditHint = 'Exists in Pending'; $EditMode = 0; }
	else { $EditHint = 'Select Record'; $EditMode = 1; }
	
		echo'<tr '.$Color.'>';
		
			echo"<td align='center'><span class='style5'>";
			if ($EditMode == 1)
				echo "<img src='img/edit.png' title='Select Record' onclick=\"selectRecord('$sorderdt_id');\" />";
			else echo "*";
			echo "</span></td>";
				
			echo'<td align="left"><span class="style5">'.$item_code.'</span></td>
				 <td align="left"><span class="style5">'.$item_description.'</span></td>
				 <td align="center"><span class="style5">'.$sorder_reference.'</span></td>
				 <td align="left"><span class="style5">'.$client_code.'</span></td>
				 <td align="left"><span class="style5">'.$ledger_name.'</span></td>
				 <td align="center"><span class="style5">'.$sorderdt_ProdQty.'</span></td>';
		echo'</tr>';
		
		 
}
							
echo "<input type='hidden' name='i' value='$i'>";

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

/* 	echo"   <tr bgcolor='#DDDDDD'><td id='search-content1' style='height:34px; width:31px;'>&nbsp;</td><td id='search-content2' style='height:34px; width:850px;' valign='top' align='center'>
	<button type='button' id='btnLoad' name='btnLoad' onclick='LoadData();return false;' title='Load'><span><span>Load</span></span></button>
	</td><td id='search-content3' style='height:34px; 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;

?>