 <?php session_name('CAKEPHP'); session_start();
$PageSecurity = 4;
  $_SESSION['test']=$_REQUEST['route'];
$PageName = 'Purchase Requisition';
include('includes/DefinePOClass.php');
include('includes/SQL_CommonFunctions.inc');
include('includes/DefineSuppTransClass.php');
include('includes/Fun-ChkOpeningStock.php');
$year=date('y');
$year_after=$year+1;

$title = _('Purchase Requisition');

        /***********************************************************************************/
		
		
		function openingBalance($function_filter,$item)
							{
								global $db;
								$site=$function_filter[0];
								$from=$function_filter[1];
															
								if($site!='')
								$filter[]="site = '".$site."'";
								if($from!='--')
								$filter[]="reveive_date <= '".$from."'";
								if($item!='')
								$filter[]="mstid = '".$item."'";
								
								$filter=implode(' and ',$filter);
								 $sql1="Select stock, rate from opening_stockitemwise where $filter";
								$result1=DB_query($sql1,$db);
								$myrow1=DB_fetch_array($result1);
								return $myrow1['stock'];
							}
                       ////////////Opening Balance End/////////////////////////
					   
					   

						////1. MRN/////
                   function receivedMRN($function_filter,$item)
						 {
							global $db;
							$site=$function_filter[0];
							$from=$function_filter[1];
							$to=$function_filter[2];
							if($site!='')
							$filter[]="addmrn.site = '".$site."'";
							if($item!='')
							$filter[]="addmrnqty.mst_itemid = '".$item."'";
							if($from!='--' && $to!='--')
							$filter[]="addmrn.MRNDate  <='".$from."'";
							$filter=implode(' and ',$filter);
						 	 $sql1="Select SUM(addmrnqty.reciveqty) from addmrn left join addmrnqty 
							       on(addmrn.id=addmrnqty.issue_id) where $filter";
							$result1=DB_query($sql1,$db);
							$myrow1=DB_fetch_array($result1);
							return $myrow1['SUM(addmrnqty.reciveqty)'];
						}
						

							////1. Issue Slip/////
function issueSlip($function_filter,$item)
							{
								global $db;
								$site=$function_filter[0];
								$from=$function_filter[1];
								$to=$function_filter[2];
								if($site!='')
								$filter[]="addissue.site = '".$site."'";
								if($item!='')
								$filter[]="issueqty.mst_itemid = '".$item."'";
								if($from!='--' && $to!='--')
	                       $filter[]="addissue.issuedate <='".$from."' ";
								
								$filter=implode(' and ',$filter);
							
							 	$sql1="Select SUM(issueqty.issueqty) from addissue left join 
								 issueqty on(addissue.id=issueqty.issue_id) where $filter";
								$result1=DB_query($sql1,$db);
								$myrow1=DB_fetch_array($result1);
								
								return $myrow1['SUM(issueqty.issueqty)'];
							}




/// added new function 

////2. Material return/////
function receivedReturn($function_filter,$item)
{
	global $db;
	$site=$function_filter[0];
	$from=$function_filter[1];
	$to=$function_filter[2];
	
	if($site!='')
	$filter[]="material_return.site = '".$site."'";
	if($from!='--' && $to!='--')
	$filter[]="material_return.returndate <='".$from."' ";
	if($item!='')
	$filter[]="material_return_details.mst_itemid = '".$item."'";
	
	$filter=implode(' and ',$filter);
	  $sql1="Select SUM(material_return_details.receiveqty) from material_return left join material_return_details on(material_return.id=material_return_details.parentId) where $filter";
 
	
	$result1=DB_query($sql1,$db);
	$myrow1=DB_fetch_array($result1);
	return $myrow1['SUM(material_return_details.receiveqty)'];
}



function receivedSiteToSite($function_filter,$item)
{
	global $db;
	$site=$function_filter[0];
	$from=$function_filter[1];
	$to=$function_filter[2];
	
	if($site!='')
	$filter[]="transfer_receipt.sitecode = '".$site."'";
	if($from!='--' && $to!='--')
	$filter[]="transfer_receipt.MRNDate <='".$from."'";
	if($item!='')
	$filter[]="transfer_receipt_details.mst_itemid = '".$item."'";
	
	$filter=implode(' and ',$filter);
	
	 $sql1="Select SUM(transfer_receipt_details.reciveqty) from transfer_receipt left join transfer_receipt_details on(transfer_receipt.id=transfer_receipt_details.transfer_receipt_id) where $filter";
	$result1=DB_query($sql1,$db);
	$myrow1=DB_fetch_array($result1);
	return $myrow1['SUM(transfer_receipt_details.reciveqty)'];
}
//////////Total received end//////////////////////////

/* Calculate total issued*/
////1. Issue Slip/////

