<?php ob_start();
				
	
	if(isset($_POST['Save']))
	   {    
	  date_default_timezone_set('Asia/Calcutta');
	   
			 	$Lastreq_id=$_REQUEST['id'];			 
			
				if($Lastreq_id!='')
				{
					
					for($i=0;$i<count($_REQUEST['itemid']);$i++)
					{		
				     
                        $data['stock_qty2']=$_REQUEST['secondaryqty'][$i]; 
                        $data['receiveqty']=$_REQUEST['receiveqty'][$i];  
			            $cond="id='".$_REQUEST['return_dtl'][$i]."' and parentId='".$Lastreq_id."'";
                        $s->RecordEdit('material_return_details',$data,$cond);
			           			            
			          $data_stock['inwardqty_primary']        =$_REQUEST['receiveqty'][$i];
			          $data_stock['inwardqty_secondary']      =$_REQUEST['secondaryqty'][$i];
			          $cond1="type='RTN' and against_voucher_main_id='".$Lastreq_id."' 
			          and against_voucher_dtls_id='".$_REQUEST['return_dtl'][$i]."'";
			          $s->RecordEdit('stock_valuation_tbl', $data_stock,$cond1);

			          if($_REQUEST['receiveqty'][$i]>=$_REQUEST['pending_qty'][$i])
			          $status_slip="1";
			          else
			          $status_slip="0";			      
			          $update=DB_query("update issueqty set status_Receive='".$status_slip."' where issue_id='".$_REQUEST['issueid']."' 
			          	and mst_itemid='".$_REQUEST['itemid'][$i]."'",$db);
				 
			       }
				  
		 	
		$get_num_rows=DB_query("Select * from issueqty where issue_id='".$_REQUEST['issueid']."'",$db);
		$num_rows=DB_num_rows($get_num_rows);				
		$check_item_stat=DB_query("Select * from issueqty where issue_id='".$_REQUEST['issueid']."'
		and status_Receive='1'",$db);
		$received_num_rows=DB_num_rows($check_item_stat);
		
		if($num_rows==$received_num_rows)
		{  
			$updatePOStat=DB_query("Update addissue set status='Receive' where 
			id='".$_REQUEST['issueid']."'",$db);
		}
		else
		{
			
			$updatePOStat=DB_query("Update addissue set status='Pending' where 
			id='".$_REQUEST['issueid']."'",$db);
		}
     		
			//echo "dfdff";
			//exit;		 
	}
	 
	 prnMsg( _('Record Insert Successfully'),'success');
	$s->pageLocation("index.php?route=Inventory/transation/Return_Slip_index".$rurl);
	 //unset($_REQUEST);
}

$sql="SELECT * FROM `material_return` where id='".$_REQUEST['id']."'";
	$result=DB_query($sql,$db);
	$myrow1=DB_fetch_array($result);
	extract($myrow1);
 ?>
 <link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div">
<h1><?php echo $s->getField('modules_form','id',$_REQUEST['frmid'],'frm_name'); ?></h1>
<form name="form1" action="" method="post">
<table width="100%" cellpadding="3" border="0" cellspacing="0" align="center">
<tr class="row1">
    <td width="13%" align="right"><strong>Branch:</strong></td>
    <td width="20%">
	<?php
		$ss="Select loccode,locationname from locations where CompanyId='".$_SESSION['ACGCompanyId']."' and loccode='".$site."'";
		$site_sql=DB_query($ss,$db);
	
	?>
      <select name="site" id="site" style="width:98%;"  onchange="showsitename159(this.value)">
	<option value="0">Select</option>
      <?php 
			while ($myrow=DB_fetch_array($site_sql))
				{
				?>
      <option value="<?php echo $myrow['loccode']; ?>"<?php echo($site==$myrow['loccode']?'selected':'')?>><?php echo $myrow['locationname'];?></option>
      <?php  }	?>
    </select></td>
    <td width="13%" align="right"><strong>Store:</strong></td>
    <td width="20%"><div id='hid-Godown-div'><?php
	     $sql_store ="select   id, StoreCode, StoreName from storetype where Store_Site='".$site."' and id='".$store."'";
		 $resultStkLocs = DB_query($sql_store,$db);
		?>
      <select name="store" id="store" style="width:98%;">
         <?php 
		while ($myrow=DB_fetch_array($resultStkLocs))
		{		
			?>
        <option value="<?php echo $myrow['id'];?>"><?php echo $myrow['StoreName'];?></option>
        <?php 
		}
		?>
      </select>
 	  </div></td>
      <td width="13%" align="right"><strong>Contractor:</strong></td>
    <td><select name="issueto" id="issueto" style="width:98%;" onchange="getdataitems(this.value,'IssueSlip-div','FindIssueSlip.php?site='+document.getElementById('site').value+'&store='+document.getElementById('store').value+'&type=1')" >
	<option value="0">Select</option>
	<?php 
	$floor_sql=DB_query("Select * from contractor_master where id='".$receivefrom."'",$db);
	while($floor_row=DB_fetch_array($floor_sql))
	{?>
	<option value="<?php echo $floor_row['id'];?>"<?php echo $receivefrom==$floor_row['id']?'selected':''; ?>><?php echo $floor_row['contractor_name'];?></option>
	<?php 	
	}
	?>
    </select></td>
</tr>
<tr class="row1">
    <td align="right"><strong>Employee:</strong></td>
    <td>
	<select name="received_by" id="received_by" style="width:98%;">
		<option value="0">Select</option>
	<?php 
	$floor_sql=DB_query("Select * from empmaster where id='".$receivefrom."'",$db);
	while($floor_row=DB_fetch_array($floor_sql))
	{
			     $p='';
				 if($floor_row['id']==$receivefrom)
				 $p='selected';	
	
	?>
	<option value="<?php echo $floor_row['id'];?>"<?php echo $p; ?>><?php echo $floor_row['emp_name'];?></option>
	<?php 	
	}
	?>
    </select></td>
  	<td align="right"><strong>Issue Slip No.:</strong></td>
    <td id="IssueSlip-div"><input type="text" name="issue_slipno" id="issue_slipno" style="width:98%;" value="<?php echo $s->getField('addissue','id',$issue_slipno,'issue_slipno') ; ?>" readonly ><input type="hidden" name="issueid" value="<?php echo $issue_slipno; ?>" /></td> 	
	<td align="right"><strong>Return Slip No.:</strong></td>
    <td><input name="return_slipno" type="text" id="return_slipno" value="<?php echo $return_slipno; ?>" style="width:98%;" readonly/></td>
   </tr>
  <tr class="row1">  
  	<td align="right"><strong>Return Date:</strong></td>
    <td><input name="returndate" type="text" id="returndate" value="<?php echo ConvertSQLDate($returndate); ?>" style="width:98%;" readonly class="testdatepicker"/></td>
    <td align="right"><strong>Return Type:</strong></td>
    <td><input name="return_type" type="text" id="return_type" readonly value="<?php echo $slip_return_type; ?>" style="width:98%;"/>
    	<?php //echo $slip_return_type;?>
    	<!--<select name="return_type" id="return_type" style="width:256px;" readonly>
		<option value="Process"<?php if($slip_return_type=="Process"){?> selected <?php } ?>>Process</option>
		<option value="Direct" <?php if($slip_return_type=="Direct"){?> selected <?php } ?>>Direct</option>-->
	</td>
	<td colspan="2"></td> 
 </tr>
</table>
<br>
<table width="100%" border="1" cellspacing="0" cellpadding="3" style="border:#808080 1px solid;">
  <tr>
    <th width="12%">Item Code</th>
    <th>Item Name</th>
    <th width="12%" style="text-align:center;">Batch No.</th>
    <th width="8%" style="text-align:center;">Stock</th>
    <th style='text-align:center;' width="8%">Issue Qty.</th>
    <th style='text-align:center;' width="8%">Pending Qty.</th>
    <!-- <th class="tabledata1" style='text-align:center;'  width="100" >Pending Qty </th>-->
   	<th colspan="5" style='text-align:center;'>Received Qty.</th>
    <!--<td class="tabledata1"><strong>Unit</td>-->
  <!-- <td class="tabledata1"><strong>Batch No</strong></td>
    <td class="tabledata1" colspan="2"><strong><center>Specification</center></strong></td>
    <td class="tabledata1"><strong>Issue Qty </strong></td>
   	<td class="tabledata1" colspan="3" style='text-align:center;'><strong>Received Qty </strong></td>-->
  </tr>
   <?php 
  if($_REQUEST['id']!=''){
  $detailsSql="select * from material_return_details where parentId='".$_REQUEST['id']."' ";
  $detailsResult=DB_query($detailsSql,$db);
  $i=0;
  while($detailsRow=DB_fetch_array($detailsResult))
  {
  	  $unitname=$s->getField('unitsofmeasure','unitid',$detailsRow['mst_unitid'],'unitname');
  	   $unitname1=$s->getField('unitsofmeasure','unitid',$detailsRow['conv_unitid'],'unitname');
  	 // echo $unitname;

  	   $check_last_mrn="Select sum(receiveqty),issueqty,sum(stock_qty2) as stock_qty2 from material_return_details 
  	   inner join material_return       on material_return.id=material_return_details.parentId 
  	   where material_return.issue_slipno='".$issue_slipno."'
                  and material_return_details.itemid='".$detailsRow['itemid']."'  and mst_unitid='".$detailsRow['mst_unitid']."'";
  	  
  	           $last_mrn_res=DB_query($check_last_mrn,$db);
				
				$last_mrn_row=DB_fetch_array($last_mrn_res);

				if($last_mrn_row['issueqty']!='' && $last_mrn_row['sum(receiveqty)']!='' )
						{
						$pending_qty=$last_mrn_row['issueqty']-($last_mrn_row['sum(receiveqty)']);
						}
						else
						{
						$pending_qty=$PORecDetails['issueqty'];
						}


	$query = "SELECT sum(inwardqty_primary) as inwardqty_primary,sum(outwardqty_primary) as outwardqty_primary,date_of_mfg,date_of_expiry,batch_no
   FROM `stock_valuation_tbl` where mst_itemid = '".$detailsRow['itemid']."' and site='".$myrow1['site']."' and store='".$myrow1['store']."' and batch_no='".$detailsRow['batchno']."' group by batch_no";
 //echo $query;
  $sql = DB_query($query,$db); 
 // $i=1;
  if(DB_num_rows($sql)>0)
  {
    while($myrow=DB_fetch_array($sql))
    {
      $query1 = "select * from item_master where id ='".$row['mst_itemid']."'";
      $result = DB_query($query1,$db);
      $items_data = DB_fetch_assoc($result,$db);
      $qty=$myrow['inwardqty_primary'] - $myrow['outwardqty_primary'];
      $date_of_mfg=$myrow['date_of_mfg'];
      $date_of_expiry=$myrow['date_of_expiry'];
      //$unitname=$s->getField('unitsofmeasure','unitid',$items_data['mst_unitid'],'unitname');
     // $unitname='';
      if($qty!=0)
      {
      }
    }
  }						

  ?>
  <tr bgcolor="#FFFFFF">
  <td><input type="hidden" name="return_dtl[]" value="<?php echo $detailsRow['id']; ?>">
  	<?php echo $s->GetFieldValue('item_master',"id='".$detailsRow['itemid']."'",'StockId'); ?></td>		
  <td><?php echo $s->GetFieldValue('item_master',"id='".$detailsRow['itemid']."'",'item_name');?> 
  <input type="hidden" name="itemid[]" value="<?php echo $detailsRow['itemid'];?>" /></td>
  <!--<td ><?php //echo $unitname; ?>		
	<input type="hidden" name="mst_unitid[]"  id="mst_unitid" value="<?php echo $detailsRow['mst_unitid']; ?>" /></td>-->
   <!--<td><?php echo $s->GetFieldValue('size_master',"id='".$detailsRow['size_id']."'",'size') ?></td>	
   <td><?php echo $s->GetFieldValue('product_grade',"id='".$detailsRow['grade_id']."'",'grade') ?></td>-->
   <td><?php echo $detailsRow['batchno']; ?><?php //echo $unitname; ?>	
			<input type="hidden" name="batchno[]" id="batchno_<?php echo $i;?>" value="<?php echo $detailsRow['batchno']; ?>" /></td>
	<td><?php echo $qty; ?></td>
   <td><?php echo $detailsRow['issueqty'];?>
   <input type="hidden" name="rate[]" id="rate_<?php echo $i; ?>" value="<?php echo $detailsRow['rate']; ?>" /></td>
   <td><input type="text" name="pending_qty[]" style="width:98%;" readonly id="pending_qty_<?php echo $i; ?>" value="<?php echo ($pending_qty);//+$detailsRow['receiveqty']); ?>"/></td>
   <td width="10%"><input type="text" name="receiveqty[]" style="width:98%;" value="<?php echo $detailsRow['receiveqty'];?>" id="receiveqty_<?php echo $i; ?>" onkeyup="chkbalance(<?php echo $i; ?>)"></td>
 	<td width="1"><input  type="hidden" name="confac[]" style="width:98%;" id="confac_<?php echo $i; ?>" value="<?php echo $detailsRow['confac']; ?>"   /></td>
 	<td width="6%"><?php echo $unitname;?> </td>
	<td width="10%"><input  type="text" name="secondaryqty[]" style="width:98%;"  id="secondary_<?php echo $i; ?>" value="<?php echo $detailsRow['stock_qty2']; ?>"   /></td>     
	<td width="6%"><?php echo $unitname1;?></td>  	
  	<input type="hidden" name="matid[]" value="<?php echo $detailsRow['id']; ?>">
	</tr>
  <?php $i++;}?><input type="hidden" name="count" value="<?php echo $i;?>" /><?php } ?>
</table>
<br>
<table width="100%" border="0" cellpadding="3" cellspacing="0">
<tr class="row1">
<td width="13%" align="right"><strong>Remarks:</strong></td>
<td colspan="5"><textarea name="remarks" style="width:99%; height:60px;" rows="3" id="remark"><?php echo $remarks; ?></textarea></td>
</tr>
</table>
<p align="center"><input type="submit" name="Save" class="search" value="Save" onclick="return validate()" /></p>
</form></div></div>

<script language="javascript" type="text/javascript">
function issuedetails(str)
{
	var branch=document.getElementById("site").value;
	var godown=document.getElementById("store").value;
	
if (str.length==0)
  {
  document.getElementById("ISSUE").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("ISSUE").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","get_IssueDetails.php?q="+str+"&site="+branch+"&store="+godown,true);
xmlhttp.send();

}

function calTotal(str)
{
var k=parseFloat(document.getElementById('issueqty_'+str).value);
var j=parseFloat(document.getElementById('receiveqty_'+str).value);
if(k<j)
{
alert("Receiveqty Not Grater then Issue Qty");
document.getElementById('receiveqty_'+str).focus(); 
document.getElementById('').hide();
}	
}
function getdataitems(str,hiddiv,url)
{

var employee=document.getElementById("received_by").value;
var contractor=document.getElementById("issueto").value;

if(contractor!='0')
	{
		var element=document.getElementById("received_by");
		element.style.display = "none";
	}
	else
	{
		var element=document.getElementById("received_by");
		element.style.display = "";
	}
	if(employee!='0')
	{
		var element=document.getElementById("issueto");
		element.style.display = "none";
	}
	else
	{
		var element=document.getElementById("issueto");
		element.style.display = "";
	}
	
  val=url.indexOf("?");
   if (str=="")
  {
  document.getElementById(hiddiv).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(hiddiv).innerHTML=xmlhttp.responseText;
    }
  }
  if( val==-1)
xmlhttp.open("GET",url+"?q="+str,true);
else
xmlhttp.open("GET",url+"&q="+str,true);
xmlhttp.send();
}
function chkbalance(str)
{
	//alert(str);
	var k=parseFloat(document.getElementById('pending_qty_'+str).value);
	var j=parseFloat(document.getElementById('receiveqty_'+str).value);
	 var confac=document.getElementById("confac_"+str).value;
	
	if(k < j)
	{
	alert("Receive Qty Not Grater then Issue Qty Balance");
	document.getElementById('receiveqty_'+str).value='';
	document.getElementById("secondary_"+str).value='';
	document.getElementById('receiveqty_'+str).focus();
	}
	else
	{
	
	 var qty=parseFloat(j)*parseFloat(confac);

	 document.getElementById("secondary_"+str).value=qty.toFixed(2);	
	}

}
function showsitename159(str)
{

var xmlhttp;
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)
    {
	var data=xmlhttp.responseText.split("__");	
	
	document.getElementById("hid-Godown-div").innerHTML=data[0];
   // document.getElementById("textitem").innerHTML=data[1];
	
    }
  }
  xmlhttp.open("GET","GoDownIssueSlip1.php?site="+str,true);
	xmlhttp.send();

//xmlhttp.open("GET","getSort.php?s="+str+"&cat="+cat,true);

	
}

function validate()
{
if(document.getElementById("site").value=='0')
{
alert("Must Select Branch Name");
return false;	
}
if(document.getElementById("issueto").value=='0')
{
var count=0;	
}
if(document.getElementById("received_by").value=='0')
{
var count=0;	
}
if(document.getElementById("issueto").value!='0' || document.getElementById("received_by").value!='0' )
{
var count=1;	
}
if(count==0)
{
alert("Must Select Contractor Name /Employee Name");
return false;	
}
if(document.getElementById("issue_slipno").value=='')
{
alert("Must Select Issue Slip No");
return false;		
}
	
var rowCount=document.getElementById("count").value;
for(var i=1;i<=rowCount;i++)
{
if(isNaN(document.getElementById("receiveqty_"+i).value))
{
alert("Sting Not Allowed");
document.getElementById("receiveqty_"+i).value='';
document.getElementById("receiveqty_"+i).focus();
return false;	
}
var countdata;	
if(document.getElementById("receiveqty_"+i).value=='')
{
countdata=0;	
}
else
{
countdata=1;	
}
if(countdata==0)
{
alert("Must Enter Atleast One Return Qty");
return false;	
}
var issuqty=parseFloat(document.getElementById("pending_qty_"+i).value);
var receiveqty;
if(document.getElementById("receiveqty_"+i).value=='')
{
receiveqty=0;	
}
else
{
 receiveqty=parseFloat(document.getElementById("receiveqty_"+i).value);
}
if(receiveqty>issuqty)
{
alert("Received Qty Not Greater Then Issue Qty");
document.getElementById("receiveqty_"+i).value='';
document.getElementById("receiveqty_"+i).focus();
return false;	
}	
}
if(document.getElementById("returndate").value=='')
{
alert("Must Select Return Date");
return false;	
}	
return true;	
	
}

</script>
