<?php
ob_start();
$PageSecurity = 5;
include('includes/SQL_CommonFunctions.inc');
$title = _('Purchase Order Register');
$PageName ='Purchase Order Register';	



                    //**************************   Calculating Stock Balance *******************************//
		

						
                        function openingBalance($function_filter,$item)
							     {							
								global $db;
								$site=$function_filter[0];
								$store=$function_filter[1];								
								$from=$function_filter[2];																
								if($site!='')
								$filter[]="site = '".$site."'";
								if($store!='')
								$filter[]="store = '".$store."'  ";								
								if($from!='--' && $to!='--')
								$filter[]="reveive_date <= '".$from."'";
								if($item!='')
								$filter[]="itemcode = '".$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'];
							}

                        function receivedMRN($function_filter,$item)
						  {
							global $db;
							$site=$function_filter[0];
							$store=$function_filter[1];							
							if($site!='')
							$filter[]="addmrn.site = '".$site."'";
							if($store!='')
							$filter[]="addmrn.StoreCode = '".$store."'";
							if($item!='')
							$filter[]="addmrnqty.mst_itemid = '".$item."'";							
							$filter=implode(' and ',$filter);
							     $sql1="Select SUM(addmrnqty.reciveqty) from addmrn left join addmrnqty 
							       on(addmrn.id=addmrnqty.issue_id) where Cancel_Status='N'and  $filter";
							$result1=DB_query($sql1,$db);
							$myrow1=DB_fetch_array($result1);  
							return $myrow1['SUM(addmrnqty.reciveqty)'];
						}
						
				function receivedReturn($function_filter,$item)
			    {
				global $db;
				$site=$function_filter[0];
				$store=$function_filter[1];
				$from=$function_filter[2];
				$to=$function_filter[3];
				
				if($site!='')
				$filter[]="material_return.site = '".$site."'";
				if($store!='')
				$filter[]="material_return.store = '".$store."'";
				if($from!='--' && $to!='--')
				$filter[]="material_return.returndate <= '".$from."'";
				if($item!='')
				$filter[]="material_return_details.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 issueSlip($function_filter,$item)
							   {
								global $db;
								$site=$function_filter[0];
								$store=$function_filter[1];
								
								if($site!='')
								$filter[]="addissue.site = '".$site."'";
								if($store!='')
								$filter[]="addissue.mst_storeid = '".$store."'";
								if($item!='')
								$filter[]="issueqty.mst_itemid = '".$item."'";
								
								$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);
								
								//echo $myrow1['SUM(issueqty.issueqty)'];
								
								return $myrow1['SUM(issueqty.issueqty)'];
							}		



			function receivedSiteToSite($function_filter,$item)
			{
				global $db;
				$site=$function_filter[0];
				$store=$function_filter[1];
				$from=$function_filter[2];
				$to=$function_filter[3];
				
				if($site!='')
				$filter[]="transfer_receipt.Received_to = '".$site."'";
				if($store!='')
				$filter[]="transfer_receipt.Received_store = '".$store."'";
				if($from!='--' && $to!='--')
				$filter[]="transfer_receipt.MRNDate <= '".$from."' ";
				if($item!='')
				$filter[]="transfer_receipt_details.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)'];
			}

					function issueSiteToSite($function_filter,$item)
					{
						global $db;
						$site=$function_filter[0];
						$store=$function_filter[1];
						$from=$function_filter[2];
						$to=$function_filter[3];
						
						if($site!='')
						$filter[]="transfer_issue.sitecode = '".$site."'";
						if($store!='')
						$filter[]="transfer_issue.fromstore = '".$store."'";
						if($from!='--' && $to!='--')
						$filter[]="transfer_issue.issuedate <= '".$from."' ";
						if($item!='')
						$filter[]="transfer_issue_details.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;
						
					}

        function issueMatarialReturn($function_filter,$item)
        {
	global $db;
	$site=$function_filter[0];
	$store=$function_filter[1];
	$from=$function_filter[2];
	$to=$function_filter[3];
	
	if($site!='')
	$filter[]="inv_material_return.sitecode = '".$site."'";
	if($store!='')
	$filter[]="inv_material_return.storecode = '".$store."'";
	if($from!='--' && $to!='--')
	$filter[]="inv_material_return.Reqdate <= '".$from."' ";
	if($item!='')
	$filter[]="inv_material_return_details.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)'];
   }				
						