////2. Site to site transfer issue/////
function issueSiteToSite($function_filter,$item)
{
	global $db;
 
	$site=$function_filter[0];	
	$from=$function_filter[1];
	$to=$function_filter[2];
	
	if($site!='')
	$filter[]="transfer_issue.sitecode = '".$site."'";	
	if($from!='--' && $to!='--')
	$filter[]="transfer_issue.issuedate <='".$from."'";
	if($item!='')
	$filter[]="transfer_issue_details.mst_itemid = '".$item."'";
	
	$filter=implode(' and ',$filter);
	     $sql1="Select SUM(transfer_issue_details.issueqty)  from transfer_issue left join transfer_issue_details on(transfer_issue.id=transfer_issue_details.transfer_issue_id) where $filter";
	$result1=DB_query($sql1,$db);
	$myrow1=DB_fetch_array($result1);
	$return_array=$myrow1['SUM(transfer_issue_details.issueqty)'];
	//$avg_rate=$myrow1['SUM(transfer_issue_details.rate)'];
	//$return_array[]=$avg_rate;
	return $return_array;
	
}
////3. Material return to vendor///
function issueMatarialReturn($function_filter,$item)
{
	global $db;
	$site=$function_filter[0];
	$from=$function_filter[1];
	$to=$function_filter[2];
	
	if($site!='')
	$filter[]="inv_material_return.sitecode = '".$site."'";
	if($from!='--' && $to!='--')
	$filter[]="inv_material_return.MRNDate <='".$from."'";
	if($item!='')
	$filter[]="inv_material_return_details.mst_itemid = '".$item."'";
	
	$filter=implode(' and ',$filter);
	
  $sql1="Select SUM(inv_material_return_details.ReturnQty) from inv_material_return left join inv_material_return_details on(inv_material_return.id=inv_material_return_details.parentId) where $filter";
	$result1=DB_query($sql1,$db);
	$myrow1=DB_fetch_array($result1);
	return $myrow1['SUM(inv_material_return_details.ReturnQty)'];
}
	
		
		
		
		
		
		
		/*********************************************************************************/












if($_REQUEST['RequisitionNo']!='' && $_REQUEST['Delete']=='1')
{
	  $delete_sql1="Delete from materialrequisitions where requisitionno='".$_REQUEST['RequisitionNo']."'";
	 $delete_res1=DB_query($delete_sql1,$db);
 	$delete_sql2="Delete from requisitionorderdetails where requsitionno='".$_REQUEST['RequisitionNo']."'";
	 $delete_res2=DB_query($delete_sql2,$db);
 		$delete_sql3="Delete from comprative_detail where RequisitionNo='".$_REQUEST['RequisitionNo']."'";
	 $delete_res3=DB_query($delete_sql3,$db);

	 
	 echo "<script>location.href='index.php?route=MR_SelectOSMaterialRequi&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";
 }
if($_REQUEST['cancel'])
{
	
	unset($_SESSION['date']);
	unset($_SESSION['site']);
	unset($_SESSION['requisition_no']);
	unset($_SESSION['remarks']);
	unset($_SESSION['itemlist']);
	unset($_SESSION['ACGRequisition-ItemList']);
	unset($_SESSION['ACGRequisition-ItemList_1']);
	unset($_SESSION['manvi']); 
	unset($_SESSION['requsition_itemcode']);
	
	
}
if($_REQUEST['item_popup'])
{
	$_SESSION['date']=$_REQUEST['date'];
	$_SESSION['site']=$_REQUEST['site'];
	$_SESSION['requisition_no']=$_REQUEST['requisition_no'];
	$_SESSION['remarks']=$_REQUEST['remarks'];
	$_SESSION['ACGRequisition-ItemList_1'];
	
} 
if($_REQUEST['Save'])
{
$fstatus=true;
  if($_REQUEST['site']=='000')
  {
  	  $msgErr[]="Please Select Branch Name"	;
      $fstatus=false;
  }
  if(empty($_SESSION['ACGRequisition-ItemList_1']))
  {
  $msgErr[]="Please Select Item";
      $fstatus=false;	
  }
  
  $qty=$_REQUEST['item_code'];
  for($i=0;$i<count($qty);$i++)
  {
  	if($_REQUEST['required_qty'][$i]=='')
  {
  	  $msgErr[]="Please Enter Required Qty"	;
      $fstatus=false;
  } 
  if($_REQUEST['requisition_qty'][$i]=='')
  {
  	  $msgErr[]="Please Enter Requisition Qty"	;
      $fstatus=false;
  } 
	
	
  }
	
}
if(isset($_POST['DeleteRow']))		 
{
 if(!empty($_REQUEST['delitem']))
 {	
 $ListItem=explode('#',$_SESSION['ACGRequisition-ItemList_1']);
  for($i=0;$i<count($_REQUEST['delitem']);$i++)
   {	  
		 $key=array_search($_REQUEST['delitem'][$i],$ListItem);
  		 if($key!==false)
		 unset($ListItem[$key]);
		 $itemlist1=implode("#",$ListItem);
		 $_SESSION['ACGRequisition-ItemList_1']=$itemlist1;
		  }
 }
 
 }


