<?php

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


include("config.inc.php");
include("Functions_Purchase.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");

$querylog=" select ifNull(login_belongstogrp,0) As FI_BelongsToGrp ".
          " from ".$HTTP_SESSION_VARS['dbLabel'].".login where user_account='".$HTTP_SESSION_VARS['useraccount']."' and Upper(Login_Schema) = Upper('".$HTTP_SESSION_VARS['dbName']."')  ";
$resultlog=mysql_query($querylog,$connection) or die(mysql_error());
while($rows=mysql_fetch_array($resultlog)){
	extract($rows);
}


$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('_',$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;	

if (empty($PDateFrom))	$PDateFrom = displayToday();
if (empty($PDateTo))	$PDateTo = displayToday();

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">
<title>Select Production Template</title>
<script type="text/javascript" language="javascript">

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

}

function ClearForm()
{
	document.search.keyword.value='';
	document.search.PDateFrom.value='';
	document.search.PDateTo.value='';
	document.search.SelectedID.value = '';
	document.search.SelectedRows.value = '';
	document.search.action='Form_Production_LoadMaterials.php';
	document.search.submit();

}

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

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

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


function ChangeLocation()
{
    if (document.search.PMode.value == 1) {
	    var GenId = document.search.GeneratedId.value;
		
		opener.document.production.txtPrdId.value=GenId;
	    opener.document.production.mainaction.value='';
		opener.document.production.actionmode.value='submitrecord';
		opener.document.production.message.value = document.search.message.value;
		opener.document.production.action='Form_Production.php';
		opener.document.production.submit();
		self.close();
	}	
}

function ShowHideDetails(AdustmentId, Option) {
	if (Option == 'S') {
		document.search.SelectedID.value = AdustmentId;
	}
	else if (Option == 'H') {
		document.search.SelectedID.value = '';
	}	
	document.search.action='Form_Production_LoadMaterials.php?SelectedID='+AdustmentId;
	document.search.submit();
}

function SelectRecord() {
	var MasterCheckName, vSelectedRows;
	var x, y;
	
	vSelectedRows = '';
	for (var i=1; i <= document.search.i.value; i++)
	{
		MasterCheckName='M'+i;
		x = document.getElementById(MasterCheckName);
		
		if (x.checked)	vSelectedRows = vSelectedRows + ',' + x.value;	
		
		
	}
	
	vSelectedRows = vSelectedRows.substr(1);
	document.search.SelectedRows.value = vSelectedRows;
}

function LoadData(){
	var x = document.search;
	var vSelectedRows = x.SelectedRows.value;
	
	if (vSelectedRows != '') {
		var vPrdId    = x.PPrdId.value;
		
		x.action="Form_Production_Actions.php?mode=loadmaterials&mainmode=&SPrdId="+vPrdId+"&SSelectdId="+vSelectedRows;
		x.submit();
	} else
		alert ('Please Select a Record.');
	
}

function SubmitForm()
{	

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

}