/*function return_rejection($function_filter,$item)
{
	global $db;
	$site=$function_filter[0];
	$store=$function_filter[1];
	$from=$function_filter[2];
	$to=$function_filter[3];
	
	if($site!='')
	$filter[]="rejection_tbl.issue_branch = '".$site."'";
	if($store!='')
	$filter[]="rejection_tbl.issue_stroe = '".$store."'";
	if($from!='--' && $to!='--')
	$filter[]="rejection_tbl.date between '".$from."' and '".$to."'";
	if($item!='')
	$filter[]="rejection_tbl_details.itemid = '".$item."'";
	
	$filter=implode(' and ',$filter);
	
	  $sql1="Select SUM(rejection_tbl_details.returnqty) from rejection_tbl left join rejection_tbl_details on(rejection_tbl.id=rejection_tbl_details.parentId) where $filter";
	$result1=DB_query($sql1,$db);
	$myrow1=DB_fetch_array($result1);
	return $myrow1['SUM(rejection_tbl_details.returnqty)'];
}*/
	
		
function Rgpchallan($function_filter,$item)
					  {
					  
					      global $db;
							$site=$function_filter[0];
							$store=$function_filter[1];
							$from=$function_filter[2];
							$to=$function_filter[2];
							
							if($site!='')
							$filter[]="rgp_tab.branch = '".$site."'";
							if($store!='')
							$filter[]="rgp_tab.store = '".$store."'";
							if($from!='--' && $to!='--')
							$filter[]="rgp_tab.date between '".$from."' and '".$to."'";
							if($item!='')
							$filter[]="rgp_tab_details.mst_itemid = '".$item."'";
							
							$filter=implode(' and ',$filter);
							
							  $sql1="Select SUM(rgp_tab_details.qty) 
							  from rgp_tab left join rgp_tab_details 
							  on(rgp_tab.id=rgp_tab_details.parent_id) where $filter";
							$result1=DB_query($sql1,$db);
							$myrow1=DB_fetch_array($result1);
							return $myrow1['SUM(rgp_tab_details.qty)'];
					  
					  
					  		
					  }	
					   function Rgpreturn($function_filter,$item)
					    {
					  
					        global $db;
							$site=$function_filter[0];
							$store=$function_filter[1];
							$from=$function_filter[2];
							$to=$function_filter[2];
							
							if($site!='')
							$filter[]="rgp_return.branch = '".$site."'";
							if($store!='')
							$filter[]="rgp_return.store = '".$store."'";
							if($from!='--' && $to!='--')
							$filter[]="rgp_return.return_date between '".$from."' and '".$to."'";
							if($item!='')
							$filter[]="rgp_return_details.item_id = '".$item."'";
							
							$filter=implode(' and ',$filter);
							
							  $sql1="Select SUM(rgp_return_details.qty) 
							  from rgp_return left join rgp_return_details 
							  on(rgp_return.id=rgp_return_details.parent_id) where $filter";
							$result1=DB_query($sql1,$db);
							$myrow1=DB_fetch_array($result1);
							return $myrow1['SUM(rgp_return_details.qty)'];
					  
					  
					  		
					  }	
					  
					  function Nrgp($function_filter,$item)
					    {					  
					        global $db;
							$site=$function_filter[0];
							$store=$function_filter[1];
							$from=$function_filter[2];
							$to=$function_filter[2];
							
							if($site!='')
							$filter[]="nrgp_challan.branch = '".$site."'";
							if($store!='')
							$filter[]="nrgp_challan.store = '".$store."'";
							if($from!='--' && $to!='--')
							$filter[]="nrgp_challan.date between '".$from."' and '".$to."'";
							if($item!='')
							$filter[]="nrgp_challan_details.item_code = '".$item."'";
							
							$filter=implode(' and ',$filter);
							
							  $sql1="Select SUM(nrgp_challan_details.qty) 
							  from nrgp_challan left join nrgp_challan_details 
							  on(nrgp_challan.id=nrgp_challan_details.parant_id) where $filter";
							$result1=DB_query($sql1,$db);
							$myrow1=DB_fetch_array($result1);
							return $myrow1['SUM(nrgp_challan_details.qty)'];
					  
					  
					  		
					  }		





















											if($_REQUEST['cancel'])
											{
												unset($_SESSION['materialReturn']);
												
												unset($_SESSION['site']);
												
												unset($_SESSION['requisition_no']);
												
												unset($_SESSION['returnDate']);
												
												unset($_SESSION['vendor']);
												
												unset($_SESSION['returnAgainst']);
												unset($_SESSION['requisition_no']);
												unset($_SESSION['itemcode']);
												unset($_SESSION['store']);
											}
											
									if($_REQUEST['item_popup'])
									{
									
										$_SESSION['returnDate']=$_REQUEST['returnDate'];
										$_SESSION['site']=$_REQUEST['site'];
										$_SESSION['store']=$_REQUEST['storecode'];
										$_SESSION['returnAgainst']=$_REQUEST['returnAgainst'];
										$_SESSION['vendor']=$_REQUEST['vendor'];
										$_SESSION['requisition_no']=$_REQUEST['requisition_no'];
										
									    
										
										
									}

                 //*******************************************************************************************************************//
	  
	   function get($site,$store,$date1,$item,$closqty,$closerate,$closevalue)
					{
					global $db;
					  $check_current_opening="Select * from stock_summary where date='".$date1."'
					 and site='".$site."' and store='".$store."'
					  and item='".$item."'";
					
					$check_current_op_result=DB_query($check_current_opening,$db);
					if(DB_num_rows($check_current_op_result)=='0')
					{
					$closing_qty=$closqty;		
					$closing_value=$closevalue;
					$closing_rate=$closerate;	
					}
					else
					{
						$check_current_op_row=DB_fetch_array($check_current_op_result);
						$id=$check_current_op_row['id'];
						$opening_qty=$closqty;
						$opening_value=$closevalue;    
						$opening_rate=round($closing_value/$closing_qty);
						$closing_qty=$opening_qty+$check_current_op_row['inwards_qty']-$check_current_op_row['outwards_qty'];
					$closing_value=$opening_value+$check_current_op_row['inwards_value']-$check_current_op_row['outwards_value'];
						$closing_rate= round($closing_value/$closing_qty);
					
						$update_summary="Update  stock_summary set 
													opening_qty='".$opening_qty."',    
													opening_rate='".round($opening_rate,2)."',    
													opening_value='".$opening_value."', 								   
													closing_qty='".$closing_qty."',    
													closing_rate='".$closing_rate."',    
													closing_value='".$closing_value."' where id=$id ";
						$result2=DB_query($update_summary,$db);
						
						
					}

                               $date2= strtotime(date("Y-m-d", strtotime($date1)) . " +1 day");
                                $date11= date("Y-m-d",$date2);
							 
							    if($date11<=date('Y-m-d'))
							   {
 										get($site,$store,$date11,$item,$closing_qty,$closing_rate,$closing_value);
								}		
								}	
	  
	  

      //*******************************************************************************************************************//