if($_REQUEST['Save']!='' and $fstatus)
{
  	$prefix_sql=DB_query("Select * from prefix_tbl where prefix_name='".$PageName."'",$db);
	$prefix_row=DB_fetch_array($prefix_sql);
	$prefix=$prefix_row['prefix_code'];

    $sql="Select Reqno from materialrequisitions where sitecode='".$_REQUEST['site']."' order by Reqno desc limit 1";
$result=DB_query($sql,$db);
$myrow=DB_fetch_array($result);
//echo DB_num_rows($result);
if(DB_num_rows($result)>0)
{
	$Reqno=$myrow['Reqno'];
	$req_part1=substr($Reqno,-4);
	//echo $req_part1;
	$req_final=$req_part1+1;
	//echo "<br>".$req_final;
}
else
{
	$req_final="1";
}

$string=$prefix."/".$_REQUEST['site']."/".$year."-".$year_after."/";
$final_string=$string.str_pad($req_final,4,"0",STR_PAD_LEFT);
	
	$requisition_sql="Insert into materialrequisitions set
									requisitionno='',
									comments='".$_REQUEST['remarks']."',
									prdate='".FormatDateForSQL($_REQUEST['date'])."',
									initiator='".$_SESSION['UserID']."',
									sitecode='".$_REQUEST['site']."',
									Reqno='".$final_string."' ";
	//echo "<pre>";
	//print_r($requisition_sql); exit;
	$requisition_res=DB_query($requisition_sql,$db);
	$last_id=DB_Last_Insert_ID($db,'materialrequisitions','id');
	
	if($last_id!='')
	{
		for($cr=0;$cr<$_REQUEST['ctr'];$cr++)
		{
		   	$material_details_sql="insert into requisitionorderdetails set
											id='',											
											requsitionno='".$last_id."',
											mst_itemid='".$_REQUEST['mst_itemid'][$cr]."' ,											
											product_id='".$_REQUEST['item_code'][$cr]."',
 											product_description='".$_REQUEST['item_name'][$cr]."',
											make='".$_REQUEST['Make'][$cr]."',    
											color='".$_REQUEST['Color'][$cr]."',   
											grade='".$_REQUEST['Grade'][$cr]."',
											size='".$_REQUEST['size'][$cr]."',
											gsm='".$_REQUEST['gsm'][$cr]."',
											required_qty='".$_REQUEST['required_qty'][$cr]."',
											min_qty='".$_REQUEST['min_qty'][$cr]."',
											requisition_qty='".$_REQUEST['requisition_qty'][$cr]."',
											Remarks='".$_REQUEST['remark'][$cr]."',
											stock_qty='".$_REQUEST['stock_qty'][$cr]."'"; 
			//echo "<pre>";
			//print_r($material_details_sql);
		//	echo "<br>---------------<br>";
			$details_res=DB_query($material_details_sql,$db);
		}
	}

	unset($_SESSION['date']);
	unset($_SESSION['site']);
	unset($_SESSION['requisition_no']);
	unset($_SESSION['remarks']);
	unset($_SESSION['date']);
	unset($_SESSION['site']);
	unset($_SESSION['requisition_no']);
	unset($_SESSION['remarks']);
	unset($_SESSION['itemlist']);
	unset($_SESSION['ACGRequisition-ItemList']);
	unset($_SESSION['ACGRequisition-ItemList_1']);
	
	unset($_SESSION['manvi']); 
	unset($_SESSION['requsition_itemcode']);
	

 
prnMsg( _('Requisition No. - '.$_REQUEST['requisition_no'].' Saved Successfully'),'success');
  echo "<script>location.href='index.php?route=MR_SelectOSMaterialRequi&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>"; 
 
}
?>
<script language="javascript" type="text/javascript">
function CalrequiredQty(val,i){
//alert(i);
 
var a=	document.getElementById("stock_qty_"+i).value;
if(a=='')
a=document.getElementById("stock_qty_"+i).value=0;

var b=	document.getElementById("min_qty_"+i).value;
if(b=='')
b= document.getElementById("min_qty_"+i).value=0;


	document.getElementById("required_qty_"+i).value=parseFloat(val)-parseFloat(a) + parseFloat(b);

 
}