function SetFirstPage(startrange,perpage){
	document.search.action='Form_Production_LoadMaterials.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_Production_LoadMaterials.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: 0px;
	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 {color: #5151FF; text-decoration:underline}


</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 onLoad='LoadForm();' class='bodybackground'>
<form name='search' method='post' action=''>
<input type='hidden' name='GeneratedId' value='$GeneratedId'>
<input type='hidden' name='SelectedRows' value='$SelectedRows'>
<input type='hidden' name='SelectedID' id='SelectedID' value='$SelectedID'>

<input type='hidden' name='PPrdDate' value='$PPrdDate'>
<input type='hidden' name='PPrdId' value='$PPrdId'>
<input type='hidden' name='PPrdExpireDate' value='$PPrdExpireDate'>
<input type='hidden' name='PPrdCurr' value='$PPrdCurr'>

HERE;

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


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

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

   
if (!empty($PDateFrom))   $PDateFrom1 = explodeword1($PDateFrom);
if (!empty($PDateTo))     $PDateTo1 = explodeword1($PDateTo);     
			
$querysearch=" Select Distinct Adjustment.Adjustment_Id, Adjustment.Adjustment_Reference, Date_Format(Adjustment.Adjustment_Date,'%d-%m-%Y') As Adjustment_Date, ".
             " Adjustment.Adjustment_Remak As Adjustment_Remak, Currency_Code, ifNull(abs(Adjustment_Amount),0) As Adjustment_Amount ".
			 " From Adjustment ".
			 " Where Adjustment.Adjustment_Reference = ifNull($PRef, Adjustment.Adjustment_Reference) ".
			 " And Date_Format(Adjustment.Adjustment_Date,'%Y-%m-%d') Between Date_Format(ifNull('".$PDateFrom1."', Adjustment.Adjustment_Date),'%Y-%m-%d') And Date_Format(ifNull('".$PDateTo1."', Adjustment.Adjustment_Date),'%Y-%m-%d')  ".
			 //" And ifNull(Adjustment_Production, 0) = 1 ".
			 " And Upper(ifNull(Entry_Type, 'ADJUSTMENT')) = 'PRODUCTION' ".
			 " And Upper(Adjustment_EntryType) = 'O' ".
			 " And Not Exists (Select 1 From AdjustmentDt  ".
			 "                 Inner Join ProductionRM on ProductionRM.RelatedDt_ID = AdjustmentDt.AdjustmentDt_ID ".
			 "                 Where AdjustmentDt.Adjustment_ID = Adjustment.Adjustment_ID)    ".
			 " And (($rowsperiod = 0 and 1 = 1) Or ($rowsperiod > 0 and (($LockViewPeriod = 1 and  Date_Format(Adjustment.Adjustment_Date,'%Y-%m-%d') >= Date_Format(ifNull('".$ViewPeriodDate."',Adjustment.Adjustment_Date),'%Y-%m-%d')) Or ($LockViewPeriod = 0 and 1=1 ))   ".
             "                                                      and (($ViewLockDaily = 1 and DateDiff(Date_Format(Now(),'%Y-%m-%d'),Date_Format(Adjustment.Adjustment_Date,'%Y-%m-%d')) <= $ViewNumberOfDays) Or ($ViewLockDaily = 0 and  1 = 1 ))) ) ".
			 " And ifNull(Adjustment.Adjustment_BelongsToGroup,0) >= ifNull($FI_BelongsToGrp,0) ";
	 
$querysearch= $querysearch." Order By Adjustment.Adjustment_Reference Desc ";
			 
//echo $querysearch; exit;

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

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

echo"<table cellpadding='0' cellspacing='0' border='0'  align='left' style='table-layout:fixed' width='910px'>";
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 Stock Out
			</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=20>
	  <col width=20>
	  <col width=100>
	  <col width=100>
	  <col width=380>
	  <col width=70>
	  <col width=150>
	
	  <tr class='Search-header-bg'>
	    <td align='left' colspan='3'><span class='style4'>Date From / To</span></td>
		<td align='left' colspan='2'>
			<span class='style4'><input type='text' name='PDateFrom' value='$PDateFrom' maxlength='10' style='width:100px;' >
				 <a href='#' onClick=\"displayCalendar(document.search.PDateFrom,'dd/mm/yyyy',this); return false;\" NAME='anchor1' ID='anchor1'><img src='./img/cal.gif' border=0 align=center></a></span>
			&nbsp;/&nbsp;<span class='style4'><input type='text' name='PDateTo' value='$PDateTo' maxlength='10' style='width:100px;' >
				 <a href='#' onClick=\"displayCalendar(document.search.PDateTo,'dd/mm/yyyy',this); return false;\" NAME='anchor1' ID='anchor1'><img src='./img/cal.gif' border=0 align=center></a></span>
		</td>				  
		<td align='left' colspan='2'>&nbsp;</td>
      </tr>		
	  <tr class='Search-header-bg'>
	    <td align='left' colspan='3'><span class='style4'>Search by Reference</span></td>
		<td align='left' colspan='4'><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>
</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();\">";
              
			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='8' 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:830px;'>
		<table border='0'  cellpadding='0' cellspacing='1' >
		 <col width=20>
		  <col width=20>
		  <col width=100>
		  <col width=100>
		  <col width=380>
		  <col width=70>
		  <col width=120>
		
	
	  <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'>Date </span></td>
		<td  height='25' align='center'><span class='style4'>Remark</span></td>
		<td  height='25' align='center'><span class='style4'>Currency</span></td>
		<td  height='25' align='center'><span class='style4'>Amount</span></td>";
echo" </tr>";
		

$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."'";	
	
	
	echo'<tr '.$Color.'>';
	$SelMaster  = 'M'.$i;
	$$SelMaster = $Adjustment_Id;
			   
	echo"	<td align='center'><span class='style5'><input type='checkbox' name='$SelMaster' id='$SelMaster' value='".$$SelMaster."' onclick='SelectRecord(this.name);' /></span></td>";		
	
	if ($SelectedID != "" && $Adjustment_Id == $SelectedID)		
		echo'<td align="center"><span class="style5"><img src="img/hide.png" onMouseOver="style.cursor=\'hand\'"  onclick="ShowHideDetails('.$Adjustment_Id.', \''.'H'.'\');" title="Hide Details" height="15px" width="15px"></span></td>';
	else	
		echo'<td align="center"><span class="style5"><img src="img/show.png" onMouseOver="style.cursor=\'hand\'"  onclick="ShowHideDetails('.$Adjustment_Id.', \''.'S'.'\');" title="Show Details" height="15px" width="15px"></span></td>';

	echo'	<td align="left"><span class="style5">'.$Adjustment_Reference.'</span></td>
			<td align="center"><span class="style5">'.$Adjustment_Date.'</span></td>
			<td align="left"><span class="style5">'.$Adjustment_Remak.'</span></td>
			<td align="center"><span class="style5">'.$Currency_Code.'</span></td>
			<td align="right"><span class="style5">'.number_format($Adjustment_Amount, $DecimalBase).'</span></td>';
	echo'</tr>';
		
	if ($SelectedID != "" && $Adjustment_Id == $SelectedID) {
		$sub_query = " Select AdjustmentDt.Item_Code, Items.Item_Description, AdjustmentDt.Warehouse_Code, abs(AdjustmentDt_Quantity), AdjustmentDt_Price  ".
					 " From AdjustmentDt ".
					 " Inner Join Items on AdjustmentDt.Item_Code = Items.Item_Code ".
					 " Where AdjustmentDt.Adjustment_Id = '".$SelectedID."' ";
		$sub_result=mysql_query($sub_query,$connection) or die(mysql_error());	
		$sub_totalrows = mysql_num_rows($sub_result);
		
		if ($sub_totalrows > 0) {
			echo "<tr ".$Color.">";
			echo "<td colspan='2' valign='top' align='left'>&nbsp;</td>";
			echo "<td colspan='5' valign='top' align='left'><div style='border:1px solid #33CCFF; z-index:9999; background-color:#CCFFFF; padding-left:5px; padding-bottom:5px;'>";
			echo "<table width='95%' border='0' cellpading='0' cellspacing='1'>";
			echo "<tr><td width='20%'><span class='style17'>Item Code</span></td><td width='45%'><span class='style17'>Description</span></td> <td width='10%' align='center'><span class='style17'>Warehouse</span></td>";
			echo "    <td width='10%' align='center'><span class='style17'>Quantity</span></td><td width='15%' align='center'><span class='style17'>Cost</span></td>";
			while($sub_rows=mysql_fetch_array($sub_result)){
				echo "<tr><td valign='top'>".$sub_rows[0]."</td><td valign='top'>".$sub_rows[1]."</td><td valign='top'>".$sub_rows[2]."</td>";
				echo "	  <td align='right' valign='top'>".$sub_rows[3]."</td><td align='right' valign='top'>".number_format($sub_rows[4], $DecimalBase)."</td></tr>";
			
			}
			
			echo "</tr></table></div></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 ><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>";

function explodeword1($date)
{

	$trim = explode('/',$date);
	$trim = "$trim[2]"."-"."$trim[1]"."-"."$trim[0]";
	return $trim;
}
function GetSQLValueString($theValue, $theType) 
{
  $theValue = trim($theValue);	
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "Null";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "Null";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "Null";
      break;
  }
  return $theValue;
}

print <<<HERE

</form>
</body>

HERE;

?>