if($_REQUEST['Save']!='')
{

$year=$_SESSION['financialYearStart'];
$year_after=$_SESSION['financialYearEnd'];
$site123=$_REQUEST['site'];
$site_code=substr($site123,0,3);
//echo "Select * from prefix_tbl where prefix_name='".$PageName."'";
//$prefix_sql=DB_query("Select * from prefix_tbl where prefix_name='".$PageName."'",$db);
//$prefix_row=DB_fetch_array($prefix_sql);

$prefix="REJ";
$sql="Select Reqno from inv_material_return where sitecode='".$_REQUEST['site']."' order by Reqno desc limit 1";
$result=DB_query($sql,$db);
$myrow=DB_fetch_array($result);
if(DB_num_rows($result)>0)
{
	$Reqno=$myrow['Reqno'];
	$req_part1=substr($Reqno,-6);
	///echo $req_part1;
	$req_final=$req_part1+1;
	//echo "<br>".$req_final;
}
else
{
	$req_final="1";
}
$string=$site_code."/".$prefix."/".$year.$year_after."/";
$final_string=$string.str_pad($req_final,6,"0",STR_PAD_LEFT);

	 $requisition_sql="Insert into inv_material_return set
									
									MRNno='".$_REQUEST['mrn']."',
									sitecode='".$_REQUEST['site']."',
									storecode='".$_REQUEST['storecode']."',
									Reqdate='".FormatDateForSQL($_REQUEST['returnDate'])."',
									vendor_code='".$_REQUEST['vendor']."',
									returnagainst='".$_REQUEST['returnAgainst']."',
									MRNDate='".FormatDateForSQL($_REQUEST['mrnDate'])."',
									PONo='".$_REQUEST['poNo']."',
									status='',
									PODate='".FormatDateForSQL($_REQUEST['poDate'])."',
									Reqno='".$final_string."',
									CompanyId='".$_SESSION['ACGCompanyId']."'";
							

	$requisition_res=DB_query($requisition_sql,$db);
	$last_id=DB_Last_Insert_ID($db,'inv_material_return','id');
	
	
	if($last_id!='')
	{
	
		for($cr=0;$cr <$_REQUEST['ctr'];$cr++)
		{
			
			  	
			    $material_details_sql="insert into inv_material_return_details set
											 parentId='".$last_id."',
											 itemid='".$_REQUEST['itemid'][$cr]."',
										     POQty='".$_REQUEST['POQty'][$cr]."',    
											 QtyAccepted='".$_REQUEST['QtyAccepted'][$cr]."',   
											 QtyAsPerBill='".$_REQUEST['QtyAsPerBill'][$cr]."',
											 ItemPrice='".$_REQUEST['Rate'][$cr]."',
											 TotalValue='".$_REQUEST['TotalValue'][$cr]."',                 
											 ReturnQty = '".$_REQUEST['ReturnQty'][$cr]."', 
											Remarks='".$_REQUEST['Remarks'][$cr]."'	"; 
			$material_details_sql;
			
			$details_res=DB_query($material_details_sql,$db);
			
	//****************************************** Stock Summary ************************************************************//	
					
					
					 $data_date1=explode('/',$_REQUEST['returnDate']);
					     $date51=$data_date1[2].'-'.$data_date1[1].'-'.$data_date1[0];
					      $date21= strtotime(date("Y-m-d", strtotime($date51)) . " +1 day");
                            $date= date("Y-m-d",$date21);

             		
					  	 
						
					  $check_current_opening="Select * from stock_summary where date='".$date."'
					 and site='".$_REQUEST['site']."' and store='".$_REQUEST['storecode']."'
					  and item='".$_REQUEST['itemid'][$cr]."'";
					
					$check_current_op_result=DB_query($check_current_opening,$db);
					//echo DB_num_rows($check_current_op_result);
					
					if(DB_num_rows($check_current_op_result)=='0')
					{
					 	$get_previous_closing="Select * from stock_summary where site='".$_REQUEST['site']."'
						 and store='".$_REQUEST['storecode']."' and item='".$_REQUEST['itemid'][$cr]."' 
						 and date<'".$date."' ORDER BY DATE DESC LIMIT 0,1";
						
						$previous_closing_result=DB_query($get_previous_closing,$db);
						$previous_closing_row=DB_fetch_array($previous_closing_result);
						
						
						if(DB_num_rows($previous_closing_result)=='0')
							{
							       $check_opening_entry="Select * from opening_stockitemwise 
													     where site='".$_REQUEST['site']."' 
													     and store='".$_REQUEST['storecode']."' 
													     and itemcode='".$_REQUEST['itemid'][$cr]."'
													     and reveive_date<'".$date."'  ";
								$check_opening_entry_result=DB_query($check_opening_entry,$db);
								$check_opening_entry_row=DB_fetch_array($check_opening_entry_result);
								if(DB_num_rows($check_opening_entry_result)>0){
								$opening_qty=$check_opening_entry_row['stock'];
								$opening_rate=$check_opening_entry_row['rate'];
								$opening_value=$check_opening_entry_row['amount'];}else
								{$opening_qty='';
								$opening_rate='';
								$opening_value='';}
						     }
							else
									{
										$opening_qty=$previous_closing_row['closing_qty'];
										$opening_rate=$previous_closing_row['closing_rate'];
										$opening_value=$previous_closing_row['closing_value'];
									}
									
							$outwards_qty=$_REQUEST['ReturnQty'][$cr]; 
							$outwards_value=$_REQUEST['TotalValue'][$cr];
							$outwards_rate=$outwards_value/$outwards_qty;
							
							$closing_qty=$opening_qty-$outwards_qty;
							$closing_value=$opening_value-$outwards_value;
							$closing_rate=round($closing_value/$closing_qty);
							$insert_first_summary="Insert into stock_summary set 
													site='".$_REQUEST['site']."',     
													store='".$_REQUEST['storecode']."',    
													item='".$_REQUEST['itemid'][$cr]."',
													opening_qty='".$opening_qty."',  
													opening_rate='".$opening_rate."',    
													opening_value='".$opening_value."',    
													outwards_qty='".$outwards_qty."',    
													outwards_rate='".round($outwards_rate,2)."',    
													outwards_value='".$outwards_value."',    
													closing_qty='".$closing_qty."',    
													closing_rate='".$closing_rate."',    
													closing_value='".$closing_value."',    
													date='".$date."' 	";
							$result1=DB_query($insert_first_summary,$db);
						
					}
					else
					{
					$check_current_op_row=DB_fetch_array($check_current_op_result);
					$id=$check_current_op_row['id'];
					$outwards_qty=$check_current_op_row['outwards_qty']+$_REQUEST['ReturnQty'][$cr]; 
					$outwards_value=$check_current_op_row['outwards_value']+$_REQUEST['TotalValue'][$cr]; 
					$outwards_rate=$outwards_value/ $outwards_qty;
					$closing_qty=$check_current_op_row['opening_qty']+$check_current_op_row['inwards_qty']-$outwards_qty;
					$closing_value=$check_current_op_row['opening_value']+$check_current_op_row['inwards_value']-$outwards_value;
					$closing_rate= round($closing_value/$closing_qty);
						
										$update_summary="Update  stock_summary set 
													     outwards_qty='".$outwards_qty."',    
													     outwards_rate='".round($outwards_rate,2)."',    
													     outwards_value='".$outwards_value."',    
													     closing_qty='".$closing_qty."',    
													     closing_rate='".$closing_rate."',    
													     closing_value='".$closing_value."' where id=$id ";
														 
						                 $result2=DB_query($update_summary,$db);
						
						
					}
					
 //******************************************************************************************************************************//	
	                
					
					 
					
					 $data_date=explode('/',$_REQUEST['returnDate']);
					     $date55=$data_date[2].'-'.$data_date[1].'-'.$data_date[0];
					      $date22= strtotime(date("Y-m-d", strtotime($date55)) . " +1 day");
                            $date1= date("Y-m-d",$date22);
					
					
					
				   if($date1<=date('Y-m-d'))
					{
 	get($_REQUEST['site'],$_REQUEST['storecode'],$date1,$_REQUEST['itemid'][$cr],$closing_qty,$closing_rate,$closing_value);
					}	 
			if($_REQUEST['returnAgainst']=='MRN')
			{		  
		 if($_REQUEST['stock'][$i]==$_REQUEST['ReturnQty'][$i])
		  {
		  //echo "update addmrnqty set MRVS=1 where mst_itemid='".$_REQUEST['itemid'][$cr]."' and issue_id='".$_REQUEST['mrn']."'",
		  $update=DB_query("update addmrnqty set MRVS=1 where mst_itemid='".$_REQUEST['itemid'][$cr]."'
		   and issue_id='".$_REQUEST['mrn']."' ",$db);
		    
		  }	
		  }	
		}
		
		}
		
		$col=0;
		$check=DB_query("select * from addmrnqty where issue_id='".$_REQUEST['mrn']."'",$db);
		$numrow1=DB_num_rows($check);
		while($row1=DB_fetch_array($check))
		{
		if($row1['MRVS']==1)
		{ $col=$col+1; }}
		if($col==$numrow1)
		{ $update1=DB_query("update addmrn set MRVS_status=1 where id='".$_REQUEST['mrn']."'",$db); }
		
				
					
					
			
	

	$_SESSION['success_msg']="Saved Successfully";
echo "<script>location.href='index.php?route=Inventory/transation/Material_Return_To_Vendor_index&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";
	
unset($_SESSION['materialReturn']);
unset($_SESSION['date']);
unset($_SESSION['site']);
unset($_SESSION['requisition_no']);
unset($_SESSION['returnDate']);
//unset($_SESSION['remarks']);
unset($_SESSION['vendor']);
unset($_SESSION['returnAgainst']);
unset($_SESSION['store']);
}


?>
<script type="text/javascript" src="js/function-ajax.js">
</script>
<script language="javascript" type="text/javascript">
function PurchaseOrderNumber_1(str)
{
if (str.length==0)
  {
  document.getElementById("returnAgainst").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("returnAgainst").innerHTML=xmlhttp.responseText;
    
    }
  }
xmlhttp.open("GET","Material_Return_To_Vendor_add.php?returnAgainst="+str,true);
xmlhttp.send();
}
function generate_reqno(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("rowdata").innerHTML=data[1];
	document.getElementById("reqno").innerHTML=data[0];
	//document.getElementById("venderdata").innerHTML=data[2];

	
    }
  }
  xmlhttp.open("GET","get_reqno1.php?site="+str,true);
