<link rel="stylesheet" href="css/new_mxerp.css">
<?php ob_start();
$PageSecurity = 2;
include('includes/SQL_CommonFunctions.inc');
include('includes/DefinePOClass.php');
$title = _('Job Work Return');
$PageName ='Job Work Return';
if($_REQUEST['Save']!='')
{

	$startYr = explode('-', $_SESSION['financialYrStart']);
	$endYr = explode('-', $_SESSION['financialYrEnd']);
	$startYr[0];
	$endYr[0];
	$financial=substr($startYr[0],-2)."-".substr($endYr[0],-2); 
	 
	 
	
	 	$branch=$_REQUEST['site'];
	 	$prefSql="select prefix_code from prefix_tbl where prefix_name = 'Job Work Return Slip'";
		$resultPrfx = DB_query($prefSql,$db);
		$Prefxrow=DB_Fetch_array($resultPrfx);
		$prefixcode=$Prefxrow['prefix_code'];
		
		
	  $sql="select returnSlipNo from job_work_return where site = '".$_REQUEST['site']."' 
      and CompanyId='".$_SESSION['ACGCompanyId']."' 
      and INSTR(`returnSlipNo`, '$financial') > 0 order by returnSlipNo DESC LIMIT 0,1";
		$result = DB_query($sql,$db);
		$numrows = DB_num_rows($result);
		if($numrows>0)
		{
			$myrow=DB_Fetch_array($result);
			$ExplBill=explode("/",$myrow['returnSlipNo']);
			$maxval = $ExplBill[3];
		}
		else
		{$maxval=0;}
	 

		$strChar=$branch."/".$prefixcode."/".$financial."/";
		$strFinal = $maxval+1;
		 $strBothFinal = $strChar.str_pad($strFinal,5,"0",STR_PAD_LEFT); 

	
               $insert1="Insert into job_work_return set 
								 site='".$_REQUEST['site']."',
								 store='".$_REQUEST['store']."',  
								 vendor='".$_REQUEST['vendor']."',  
								 returnSlipNo='".$strBothFinal."',  
								 returnDate='".FormatDateForSQL($_REQUEST['returnDate'])."',  
								 challanNo='".$_REQUEST['challanNo']."',  
								 partyChallanNo='".$_REQUEST['partyChallanNo']."',  
								 remarks='".$_REQUEST['remarks']."',
								 created_by='".$_SESSION['UserID']."',
								 created_date='".FormatDateForSQL(date('d/m/Y'))."',
								 CompanyId='".$_SESSION['ACGCompanyId']."' "; 
							
								
	$insertResult1=DB_query($insert1,$db); 
	$LastId=DB_Last_Insert_ID($db,'job_work_return','id');
	
	if($LastId!='')
	{
		$total=0;
		for($ct=0;$ct<count($_REQUEST['chk']);$ct++)
		{
         $ctr=$_REQUEST['chk'][$ct];
						
			$insert2="Insert into job_return_details set
								masterId='".$LastId."',
								challanNo='".$_REQUEST['challanNo']."', 
								mst_itemId='".$_REQUEST['itemCode'][$ctr]."',  
								orderQty='".$_REQUEST['issueqty'][$ctr]."',  
								receivedQty='".$_REQUEST['receivedQty'][$ctr]."',  
								pendingQty='".$pendingQty."',
								totalRec='".$totalRecievedQty."',
								rate='".$_REQUEST['rate'][$ctr]."',
								process='".$_REQUEST['process'][$ctr]."',
								itemStatus='".$itemStatus."' ";
			$insertResult2=DB_query($insert2,$db); 
			
         
         $balqty=$_REQUEST['pending'][$ctr]-$_REQUEST['receivedQty'][$ctr];
				  
			if($balqty==0)
			{
			$update=DB_query("update job_work_issue_details set status=1 
           where masterId='".$_REQUEST['challanNo']."'
            and mst_itemid='".$_REQUEST['itemCode'][$ctr]."'",$db);	
			}
         
         
         if(count($_REQUEST['chk1'])<=0)
          {
         
          //*****************************************	Stock Summary ************************************//		 
					  
            $sql_outward=DB_query("select * from stock_outward where type_id='".$_REQUEST['challanNo']."'
                          and mst_itemid='".$_REQUEST['itemCode'][$ctr]."' and type='RGP'",$db);
               $amt=0;
               $qty=0;
               $flag1=0;
                      $numrow=DB_num_rows($sql_outward); 
                        while($row_outward=DB_fetch_array($sql_outward))
                        {
                        if($row_outward['outward_rate']!='')
                        {
                         $amt=$amt+$row_outward['outward_value'];
                         $qty=$qty+$row_outward['outward_qty'];

                         $flag1=$flag1+1;

                        }
                        }
                        if($flag1==$numrow)
                        {
                         if($qty!='')
                         $rate_cal=$amt/$qty;
                         else
                          $rate_cal='';
                         $inwardamt=$rate_cal*$_REQUEST['receivedQty'][$ctr];
                        }
                       else 
                        { 
                         $rate_cal='';
                         $inwardamt='';
                        
                        
                        }
         
         
         
         
         
         
         
         
                 $data_stock['site']=$_REQUEST['site'];
                 $data_stock['store']=$_REQUEST['store'];
                 $data_stock['mst_itemid']=$_REQUEST['itemCode'][$ctr];
                 $data_stock['against_id']=$LastId;
                 $data_stock['type']='RGPOUT';  
                 $data_stock['trasaction']=$strBothFinal;
                 $data_stock['inwardqty']=$_REQUEST['receivedQty'][$ctr];
                 $data_stock['inward_rate']=$rate_cal;
                 $data_stock['inwared_value']=$inwardamt;
                 $data_stock['pendingqty']=$_REQUEST['receivedQty'][$ctr];
                 $data_stock['against_tra_id']=$_REQUEST['challanNo'];
                 $data_stock['date']=date('Y-m-d H:i:s', time());

                 $s->RecordInsert('stock_inward', $data_stock);  
         
          }
			
		}
      
      
      
      for($ct=0;$ct<count($_REQUEST['chk1']);$ct++)
		{
         $ctr1=$_REQUEST['chk1'][$ct];
						
			$insert2="Insert into job_return_details1 set
								masterId='".$LastId."',
								mst_itemId='".$_REQUEST['itemCode1'][$ctr1]."',  
								issue_qty='".$_REQUEST['orderQty'][$ctr1]."',  
								qty='".$_REQUEST['receivedQty1'][$ctr1]."',  
								waste_qty='".$_REQUEST['waste'][$ctr1]."'";
         
			$insertResult2=DB_query($insert2,$db); 
			
         
         $balqty1=$_REQUEST['pendingqty1'][$ctr1]-($_REQUEST['receivedQty1'][$ctr1]+$_REQUEST['waste'][$ctr1]);
				  
			if($balqty==0)
			{
			$update=DB_query("update job_work_issue_details1 set status=1 
           where parent_id='".$_REQUEST['challanNo']."'
            and mst_itemId='".$_REQUEST['itemCode1'][$ctr1]."'",$db);	
			}
         
         //*****************************************	Stock Summary ************************************//		 
					  
            $sql_outward=DB_query("select * from stock_outward where type_id='".$_REQUEST['challanNo']."'
                          and mst_itemid='".$_REQUEST['itemCode1'][$ctr1]."' and type='RGP'",$db);
               $amt=0;
               $qty=0;
               $flag1=0;
                      $numrow=DB_num_rows($sql_outward); 
                        while($row_outward=DB_fetch_array($sql_outward))
                        {
                        if($row_outward['outward_rate']!='')
                        {
                         $amt=$amt+$row_outward['outward_value'];
                         $qty=$qty+$row_outward['outward_qty'];

                         $flag1=$flag1+1;

                        }
                        }
                        if($flag1==$numrow)
                        {
                         if($qty!='')
                         $rate_cal=$amt/$qty;
                         else
                          $rate_cal='';
                         //$rate_cal=$amt/$qty;
                         $inwardamt=$rate_cal*$_REQUEST['receivedQty1'][$ctr1];
                        }
                       else 
                        { 
                         $rate_cal='';
                         $inwardamt='';
                        
                        
                        }
         
         
         
         
         
         
         
         
                 $data_stock['site']=$_REQUEST['site'];
                 $data_stock['store']=$_REQUEST['store'];
                 $data_stock['mst_itemid']=$_REQUEST['itemCode1'][$ctr1];
                 $data_stock['against_id']=$LastId;
                 $data_stock['type']='RGPOUT';  
                 $data_stock['trasaction']=$strBothFinal;
                 $data_stock['inwardqty']=$_REQUEST['receivedQty1'][$ctr1];
                 $data_stock['inward_rate']=$rate_cal;
                 $data_stock['inwared_value']=$inwardamt;
                 $data_stock['pendingqty']=$_REQUEST['receivedQty1'][$ctr1];
                 $data_stock['against_tra_id']=$_REQUEST['challanNo'];
                 $data_stock['date']=date('Y-m-d H:i:s', time());

                 $s->RecordInsert('stock_inward', $data_stock);  
         
         
         
			
			
		}
      
      //---------------- First Child Table -----------------------//
      $col=0;
      $sql_data=DB_query("select * from job_work_issue_details
       where masterId='".$_REQUEST['challanNo']."'",$db);
       $num_data=DB_num_rows($sql_data);
			 while($row_data=DB_fetch_array($sql_data))
		     { 	if($row_data['status']==1) 	{  	$col=$col+1;  }		 }
		 
      //******************* Second Child Table *******************//
           
           $col1=0;
      $sql_data1=DB_query("select * from job_work_issue_details1
       where parent_id='".$_REQUEST['challanNo']."'",$db);
       $num_data1=DB_num_rows($sql_data1);
			 while($row_data1=DB_fetch_array($sql_data1))
		     { 	if($row_data1['status']==1) 	{  	$col1=$col1+1;  }		 }
		 
           
           
           
      //**********************************************************//     
      
	
	   if($col==$num_data && $col1==$num_data1 )
		   {			
	
	$updateIssueStatus=DB_query("Update job_work_issue set status='received' 
    where id='".$_REQUEST['challanNo']."'",$db);
         }
 }


prnMsg( _('Record Inserted Successfully'),'success');
echo "<script>location.href='index.php?route=JobWorkReturnList&modid=".$_REQUEST['modid']."&frmid=".$_REQUEST['frmid']."'</script>";
}
?>
<script language="javascript" type="text/javascript">

function chkQty(val,i)
{
	var pendQty=document.getElementById("pendingQty_"+i).value;
		if(pendQty=='') { comQty=document.getElementById("orderQty_"+i).value; }
		else { comQty=document.getElementById("pendingQty_"+i).value; }

		
			if(parseFloat(val)>parseFloat(comQty))
			{
			alert('Recieved Qty Cannot Be Greater Than Pending Qty');
			document.getElementById("receivedQty_"+i).value='0';
			document.getElementById("receivedQty_"+i).focus();
			}
}

function generateReturn(str)
{
  if (str.length==0)
  {
  document.getElementById("store").innerHTML="";
  document.getElementById("vendor").innerHTML="";
  document.getElementById("challanNo").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)
    {
   	var data=xmlhttp.responseText.split("__");	
	
	document.getElementById("store").innerHTML=data[0];
  	document.getElementById("vendor").innerHTML=data[1];
    }
  }
xmlhttp.open("GET","JobReturnNo.php?branch="+str,true);
xmlhttp.send();
}
function ChallanList(str)
{
var s=document.getElementById("site").value;	
	if (str.length==0)
  {
  document.getElementById("CHID").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("challanNo").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","JobWorkChallan.php?r="+str+"&s="+s,true);
xmlhttp.send();
}
function getChallanDetails(str)
{
if (str.length==0)
  {
	document.getElementById("challanDate").value="";
  	document.getElementById("jobDate").value="";
	document.getElementById("partyJWNo").value="";
	document.getElementById("jobNumber").value="";
	document.getElementById("showItems").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)
    {
    var data=xmlhttp.responseText.split("__");	
	document.getElementById("challanDate").value=data[0];
  	document.getElementById("jobDate").value=data[1];
	document.getElementById("partyJWNo").value=data[2];
	document.getElementById("jobNumber").value=data[3];
	document.getElementById("showItems").innerHTML=data[4];
   document.getElementById("showItems1").innerHTML=data[5];
    }
  }
xmlhttp.open("GET","JobWorkChallan.php?q="+str,true);
xmlhttp.send();
}


function showqty(str,id)
{
 var pend=document.getElementById("pending_"+id).value;
 
 if(pend<str)
 {
 alert("Receiving Qty Should be less then  pending qty");
 document.getElementById("receivedQty_"+id).value='';
 document.getElementById("receivedQty_"+id).focus();
 
 return false;
 }
return true;
 
}

function showwaste(str,id)
{
 
  var pend=document.getElementById("pendingqty1_"+id).value;
 
 if(pend<str)
 {
 alert("Receiving Qty Should be less then  pending qty");
 document.getElementById("receivedQty1_"+id).value='';
 document.getElementById("receivedQty1_"+id).focus();
 document.getElementById("waste_"+id).value='';
 
 return false;
 }
 
return true;
 
}
function wastqty(str,id)
{
  var pend=document.getElementById("pendingqty1_"+id).value;
 var receive=document.getElementById("receivedQty1_"+id).value;
  
 
  var totalpending=parseFloat(pend)-parseFloat(receive);
  if(totalpending<str)
  {
 alert("Plz check Waste Qty");
 document.getElementById("waste_"+id).value='';
 document.getElementById("waste_"+id).focus();
  }
 
   return true;
}

function validate()
{
 if(document.getElementById("site").value=='0')
 {
 alert("Must Select Branch");
 document.getElementById("site").focus();
 return false;
 }
 if(document.getElementById("store").value=='0')
 {
 alert("Must Select Store");
 document.getElementById("store").focus();
 return false;
 }
 if(document.getElementById("vendor").value=='0')
 {
 alert("Must Select Vendor");
 document.getElementById("vendor").focus();
 return false;
 }
 if(document.getElementById("challanNo").value=='0')
 {
 alert("Must Select Challan No");
 document.getElementById("challanNo").focus();
 return false;
 }
 return true; 
}


</script>
<div class="body_contain">
<div class="tab_div">

<h1>Job Work Return Slip</h1>
<form action="" method="post">
<table width="100%" border="1" cellpadding="3" cellspacing="0" style="border-collapse:collapse; border:#666666 solid 1px;" align="center">
  <tr>
    <td class="tabledata3">Branch</td>
    <td style="width:250px">
	<?php
	if($_SESSION['AssignedBranch']!='')
	  {	  	
  $ss="Select loccode, locationname from locations  where CompanyId='".$_SESSION['ACGCompanyId']."' and loccode in('".$_SESSION['AssignedBranch']."')";
	  	 $site_sql=DB_query($ss,$db);
	  }
	  else
	  {
		$ss="Select loccode,locationname from locations where CompanyId='".$_SESSION['ACGCompanyId']."'";
		$site_sql=DB_query($ss,$db);
	  }
	?>
	<select name="site" id="site" style="width:100%" onchange="generateReturn(this.value)">
      <option value="0">Select</option>
     <?php 
					while($Row=DB_fetch_array($site_sql)){?>
             <option value="<?php echo $Row['loccode']?>"<?php echo($_SESSION['Site']==$Row['loccode'] ? 'selected':'');?> ><?php echo $Row['locationname']?></option>
                                <?php  } ?>
    </select></td>
	<td  rowspan="4" id="JWID">
	<table width="100%" border="1" cellpadding="3" cellspacing="0" style="border-collapse:collapse; border:#666666 solid 1px;">
	<tr>
	<td class="tabledata3" width="45%">Challan Date </td>
    <td width="55%"><input type="text" name="challanDate" id="challanDate" readonly value="<?php echo ConvertSQLDate($_REQUEST['challanDate']);?>" style="width:100%" /></td>
	</tr>
	<tr>
	<td class="tabledata3">Job Work Date </td>
    <td><input type="text" name="jobDate" id="jobDate" readonly value="<?php echo ConvertSQLDate($_REQUEST['jobDate']);?>"  style="width:100%"/></td>
	</tr>
	<tr>
	<td class="tabledata3">Party Job Work No. </td>
	<td><input type="text" name="partyJWNo" id="partyJWNo" readonly value="<?php echo $_REQUEST['partyJWNo'];?>"  style="width:100%" /></td>
	</tr>
	<tr>
	<td class="tabledata3">Job Work No.</td>
	<td id="JOBID"><input type="text" name="jobNumber" id="jobNumber" readonly value="<?php echo $_REQUEST['jobNumber'];?>"   style="width:100%"/></td>
	</tr>
	</table>	</td>
   <td rowspan="4" >
    <table width="100%" border="1" cellpadding="3" cellspacing="0" style="border-collapse:collapse; border:#666666 solid 1px;">
     <tr>
      <td class="tabledata3">Return Slip No. </td>
  <td colspan="3" id="ReturnId"><input name="returnSlipPrefix" type="text" style="width:100%" id="returnSlipPrefix" value="Auto Generated"  readonly/>
  </td>
     </tr>
     <tr>
  <td class="tabledata3">Party Challan No. </td>
  <td><input type="text" name="partyChallanNo" id="partyChallanNo" value="<?php echo $_REQUEST['partyChallanNo'];?>"  style="width:100%" /></td>
     </tr>
     <tr>
  <td class="tabledata3">Return Date </td>
  <?php if(isset($_REQUEST['returnDate']))$returnDate=$_REQUEST['returnDate']; else $returnDate=date('d/m/Y');?>
  <td><input type="text" name="returnDate" id="returnDate" value="<?php echo $returnDate;?>" class="datepicker"  style="width:100%" /></td>
  <tr>
   <td class="tabledata3">&nbsp;</td>
   <td>&nbsp;</td>
  </tr>  
  
     </tr>
    </table>
   </td>
  </tr>
  <tr>
  	<td class="tabledata3">Godown</td>
    <td><?php
    	
	     $sql_store ="SELECT id, StoreName,storecode FROM storetype WHERE CompanyId='".$_SESSION['ACGCompanyId']."' AND Store_Site IN ('".$_SESSION['AssignedBranch']."')";
		 $resultStkLocs = DB_query($sql_store,$db);
		?>
      <select name="store" id="store" style="width:100%">
        <option value="0">Select</option>
        <?php 
		while ($myrow=DB_fetch_array($resultStkLocs))
		{?>
        <option value="<?php echo $myrow['StoreCode'];?>"><?php echo $myrow['StoreName'];?></option>
        <?php 
		}
		?>
      </select></td>
     </tr>
     <tr>
    <td class="tabledata3">Vendor</td>
    <td><select name="vendor" id="vendor" style="width:100%" onchange="ChallanList(this.value)">
        <option name="0">Select</option>
        <?php 
	$vend_sql=DB_query("Select id,vendor_name from suppliers where CompanyId='".$_SESSION['ACGCompanyId']."' AND site IN ('".$_SESSION['AssignedBranch']."')",$db);
	while($vend_row=DB_fetch_array($vend_sql))
	{?>
        <option value="<?php echo $vend_row['vendor_code'];?>"><?php echo $vend_row['vendor_name'];?></option>
        <?php 	
	}
	?>
    </select></td>
  </tr>
  <tr>
    <td class="tabledata3">57 F Challan No. </td>
    <td id="CHID"> <?php 
	$sql="Select id,challanNumber from job_work_issue where site='".$_REQUEST['site']."' and vendor='".$_REQUEST['vendor']."'";
	$result=DB_query($sql,$db);
?>
<select name="challanNo" id="challanNo" style="width:100%" onchange="getChallanDetails(this.value)">
	<option value="0">Select</option>
	<?php 
	while($Myrow=DB_fetch_array($result))
	{?>
	<option value="<?php echo $Myrow['id'];?>"<?php echo ($_REQUEST['challanNo']==$Myrow['id']?'selected':'')?>><?php echo $Myrow['challanNumber'];?></option>
	<?php 	
	}
	?>
	</select></td>
  </tr>

</table>

<br>
<div style="overflow:auto; width:1280px;" id="showItems"> 
</div>
<br>
<div style="overflow:auto; width:1280px;" id="showItems1"> 
</div>
<table width="100%" border="1" cellpadding="3" cellspacing="0" style="border-collapse:collapse; border:#666666 solid 1px; margin-top:15px;">
<tr>
<td class="tabledata3">Remarks</td>
<td><textarea name="remarks" id="remarks" style="width:100%" ></textarea></td>
</tr>
</table>
<p align="center"><input type="submit" name="Save" value="Save" class="search" onclick="return validate();" /><input type="submit" name="Cancel" value="Cancel" class="search" /></p>
</form>

</div></div>