function open_items()
{
	var site=document.getElementById("site").value;
	var date=document.getElementById("date").value;
	
	if(site==000){
		alert("Please select Site First.");
		return false;
	}

	window.open("requisition_items.php?action=add&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>&route=<?php echo $_REQUEST['route'];?>&site="+site+"&date="+date,"item_popup_window","height=500,width=500,toolbar=no,menubar=no,dependent=yes,resizable =yes, scrollbars=yes");
}
function generate_reqno(str)
{
	if (str.length==0)
  {
  document.getElementById("reqno").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("reqno").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","get_reqno.php?site="+str,true);
xmlhttp.send();
}
function check_approveqty(str,j)
{
	var req_qty=document.getElementById("req_qty_"+j).value;
	if(str>req_qty)
	{
		alert("Quantity to approve cannot be greater than requsition quantity");
		document.getElementById("app_qty_"+j).value='';
		document.getElementById("app_qty_"+j).focus();
	}
}
function get_AppQty(i,str)
{
if(str!=''){
var req_qty=document.getElementById("app_qty1_"+i).value;
var app_qty=parseFloat(req_qty)-parseFloat(str);
/*if(parseFloat(str)>parseFloat(req_qty))
{
	alert('Approved quantity cannot be greater then requisition quantity');
	document.getElementById("app_qty_"+i).value='';
	document.getElementById("app_qty2_"+i).value=document.getElementById("app_qty1_"+i).value;
	return false;
}*/
if(app_qty>0){final=app_qty;}else{final='0';}
document.getElementById("app_qty2_"+i).value=final;}
else{document.getElementById("app_qty2_"+i).value=document.getElementById("app_qty1_"+i).value;}
}
</script>

<!--<a href="MR_SelectOSMaterialRequi.php">Back>></a>-->
<?php if($_REQUEST['RequisitionNo']=='')
{ ?>
	<table width="70%" border="0">	
<?php if(count($msgErr)>0){?>
   <tr>
   <td colspan="4"><?php
   for($i=0;$i<count($msgErr);$i++)
   {
     echo "<div class='error'>".$msgErr[$i].'</div>';
   }
    ?></td>
   </tr>
   <?php } ?>	
	</table>
	
	
	
<h2 align="center"><strong><?php  echo $page_title;?></strong></h2>
<h3 align="center"><font color="#FF0000">Please enter the requisition details first</font></h3>
<form name="RequisitionDetailsform" action="" method="post" >

<fieldset><legend>Requisition Details</legend>
<table width="100%" border="1" cellspacing="0" cellpadding="3" align="center" style="border-collapse:collapse;">
  <tr>
    <th><strong>REQUISITION DATE</strong></th>
    <td><input type="text" name="date" id="date" style="width:100%" class="datepicker" readonly="true" value="<?php if(isset($_SESSION['date']))echo $_SESSION['date']; else echo date('d/m/Y');?>" onchange="checkReqDate()"></td>
    <th rowspan="3"><strong>REMARKS</strong></th>
    <td rowspan="3"><textarea name="remarks" style="width:100%" rows="3"><?php echo $_SESSION['remarks'];?></textarea></td>
  </tr>
  <tr>
    <th><strong>SITE</strong></th>
    <td>
	<?php 
 
		$ss="Select loccode,locationname from locations";
		$site_sql=DB_query($ss,$db);
 	?>
	<select name="site" id="site" style="width:100%">
      <option value="000">---Select---</option>
      <?php
	while($site_row=DB_fetch_array($site_sql)){
	?>
      <option value="<?php echo $site_row['loccode'];?>"<?php echo ($_SESSION['site']==$site_row['loccode']?'selected':'')?>><?php echo $site_row['locationname'];?></option>
      <?php } ?>
    </select></td>
  </tr>
  <tr>
    <th><strong>REQUISITION NUMBER </strong></th>
    <td><div id="reqno">
        <input name="requisition_no" type="text" id="requisition_no" value="Auto generation after saving" style="width:100%" readonly="true" />
      </div></td>
  </tr>
</table>
</fieldset>


<p align="left">
<input type="hidden" name="date1" value="<?php echo $_SESSION['date'];?>" />
<input type="hidden" name="site1" value="<?php echo $_SESSION['site'];?>" />
<input type="hidden" name="requisition_no1" value="<?php echo $_SESSION['requisition_no'];?>" />
<input type="hidden" name="remarks1" value="<?php echo $_SESSION['remarks'];?>" />
<div style="padding-left:40px; text-align:left;">
<input class="bottonsview1" type="submit" name="item_popup" value="Add Items" id="item_popup"  onclick="return open_items();" />
<input type="submit" name="DeleteRow" value="Delete" class="bottonsview1" onclick="return confirm('Are you sure you want to delete?')"/>	
	
</div></p> 


<div style="clear:both;"></div>


<fieldset><legend>Item Details</legend>
<div style="overflow:auto; width:100%; height:auto">
<table width="100%" border="1" align="center" cellpadding="3" cellspacing="0">
  <tr>
  	<th width="6" align="center">Select</th>
    <th width="6%" align="center">Item Code </th>
    <th width="8%" align="center">Item Name </th>
    <th width="13%" align="center">Make</th>
    <th width="8%" align="center">Grade</th>
    <th width="8%" align="center">Color</th>
	<th width="8%" align="center">Size</th>
	<th width="6%" align="center">Unit</th>
    <th width="8%" align="center">Stock In Hand  </th>
    <th width="10%" align="center">Req. Qty </th>
	<th width="8%" align="center">Minimum Qty. in Store </th>
    <th width="10%" align="center">Required Qty. </th>
    <th width="30%" align="center">Remarks</th>
    </tr>
<?php
//print_r($_SESSION['ACGRequisition-ItemList_1']);
if(isset($_SESSION['ACGRequisition-ItemList_1']))
{
 /************ call stock function ****************/
 
$function_filter[]=$_SESSION['site'];;
$function_filter[]=FormatDateForSQL($_SESSION['date']); 
$function_filter[]=FormatDateForSQL($_SESSION['date']); 
 /*************************************************/


	$store=$s->getField('storetype','Store_Site',$_SESSION['site'],'StoreCode');
$itemlist=array();
//print_r($_SESSION['ACGRequisition-ItemList']);
$itemlist=explode('#',$_SESSION['ACGRequisition-ItemList_1']);
//print_r($itemlist);
?>
	<?php 
	for($i=0;$i<count($itemlist);$i++)
	{
//	echo "select * from item_master where StockID='".$itemlist[$i]."'";
	 $itemquery=DB_query("select * from item_master where StockID='".$itemlist[$i]."'" , $db);
	 //echo "select StockID,item_name,unit, make ,grade, color from item_master where StockID='".$itemlist[$i]."'" ;
	while($item_row=DB_fetch_array($itemquery))
	{
	
	
	      $op=openingBalance($function_filter,$item_row['id']);
 		  $in_1=receivedMRN($function_filter,$item_row['id']);
 		  $out_1=issueSlip($function_filter,$item_row['id']);
		  $out_2=issueSiteToSite($function_filter,$item_row['id']);		
		  $in_2=receivedSiteToSite($function_filter,$item_row['id']);
		  $out_3=issueMatarialReturn($function_filter,$item_row['id']);		  
		  $in_3=receivedReturn($function_filter,$item_row['id']);	
		  $invalue=$op+$in_1+$in_2+$in_3;
		  $outvalue=$out_1+$out_2+$out_3;
   		  $stockbalance=$invalue-$outvalue;
	
		/*if($i%2==0)
		{$bg="#CCCCCC";}
		else
		$bg="#C8BECB";*/
	
	?>
	<tr bgcolor="#FFFFFF">	
	<td><input name="delitem[]" type="checkbox" value="<?php echo $item_row['StockID'];?>" /><img src="images/Icon_Delete.png" height="15" width="15"></td>	
	<td style="height:10px"><?php 
 
	echo $itemlist[$i];?>
   <input type="hidden" name="mst_itemid[<?php echo $i;?>]" id="mst_itemid_<?php echo $i;?>" value="<?php echo $item_row['id'];?>">	
	<input type="hidden" name="item_code[<?php echo $i;?>]" id="item_code_<?php echo $i;?>" value="<?php echo $itemlist[$i];?>">	</td>
	<td style="height:10px"><?php echo $item_row['item_name'];?><input type="hidden" name="item_name[<?php echo $i;?>]" id="item_name[<?php echo $i;?>]" value="<?php echo $item_row['item_name'];?>"/>	</td>
	<td style="height:10px">
	<?php //echo 	$item_row['make'].$item_row['grade'].$item_row['color'];?>
	
	<select name="Make[<?php echo $i;?>]" id="Make" style="width:100%">
		<option value="0">Select Make</option>
      <?php
			 $querymake=DB_query("select * from product_manufacture where 1=1" ,$db);
			while($que_row=DB_fetch_array($querymake))
			{ 
 		 ?>
      <option value="<?php echo $que_row['id'];?>" <?php echo ($item_row['make']==$que_row['id'] ?'selected':'')?>><?php echo $que_row['manufacturer'];?></option>
      <?php  }?>
	  </select></td>
	<td style="height:10px"><select name="Grade[<?php echo $i;?>]" style="width:100%">
		<option value="0">Select Grade</option>
		<?php
			 $querygrade=DB_query("select * from product_grade where 1=1" ,$db);
			while($que_row=DB_fetch_array($querygrade))
			{ 
 		 ?>
      <option value="<?php echo $que_row['id'];?>" <?php echo ($item_row['grade']==$que_row['id']?'selected':'')?>><?php echo  $que_row['grade'];?></option>
      <?php  }?>
	  </select></td>
	<td style="height:10px"><select name="Color[<?php echo $i;?>]" style="width:100%">
		<option value="0">Select Color</option>
		<?php
			 $querycolor=DB_query("select * from product_color where 1=1" ,$db);
			while($que_row=DB_fetch_array($querycolor))
			{ 
 		 ?>
      <option value="<?php echo $que_row['id'];?>" <?php echo ($item_row['color']==$que_row['id'] ?'selected':'')?>><?php echo  $que_row['color'];?></option>
      <?php  }?></select></td>
		<td style="height:10px">
		 
		  <select name="size[<?php echo $i;?>]" id="size_<?php echo $i;?>" style="width:100%">
		  	<option value="0">Select Size</option>
		    <?php 
		
			$sizeId=DB_query("Select * from size_master ",$db);
			while($sizeRow=DB_fetch_array($sizeId))
			{
		?>
		    <option value="<?php echo $sizeRow['id'];?>"><?php echo $sizeRow['name'];?></option>
		    <?php } ?>
		    </select>		</td>
		<td style="height:10px"><?php
		$grade_query=DB_query("select * from unitsofmeasure where unitid='".$item_row['unit']."'", $db);
		while($grade_row=DB_fetch_array($grade_query))
		 {
		 echo $grade_row['unitname'];?>
		  <?php } ?><input type="hidden" name="Unit[<?php echo $i;?>]" id="Unit[<?php echo $i;?>]" value="<?php $grade_row['id'];?>"/></td>
	<td style="height:10px">
	<?php 
	//echo $item_row['id'];
	
	echo $stockbalance;
	
	 ?>
	<input type="hidden" name="stock_qty[<?php echo $i;?>]" id="stock_qty_<?php echo $i;?>"  readonly="true" value="<?php  echo $stockbalance;?>" style="width:100%"/></td>
	<td align="center" style="height:10px"><input name="requisition_qty[<?php echo $i;?>]" type="text" id="requisition_qty_<?php echo $i;?>"  style="width:100%" size="14" onblur="CalrequiredQty(this.value,<?php echo $i;?>)" /></td>
	<td> <?php echo $item_row['min_qty'];?> <input type="hidden" name="min_qty[<?php echo $i;?>]" id="min_qty_<?php echo $i;?>" value="<?php echo $item_row['min_qty'];?>"></td>
    <td align="center" style="height:10px"><input name="required_qty[<?php echo $i;?>]" type="text" id="required_qty_<?php echo $i;?>" style="width:100%"/></td>
     <td align="center" style="height:10px">
	 
	 <textarea name="remark[<?php echo $i;?>]" cols="10" rows="1" id="remark_<?php echo $i;?>"></textarea>	 </td>
	</tr><?php }}?> 
	 
  <?php } ?>
  <input type="hidden" name="ctr" id="ctr" value="<?php echo $i;?>" />
</table>
</div>
</fieldset>

<p align="center"><input type="submit" name="Save" value="Save" class="bottonsview1"  onsubmit="return formvalidate()">&nbsp;<input type="submit" name="cancel" value="Cancel" class="bottonsview1"></p>
</form>

<?php }

if($_REQUEST['RequisitionNo']!='' && $_REQUEST['Approve']=='1')
{
 
if(isset($_REQUEST['dataapprove']))
{
/*
print_r($_REQUEST);
exit;
*/

 $f=0;
 $comid=array();
 	for($CTR=0;$CTR<$_REQUEST['count_req'];$CTR++)
	{
	
	   $darr['mst_itemid']=$_REQUEST['mst_itemid'][$CTR];
	   $darr['make']=$_REQUEST['Make'][$CTR];
	   $darr['color']=$_REQUEST['Color'][$CTR];
	   $darr['grade']=$_REQUEST['Grade'][$CTR];
	   $darr['size']=$_REQUEST['sizedata'][$CTR];	   
	   $darr['status']=$_REQUEST['MRstatus'][$CTR];
	   
	 
	   $get_last_approved=DB_query("select app_qty_for_qtn,App_quantity from requisitionorderdetails 
	   where requsitionno='".$_REQUEST['RequisitionNo']."' and mst_itemid='".$_REQUEST['mst_itemid'][$CTR]."'",$db);
	   $get_last_app_row=DB_fetch_array($get_last_approved);
	   $last_approved_qty=$get_last_app_row['App_quantity'];
	  $darr['App_quantity']=$_REQUEST['app_qty'][$CTR]!=''?($_REQUEST['app_qty'][$CTR]+$last_approved_qty):(0+$last_approved_qty);	   
	   $darr['pending_qty']=$_REQUEST['app_qty2'][$CTR];
	   
	  $last_qty_for_quotation=$get_last_app_row['app_qty_for_qtn'];
	  if($last_qty_for_quotation==''){$darr['app_qty_for_qtn']=$_REQUEST['app_qty'][$CTR];}
	  else if($last_qty_for_quotation!='')
	  {
	 //echo "Select * from vendorquotationdetails where requisition_no='".$_REQUEST['RequisitionNo']."' and mst_productid='".$_REQUEST['mst_itemid'][$CTR]."' and quantity='".$last_qty_for_quotation."'";
	  	$check_qtn_qty=DB_query("Select * from vendorquotationdetails where requisition_no='".$_REQUEST['RequisitionNo']."' and mst_productid='".$_REQUEST['mst_itemid'][$CTR]."' and quantity='".$last_qty_for_quotation."'",$db);
		$records=DB_num_rows($check_qtn_qty);
	  	//echo $records;
		if($records=='0')
		{
			$darr['app_qty_for_qtn']=$last_qty_for_quotation+$_REQUEST['app_qty'][$CTR];
		}
		else //$last_qty_for_quotation
	{ if($_REQUEST['app_qty'][$CTR]!=''){$darr['app_qty_for_qtn']=$_REQUEST['app_qty'][$CTR];} else{$darr['app_qty_for_qtn']=$last_qty_for_quotation;} }
	  }	  
	  
	  //**************To check if any item is left pending after assigning for PO***********//
	 $check_pending_after_assigned=DB_query("Select App_quantity1,destroyed_qty from requisitionorderdetails where requsitionno='".$_REQUEST['RequisitionNo']."' and mst_itemid='".$_REQUEST['mst_itemid'][$CTR]."'",$db);
	 $get_row=DB_fetch_array($check_pending_after_assigned);
	 
	  
	  if($get_row['App_quantity1']!='' and $_REQUEST['app_qty'][$CTR]!='')
	  {
	  	 $darr['destroyed_qty']=$get_row['App_quantity1']+$get_row['destroyed_qty'];
		 $darr['App_quantity1']='';
	  }
	 
	 if($_REQUEST['app_qty'][$CTR]!='')
	 {
	 	$darr['app_status']='0';
	 }
	 
	  $comid[]=$_REQUEST['mst_itemid'][$CTR];
	 
	   if($darr['pending_qty']=='0')
	   {$darr['AppStatus']=1;}
	   else
	   {$darr['AppStatus']=0;}
	   
	    $darr['iteam_approval_remarks']=$_REQUEST['iteamappremarks'][$CTR];	
	    $darr['approved_date']=FormatDateForSQL(date('d/m/Y'));
	    $darr['status']=$_REQUEST['MRstatus'][$CTR];	  
	   	$cond1="requsitionno='".$_REQUEST['reqid']."'	and product_id='".$_REQUEST['item_code'][$CTR]."'";
		 $rt=$s->RecordEdit('requisitionorderdetails', $darr, $cond1);
		 
		//*******Update the Id of the person who has approved (IMPORTANT)**********//
		$update_approval=DB_query("Update materialrequisitions 
		set approved_by='".$_SESSION['UserID']."' where requisitionno='".$_REQUEST['RequisitionNo']."'",$db);
		
		 
		 /*####################################Insertion Of Approved Requisition Details############################*/

 //$approved_insert=DB_query("insert into req_app_details set Reqno='".$_REQUEST['RequisitionNo']."',ItemId='".$_REQUEST['mst_itemid'][$CTR]."',ReqQty='".$_REQUEST['req_qty'][$CTR]."',AppQty='".$_REQUEST['app_qty'][$CTR]."',PendingQty='".$_REQUEST['app_qty2'][$CTR]."',AppDate='".FormatDateForSql($_REQUEST['app_date'][$CTR])."'",$db);
		}
			
	  $check_vender=DB_query("select mst_product_list, Vendor_Quot_No from comprative_detail where 
	                RequisitionNo='".$_REQUEST['RequisitionNo']."'",$db);					
					$numcom=DB_num_rows($check_vender);
					
	  if($numcom>0)
	  {	 
	   $flag=0;
	   $vender=DB_fetch_array($check_vender,$db);
	   
	   $data1=explode(",",$vender['mst_product_list']);
	   for($t=0;$t<count($data1);$t++)
	   {
	   if(in_array($data1[$t],$comid))
	   {
	    $flag=$flag+1;
	   }
	   }
	   if($flag==count($data1))
	   {
	  // echo "update   venderquotations  set  comprative_status='1' where id='".$vender['Vendor_Quot_No']."'";
	    $update=DB_query("update   venderquotations  set  comprative_status='1' where id='".$vender['Vendor_Quot_No']."'",$db);
	    }
	   
	  }
	   
	 	    $dataArray1['comments']=$_REQUEST['remarks'];
			 $dataArray1['approval_remarks']=$_REQUEST['apprremarks'];
		    $dataArray1['requisitionno']=$_REQUEST['RequisitionNo'];
			$dataArray1['status']='1';
			$cond="requisitionno='".$_REQUEST['RequisitionNo']."'";			
		 	$rt=$s->RecordEdit('materialrequisitions', $dataArray1, $cond);
			
			if(!$rt)
			{
			   die('not saved');
			}
			
  
echo "<script>location.href='index.php?route=MR_SelectOSMaterialRequi&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";  
}
//echo "Select Reqno,comments from materialrequisitions where requisitionno='".$_REQUEST['RequisitionNo']."'";
$req_sql=DB_query("Select Reqno,comments,approval_remarks from materialrequisitions where requisitionno='".$_REQUEST['RequisitionNo']."'",$db);
$req=DB_fetch_array($req_sql);
?>

<form action="" method="post">


<h2 align="center"><strong>Approve Requisition - <?php echo $req['Reqno'];?></strong></h2>
 
<input type="hidden" name="reqid" value="<?php echo $_REQUEST['RequisitionNo'];?>" />
<div style="overflow:auto; width:100%;">
<table width="100%" border="1" cellspacing="0" cellpadding="3" bgcolor="#E0E8AC" style="border-collapse:collapse;">
  <tr>
    <th><strong>ITEM CODE </strong></th>
    <th><strong>ITEM NAME </strong></th>
    <th><strong>MAKE</strong></th>
    <th><strong>GRADE</strong></th>
    <th><strong>COLOR</strong></th>
    <th><strong>SIZE</strong></th>
    <th><strong>UNIT</strong></th>
    <th><strong>TOTAL STOCK </strong></th>
    <th><strong>REQUISITION  QTY</strong></th>
	<th><strong>QTY APPROVED</strong></th>
	<th><strong>PENDING QTY</strong></th>
	<th><strong>APP DATE</strong></th>
	<th><strong>PR REMARKS</strong></th>
	<th><strong>APPROVAL REMARKS</strong></th>	
	<th><strong>ACTION</strong></th>
  </tr>
		<?php 
	     $get_sql="Select * from requisitionorderdetails where requsitionno='".$_REQUEST['RequisitionNo']."'
		and status!='Inactive'
		";
		$get_result=DB_query($get_sql,$db);		
	     $i=0;			
		while($get_row=DB_fetch_array($get_result))
		{
		 	 $App_Status=$get_row['AppStatus'];
		 	$Req_qty=$get_row['req_quantity'];
		 	//$App_Qty=$get_row['AppQty'];
		 	$pending_qty=$get_row['pending_qty'];
			
		 	$requisition_qty=$get_row['requisition_qty'];
		    $App_quantity=$get_row['App_quantity'];
		 
		 	if($App_quantity>=$requisition_qty){$Diff=0;}
		 	elseif($App_quantity<$requisition_qty){$Diff=$requisition_qty-$App_quantity;}
		 
		 /*if($App_Qty!='0')
		 {
		 $Diff= $App_Qty;
		 }
		 else
		 {
		 $Diff=$Req_qty;		 
		 }*/
		
		   $Approved_Qty=$get_row['AppQty'];		
		if($Approved_Qty!='0' || $App_Status=='')
		{
		?>
	  <tr bgcolor="#FFFFFF">
  	  <td><?php //echo $get_sql?>
	  <?php echo $get_row['product_id'];?><input type="hidden" name="item_code[<?php echo $i;?>]" id="item_code_<?php echo $i;?>" value="<?php echo $get_row['product_id'];?>">
	  
	  <input type="hidden" name="mst_itemid[<?php echo $i;?>]" id="mst_itemid_<?php echo $i;?>" value="<?php echo $get_row['mst_itemid'];?>">
	  </td>      
    <td><?php echo $get_row['product_description'];?><input type="hidden" name="item_name[<?php echo $i;?>]" id="item_name_<?php echo $i;?>" value="<?php echo $get_row['product_description'];?>"></td>
    <td> 
	
	<select  name="Make[<?php echo $i;?>]" id="Make_" style="width:100px">
		<option value="0">Select Make</option>
      <?php
			 $querymake=DB_query("select * from product_manufacture " ,$db);
			while($que_row=DB_fetch_array($querymake))
			{ 
 		 ?>
      <option value="<?php echo $que_row['id'];?>" <?php echo ($get_row['make']==$que_row['id'] ?'selected':'')?>><?php echo $que_row['manufacturer'];?></option>
      <?php  }?>
	  </select>
  </td>
    <td> 
	<select  name="Grade[<?php echo $i;?>]" id="Grade_" style="width:100px">
		<option value="0">Select Grade</option>
      <?php
			 $querymake=DB_query("select * from product_grade " ,$db);
			while($que_row=DB_fetch_array($querymake))
			{ 
 		 ?>
      <option value="<?php echo $que_row['id'];?>" <?php echo ($get_row['grade']==$que_row['id'] ?'selected':'')?>><?php echo $que_row['grade'];?></option>
      <?php  }?>
	  </select>
 </td>
    <td>
	<select  name="Color[<?php echo $i;?>]" id="Color_" style="width:100px">
		<option value="0">Select Color</option>
      <?php
			 $querymake=DB_query("select * from product_color " ,$db);
			while($que_row=DB_fetch_array($querymake))
			{ 
 		 ?>
      <option value="<?php echo $que_row['id'];?>" <?php echo ($get_row['color']==$que_row['id'] ?'selected':'')?>><?php echo $que_row['color'];?></option>
      <?php  }?>
	  </select> </td>
	  <td>
	  <select name="sizedata[<?php echo $i;?>]" id="size_" style="width:100%">
		  	<option value="0">Select Size</option>                                                                                                                                                                                                                                                                                                              
		    <?php 
		
			$sizeId=DB_query("Select * from size_master ",$db);
			while($sizeRow=DB_fetch_array($sizeId))
			{
		?>
		    <option value="<?php echo $sizeRow['id'];?>" <?php echo ($get_row['size']==$sizeRow['id'] ?'selected':'')?>   ><?php echo $sizeRow['name'];?></option>
		    <?php } ?>
	    </select></td>
    <td><?php 
	$unit=$s->getField('item_master','StockID',$get_row['product_id'],'unit');
	$unitname=$s->getField('unitsofmeasure','unitid',$unit,'unitname');
	echo $unitname;?></td>
    <td><?php echo $get_row['stock_qty'];?><input type="hidden" name="stock_qty[<?php echo $i;?>]" value="<?php echo $get_row['stock_qty'];?>" readonly="true" id="stock_qty_<?php echo $i;?>"></td>
    <td> <?php echo $get_row['requisition_qty'];?><input type="hidden" name="req_qty[<?php echo $i;?>]" id="req_qty_<?php echo $i;?>"  readonly="true" value="<?php echo $get_row['requisition_qty'];?>" size="10"  	>	
	
	</td>
	<td><input type="text" name="app_qty[<?php echo $i;?>]" id="app_qty_<?php echo $i;?>" value="" size="10"  onkeyup="get_AppQty(<?php echo $i;?>,this.value)" <?php if($Diff==0) { ?> readonly="readonly" <?php } ?>  >
	</td>
	<td>
	
	<input type="hidden" name="app_qty1[<?php echo $i;?>]"  id="app_qty1_<?php echo $i;?>" readonly="true"  size="10" value="<?php echo  $Diff ; ?>">
	<input type="text" name="app_qty2[<?php echo $i;?>]"  id="app_qty2_<?php echo $i;?>" readonly="true"  size="10"  value="<?php echo $Diff;?>">
     <!--	 onblur="check_approveqty(this.value,<?php //echo $i;?>)"-->
	</td>
	<td>
	
	<input type="text" name="app_date[<?php echo $i;?>]"  id="app_date_<?php echo $i;?>" readonly="true"  size="10"  class="datepicker" value="<?php echo date('d/m/Y');?>">
     <!--	 onblur="check_approveqty(this.value,<?php //echo $i;?>)"-->
	</td>
	
	
	<td><?php echo $get_row['Remarks'];?></td>
	
	
	<td><textarea name="iteamappremarks[<?php echo $i;?>]"><?php echo $get_row['iteam_approval_remarks'];?></textarea></td>	
	
	
	<td><select  name="MRstatus[<?php echo $i;?>]" id="MRstatus_<?php echo $i;?>"   style="width:50px">
		 <option value="Active" <?php echo $MRstatus=='Active'?'selected':''?>  >Active</option>
 		 <option value="Inactive" <?php echo $MRstatus=='Inactive'?'selected':''?> >Inactive</option>
		  <!--<option value="Declined" <?php //echo $MRstatus=='Declined'?'selected':''?> >Declined</option>
		   <option value="Davation" <?php //echo $MRstatus=='Davation'?'selected':''?> >Davation</option>-->
		 </select>
	
	</td>
  </tr>
  <?php }
  $i++; }
  ?>
  <input type="hidden" name="count_req" value="<?php echo $i;?>" id="count_req"/>
  <tr><th>PR Remarks</th><td colspan="14"><textarea name="remarks" style="width:100%" ><?php echo $req['comments']; ?> </textarea></td></tr>
  
  
    <tr><th>Approval Remarks</th><td colspan="14"><textarea name="apprremarks" style="width:100%" ><?php echo $req['approval_remarks']; ?> </textarea></td></tr>
	
	
</table>
</div>
<p align="center">
  <input type="submit" class="bottonsview1" name="dataapprove" value="Approve"  onclick="return validate1()" />
</p>
<!--onclick="return validate()"-->
</form>
<?php 	
}
?>
<?php 
include('includes/footer.inc');
?>



<script language="javascript" type="text/javascript">
function checkReqDate()
{
	
	var date=document.getElementById("date").value;
	var from_date= document.getElementById('date').value;  
	    
var curr_date2='';	
var curr_month2='';
var d = new Date();
//alert(d.format("m/dd/yy"));
var curr_date = d.getDate();
var curr_month1 = d.getMonth();
var curr_year = d.getFullYear();
var curr_month=curr_month1+1;
var t=curr_month;
var d=curr_date;
if(t!=10 || t!=11 ||t!=12 )
{
 curr_month2="0" + curr_month;	
}
else
{
 curr_month2=curr_month;	
}
if(d==1 || d==2 || d==3 || d==4 || d==5 || d==6 || d==7 || d==8 || d==9 )
{
 curr_date2="0" + curr_date;		
}
else
{
 curr_date2=curr_date;		
}


var datedat=(curr_date2 + "/" + curr_month2 
+ "/" + curr_year);

	
	
		if(date<datedat)
		{
			alert("Requisition Date Can't Be Less than Current Date");
			document.getElementById("date").focus;
			return false;
		}

	
}

function formvalidate()
{
	var counter=document.getElementById("ctr").value;
	
	if(document.RequisitionDetailsform.site.value=='000')	
		{
			alert("Please Select Site And Requisition No");
			return false;
		}
		for(var x=0;x<counter;x++)
	{
		var approve=document.getElementById("requisition_qty_"+x).value;
		
		if(approve=='')
		{
			alert("Please enter Requisition Quantity");
			document.getElementById("requisition_qty_"+x).focus();
			return false;
		}
		
	}
	return true;
}


function validate1()
{


	var counter=document.getElementById("count_req").value;
	
	
	var count;
	for(var x=0;x<counter;x++)
	{
		if(document.getElementById("app_qty_"+x).value=='')
		{
		count=1;	
				
		}
		else
		{
		count=0;
		break;
		}
		
		
		
	}
	
	if(count==1)
	{
	alert("Please enter quantity to be approved for atleast one item");
			return false;
	
	}
	return true;
}

</script>