xmlhttp.send();

//x
}
function cal_short_qty(i)
{
	var k=document.getElementById("Rate_"+i).value;
	var k1=document.getElementById("ReturnQty_"+i).value;
	if(k==''){k=0;}
	if(k1==''){k1=0;}
	var shortqty=parseFloat(k)*parseFloat(k1);
	document.getElementById("TotalValue_"+i).value=shortqty;
	
	
	
	
}
function validate_returnqty(str)
{
var stock=parseFloat(document.getElementById("stock_"+str).value);
var return12=parseFloat(document.getElementById("ReturnQty_"+str).value);
if(isNaN(document.getElementById("ReturnQty_"+str).value))
{
alert("String Not Allowed");
document.getElementById("ReturnQty_"+str).value='';
document.getElementById("ReturnQty_"+str).focus;
return false;	
}
if(return12>stock)
{
alert("Return Qty cannot be greater than stock");
document.getElementById("ReturnQty_"+str).value='';
document.getElementById("ReturnQty_"+str).focus;
return false;
}
return true;
}

function validate_returnqty1()
{
if(document.getElementById("site").value=='0')
{
alert("Must Select Branch Name");
document.getElementById("site").focus();
return false;	
}
if(document.getElementById("returnAgainst").value=='000')
{
alert("Must Select Return Aganist");
document.getElementById("returnAgainst").focus();
return false;	
}
if(document.getElementById("returnDate").value=='')
{
alert("Must select Date first.");
document.getElementById("returnDate").focus();
return false;	
}
var rowCount=document.getElementById("ctr").value;
//alert(rowCount);
var flag;
var data;
var stock;
for(var i=0; i<rowCount;i++)
{

if(document.getElementById("ReturnQty_"+i).value=='')
{
flag=0;	
}
else
{
flag=1;
data=i;
break;	
}

}
if(flag==0)
{
alert("Must Enter Return Qty");
return false;	
}
else
{
stock=parseFloat(document.getElementById("stockqty_"+data).value);	
var retrunqty=parseFloat(document.getElementById("ReturnQty_"+data).value);
if(isNaN(document.getElementById("ReturnQty_"+data).value))
{
alert("String Not Allowed");
document.getElementById("ReturnQty_"+data).value='';
document.getElementById("ReturnQty_"+data).focus();
return false;	
}
if(retrunqty>stock)
{
alert("Return Qty Cannot greater Then Stock Qty");
document.getElementById("ReturnQty_"+data).focus();
return false;	
}
}

return true;

}

</script>
<h2 align="center"><strong>Material Return to Vendor</strong></h2>
<form action="" method="post">
	

<table width="100%" border="1" cellspacing="0" cellpadding="3" style="border-collapse:collapse;">
  <tr>
    <th style="width:150px;"><strong>Branch</strong></th>
    <td>
	<?php
	if($_SESSION['AssignedBranch']!='')
	  {	  	
  $ss1="Select loccode, locationname from locations  where CompanyId='".$_SESSION['ACGCompanyId']."' and loccode in('".$_SESSION['AssignedBranch']."')";
	  	 $site_sql1=DB_query($ss1,$db);
	  }
	  else
	  {
		$ss1="Select loccode,locationname from locations where CompanyId='".$_SESSION['ACGCompanyId']."'";
		$site_sql1=DB_query($ss1,$db);
	  }
	?>
	
	<select name="site" id="site" onchange="generate_reqno(this.value)"  style="width:100%;">
	
        <option value="0">Select</option>
        <?php   
	 
	  while($site_row=DB_fetch_array($site_sql1)) 
	  {
	  	$s='';
		if($_SESSION['site']==$site_row['loccode'])
		$s="selected";
	  ?>
        <option value="<?php echo $site_row['loccode'];?>" <?php echo $s;?>><?php echo $site_row['locationname'];?></option>
        <?php } ?>
      </select>
    </td>
	 <th style="width:150px;"><strong>Store</strong></th>
		<td><div id="rowdata">
		<?php
		$sql_store = "select id, StoreCode, StoreName from storetype order by StoreCode ASC";
		$resultStkLocs = DB_query($sql_store,$db);
		?>
		<select name="storecode" style="width:100%" id="storecode">
		<option value="000">Select</option> 
		<?php 
		while ($myrow=DB_fetch_array($resultStkLocs))
		{
				$p='';
				if($myrow['id']==$_SESSION['store'])
				$p="selected";
		?>
			<option Value="<?php echo $myrow['id']; ?>" <?php echo $p; ?>><?php echo $myrow['StoreName']; ?></option>
		<?php }
		?>
		</select></div>	</td>
		
		</tr>
		
		<tr>
      
    <th nowrap="nowrap"><strong>Requisition No</strong></th>
  	
  	<td><input name="requisition_no" type="text" id="requisition_no" value="<?php echo 'Auto Generated' ?>" style="width: 100%" readonly="true" /></td>
 <th width="10%%"><strong>Date</strong></th>
  	 <td> <input name="returnDate"  id="returnDate" type="text" size="12" class="datepicker" value="<?php if(isset($_SESSION['returnDate'])) echo $_SESSION['returnDate'];?>" style="width: 100%"/></td>
  	</tr>    
	<tr>
  	<th><strong>Return Against</strong></th>
    <td>
	<select style="width:100%" name="returnAgainst"  id="returnAgainst" onchange="DeActivate(this.value)">
	<option value="000">Select</option>
	
	<option value="MRN" <?php if($_SESSION['returnAgainst']=='MRN') { echo "Selected";  }?>>MRN</option>
	<option value="Without MRN" <?php if($_SESSION['returnAgainst']=='Without MRN') { echo "Selected";  }?>>Without  MRN</option>
	
    </select></td>
      <th><strong>Vendor</strong></th>
    <td>
    	<?php 
    if($_SESSION['returnAgainst']=='Without MRN')
	{
		$disabled1="disabled";
	}
    ?>  
    
      <select name="vendor" id="vendor"  onchange="ShowDiv(this.value,'hidmrndiv','getMrnNo.php?receipt='+document.getElementById('site').value+'&store='+document.getElementById('storecode').value)" <?php echo $disabled1; ?>  style="width:100%;">
	   <option value="0">Select</option>
	  <?php 
	  $v_sql=DB_query("Select id,vendor_code,vendor_name from suppliers",$db);
	  while($v_row=DB_fetch_array($v_sql)) 
	  {
	  	$s='';
		if($_SESSION['vendor']==$v_row['vendor_code'])
		$s="selected";
	  ?>
	  <option value="<?php echo $v_row['id'];?>" <?php echo $s;?>><?php  echo str_replace(array("M/s ","M/S"),'',$v_row['vendor_name']);?></option>
	  <?php } ?>
      </select>    </td>
  
	</tr>
	
	<tr>

    
 <th><strong>MRN</strong></th>
    <td>
    <?php 
    if($_SESSION['returnAgainst']=='Without MRN')
	{
		$disabled="disabled";
	}
    ?>
   <div id='hidmrndiv'> 
	<select name="mrn" id="mrn"  style="width:100%" onchange="ShowDiv(this.value,'divmrnDate','getMrnDate.php')" <?php echo $disabled;?>>
	   <option value="0">Select</option>
	  <?php
	  while($credit_row=DB_fetch_array($result)) {
	  ?>
	  <option value="<?php echo $credit_row['id'];?>"><?php echo $credit_row['MRNNo'];?></option>
	  <?php } ?>
      </select> 
      </div>
      </td>
	  
	  <td colspan="2"></td>
  </tr>
 </table>
 
  <div id="divmrnDate">
  <table name="tablemrn" width="100%" border="1" cellspacing="0" cellpadding="3" style="border-collapse:collapse;">
 <tr>
 <th style="width:150px;"><strong>MRN Date</strong></th>
 <td style="width:248px;"><input name="mrnDate" id="mrnDate" type="text" style="width: 100%"  value="<?php if(isset($mrn_row['MRNDate']))echo ConvertSQLDate($mrn_row['MRNDate']);?>" <?php echo $disabled;?>/></td>
 <th style="width:150px;"><strong>PO No</strong></th>
 <td><input name="poNo" id="poNo" type="text" style="width:100%"  value="<?php echo $poRow['PO_Orderno'];?>" <?php echo $disabled;?>/></td>
  </tr>
 
 <tr>
 <th><strong>PO Date</strong></th>
 <td><input name="poDate" id="poDate" type="text" style="width: 100%"  value="<?php if(isset($mrn_row['OrderDate']))echo ConvertSQLDate($mrn_row['OrderDate']);?>" <?php echo $disabled;?>/>
 </td>
 <td colspan="2"></td>
 </tr>
 </table>
  	
  
   <p align="left"><input type="submit"  name="item_popup" value="Add Items" id="item_popup"  onclick="open_items();"/></p>
   <p align="right" style="display:none;"><a href="exportdata.php?modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>">Export</a></p>

	<?php //echo $_SESSION['itemcode'];
	$itemlist=array();
 $itemlist1=explode('#',$_SESSION['itemcode']);
	
	
	
	?>

      <table width="100%" border="1" cellspacing="0" cellpadding="3" style="border-collapse:collapse">
        <tr>
          <th>Item Code</th>
          <th>Item Name</th>
           <th>UOM</th>
		   <th>Stock Bal</th>
            <th>Rate</th>
          <th>Return Qty</th>
          <th>Total Value</th>
          <th>Remarks</th>
        </tr>
        <?php
  if(isset($_SESSION['materialReturn']))
   {
                                        $function_filter[]=$_SESSION['site'];
										 $function_filter[]=$_SESSION['storecode'];
										 $data_date=explode('/',$_SESSION['returnDate']);
					                      $date55=$data_date[2].'-'.$data_date[1].'-'.$data_date[0];
					                      $date22= strtotime(date("Y-m-d", strtotime($date55)) . " +0 day");
                                           $date1= date("Y-m-d",$date22);
									       $function_filter[]=$date1; 
   $itemlist=array(); 
   $itemlist=explode('#',$_SESSION['materialReturn']);
    for($i=0;$i<count($itemlist);$i++)
	{
		if($i%2==0)
		{$bg="#CCCCCC";}
		else
		$bg="#C8BECB";
	
  $itemquery=DB_query("select * from item_master where id='".$itemlist[$i]."'" , $db);
  $item_row=DB_fetch_array($itemquery);
  $stockSQL=DB_query("select * from stock_maintenance where itemcode='".$item_row['id']."'",$db) ;
  $stockRow=DB_fetch_array( $stockSQL);		
  ?>
<tr bgcolor="<?php echo $bg;?>">
<td><?php echo $item_row['StockID'];?>
<input type="text" name="itemid[]" id="itemid_<?php echo $i; ?>" value="<?php echo $itemlist[$i]; ?>" /> </td>
          <td><?php echo $item_row['item_name']; ?> </td>
<td><?php $unitsql="select unitname from unitsofmeasure where unitid='".$item_row['unit']."'";
$unitresult=DB_query($unitsql,$db);
$unitname=DB_fetch_array( $unitresult);
echo $unitname['unitname']; ?> </td>
<td><?php 
         
		  
		    $op=openingBalance($function_filter,$item_row['id']);
                ///echo "openingBalance"."<br>";
 		     $in_1=receivedMRN($function_filter,$item_row['id']);
          //echo "receivedMRN"."<br>";
 		   $out_1=issueSlip($function_filter,$item_row['id']);
             //echo "issueSlip"."<br>";
		  $out_2=issueSiteToSite($function_filter,$item_row['id']);		
            //echo "issuesitetosite"."<br>";
		  $in_2=receivedSiteToSite($function_filter,$item_row['id']);
		 //echo " receivesitetosite"."<br>";
		  $out_3=issueMatarialReturn($function_filter,$item_row['id']);
		 
		  $in_3=receivedReturn($function_filter,$item_row['id']);		 
		  //$in_4=return_rejection($function_filter,$myrow['itemid']);
		   
		 
		
		 
		   $out_4=Rgpchallan($function_filter,$item_row['id']);
		   $out_5=Nrgp($function_filter,$myrow2['id']);
		
		  //$in_4=return_rejection($function_filter,$myrow['id']);
		  $in_4=Rgpreturn($function_filter,$item_row['id']);
		   $invalue=($op+$in_1+$in_2+$in_3+$in_4);
		   $outvalue=($out_1+$out_2+$out_3+$out_4+$out_5);
		  $tot=$invalue-$outvalue;
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		  
		 //$total_current=$op ;	
		 
		 echo $stockRow=$tot;	
		 ?>
		  <input name="stock[<?php echo $i;?>]" id="stock_<?php echo $i;?>"  value="<?php echo $stockRow; ?>" type="hidden" />	

</td>
<td align="center"><input name="Rate[<?php echo $i;?>]" type="text" id="Rate_<?php echo $i;?>" size="20" /></td>
<td align="center"><input name="ReturnQty[<?php echo $i;?>]" type="text" id="ReturnQty_<?php echo $i;?>" size="20"   onchange="calamount(<?php echo $i;?>)" /></td>
 <td align="center"><input name="TotalValue[<?php echo $i;?>]" type="text" id="TotalValue_<?php echo $i;?>" size="20" onfocus="cal_short_qty(<?php echo $i;?>);" /></td>
 <td align="center"><input name="Remarks[<?php echo $i;?>]" type="text" id="Remarks_<?php echo $i;?>" size="10" onfocus="checkdata(<?php echo $i; ?>)" /></td>
        </tr>
        <?php }  } ?>
        <input type="hidden" name="ctr" id="ctr" value="<?php echo $i;?>" />
      </table>

  </div>
  <p align="center"><input type="submit" name="Save" value="Save" onclick="return validate_returnqty1();" ><input type="submit" name="cancel" value="Reset">
<a href="index.php?route=Inventory/transation/Material_Return_To_Vendor_index&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>&NewReturn=yes"><input type="button" value="Cancel" name="Back" /></a>
</p>
</form>





<script type="text/javascript" language="JavaScript">
function open_items()
{
	window.open("ItemsMaterial.php?action=add&modid=<?php echo $_REQUEST['modid'];?>&frmid=<?php echo $_REQUEST['frmid'];?>","item_popup_window","height=500,width=500,toolbar=no,menubar=no,dependent=yes,resizable =yes, scrollbars=yes");
}
function DeActivate(str)	
{
	if(str=='Without MRN')
	{
		document.getElementById("mrn").disabled=true;
		document.getElementById("vendor").disabled=true;		
		document.getElementById("mrnDate").disabled=true;
		document.getElementById("poDate").disabled=true;
		document.getElementById("poNo").disabled=true;
		document.getElementById("item_popup").disabled=false;
		document.getElementById("tableId").style.display='block';		
	}
	
	if(str=='MRN')
	{
		document.getElementById("mrn").disabled=false;
		document.getElementById("mrnDate").disabled=false;
		document.getElementById("vendor").disabled=false;
		document.getElementById("poDate").disabled=false;
		document.getElementById("poNo").disabled=false;
		document.getElementById("item_popup").disabled=true;
		document.getElementById("tableId").style.display='none';
		
	}	
}

function calamount(i)
{

var k=parseFloat(document.getElementById("ReturnQty_"+i).value);
var j=parseFloat(document.getElementById("stock_"+i).value);

if(k=='')
{
alert("Must Enter Return Qty");
document.getElementById("ReturnQty_"+i).value='';
document.getElementById("ReturnQty_"+i).focus;
return false;
}
if(k>j)
{
alert("Return Qty Can Not Greater Then Stock Qty");
document.getElementById("ReturnQty_"+i).value='';
document.getElementById("ReturnQty_"+i).focus;
return false;		
}
return true;	
}

function checkdata(i)
{
if(document.getElementById("ReturnQty_"+i).value=='')
{
alert("Must Enter Return Qty");
document.getElementById("ReturnQty_"+i).value='';
document.getElementById("ReturnQty_"+i).focus();	
return false;
}	
return true;
	
}

</script>