<?php 
    if(isset($_POST['Save']))
    {
      for($i=0;$i<count($_REQUEST['SalaryProcessed']);$i++)
      {
      	$id=$_REQUEST['SalaryProcessed'][$i];
      	$update=DB_query("update master_process_salary set net_earning='".$_REQUEST['netamt'][$id]."',rev_sal_amt='".$_REQUEST['reservalamt'][$id]."',status='Y'
      		where id='".$id."'",$db);

      	 $update=DB_query("update hr_incentive_cal set sal_reserve='".$_REQUEST['salrerveamt']."'
       where month='".$_REQUEST['paymonth']."' and year='".$_REQUEST['payyear']."' ",$db);

      } 
    }

?>
<!-- <link rel="stylesheet" type="text/css" href="css/table_frize_1.css"> -->
<link rel="stylesheet" href="css/new_mxerp.css">
<div class="body_contain">
<div class="tab_div">
<h1>Process Salary</h1>
<?php 
//unset($_SESSION['employee_code']);
//error_reporting(0);
include('./includes/fun-php.php');
include('./includes/fun-HRClass.php');
$modid=$_REQUEST['modid'];
$frmid=$_REQUEST['frmid'];
$target_rurl="index.php?route=HRModule/SalaryProcess_new&modid=".$modid."&frmid=".$frmid."";
$rurl_view="index.php?route=View_master_payslip&action=View&modid=".$modid."&frmid=".$frmid."";
//if($_REQUEST['paymonth']==date("n") && isset($_REQUEST['Search'])){?>
	<script>//alert("You not process current month salary.");</script>
<?php
	//$s->PageLocation($target_rurl);
//}
/*else*/ 

function floor_dec($number,$precision,$separator)
{
    $numberpart=explode($separator,$number);
    $numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
    if($numberpart[0]>=0)
    {$numberpart[1]=floor($numberpart[1]);}
    else
    {$numberpart[1]=ceil($numberpart[1]);}

     $ceil_number= $numberpart[1];
    return $ceil_number;
}
function floor_dec1($number,$precision,$separator)
{
    $numberpart=explode($separator,$number);
    $numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
    if($numberpart[0]>=0)
    {$numberpart[1]=floor($numberpart[1]);}
    else
    {$numberpart[1]=ceil($numberpart[1]);}

     $ceil_number= $numberpart[0];
    return $ceil_number;
}

if($_REQUEST['Reset'])
{
	unset($_SESSION['Mstemp_paysal']);			 
	unset($_SESSION['Mstemp']);
	unset($_SESSION['payyear']);
	unset($_SESSION['paymonth']);
	unset($_SESSION['employee_code']);
	unset($_SESSION['emptype']);
	unset($_SESSION['emp_salprocess_site']);
	unset($_SESSION['payyear']);
	unset($_SESSION['paymonth']);	   
	unset($_SESSION['emptype']);
	unset($_SESSION['emp_salprocess_site']);
	$s->PageLocation($target_rurl);
}	
?>
<form action="" method="post" name="myform">
<table width="100%" border="0" cellspacing="0" cellpadding="3">
  <tr class="row1">
    <td width="12%" align="right">Site</td>
    <td width="20%"><select name="site" id="site">
<!--			<option value="000">---ALL---</option>-->
			<?php $site_sql=DB_query("Select loccode, locationname from locations  where CompanyId='".$_SESSION['ACGCompanyId']."' and loccode in('".$_SESSION['AssignedBranch']."')",$db);
			while($site_row=DB_fetch_array($site_sql)){?>
			<option value="<?php echo $site_row['loccode'];?>"<?php echo ($_SESSION['emp_salprocess_site']==$site_row['loccode']?'selected':'');?>><?php echo $site_row['locationname'];?></option>
			<?php } ?>
		</select></td>
    <td width="12%" align="right">Month</td>
    <td width="20%"><select name="paymonth" id="paymonth" onchange="chk_type_employee();">
 		<?php	$arr=array(1=>"Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec");
 				foreach ($arr as $key => $value) {
 				$p='';
 				if( $key==$_REQUEST['paymonth'])
				$p='selected';?>
			<option value="<?php echo $key;?>" <?php echo $p;?> ><?php echo $value;?></option>
 		<?php } ?>
		</select></td>
    <td width="12%" align="right">Year</td>
    <td><select name="payyear" id="payyear">
 		<?php for($i=date('Y');$i>2000;$i--){
 			  $p='';
 	          if( $i==$_REQUEST['payyear'])
	          $p='selected';?>
			<option value="<?php echo $i;?>" <?php echo $p;?>><?php echo $i;?></option>
 		<?php }?>
		</select></td>
</tr>

  <tr class="row1">
    <td colspan="6" align="center" valign="top" style="text-align:center;"><input type="submit" name="Search" class="search" value="Search" onclick="return chksalprocess()"/>
      <input type="submit" name="Reset" class="search" value="Reset"/></td>
    </tr> 
</table>

<?php 
   if(isset($_POST['Search']))
   {
   	   $filter=array();
        if($_REQUEST['paymonth']!='0')
        $filter[]="payslip_month='".$_REQUEST['paymonth']."'";
        if($_REQUEST['payyear']!='0')
        $filter[]="payslip_year='".$_REQUEST['payyear']."'";	

       if(!empty($filter))
       {
       	$filter2=implode( " and ",$filter);
       }
       if($_REQUEST['paymonth']=='1')
       {
       $monthprivious='12';
       $yearprivious=$_REQUEST['payyear']-1;
       }
       else
       {
       	$monthprivious=$_REQUEST['paymonth']-1;
       	$yearprivious=$_REQUEST['payyear'];
       }
   	 $privious_reverseamt=DB_fetch_array(DB_query("select sum(reverse_amt) as amt,sum(other_cal_reserve) as other_cal_reserve ,sum(sal_reserve) as sal_reserve from hr_incentive_cal  where month='".$monthprivious."' and year<='".$yearprivious."' order by id desc limit 0,1 ",$db));
   	 $reversalamt= (($privious_reverseamt['amt']+$privious_reverseamt['other_cal_reserve'])-$privious_reverseamt['sal_reserve']); 


 $q3 =DB_query("Select * from deduction_master",$db); $ded_rows=DB_num_rows($q3) ;?>
<?php $q4 =DB_query("Select * from allowmaster",$db); $all_rows=DB_num_rows($q4);?>
<?php $q5 =DB_query("SELECT * FROM other_deduction_master WHERE status='A' AND type='D'",$db); $other_dd_rows=DB_num_rows($q5) ;?>
<?php $q6 =DB_query("SELECT * FROM other_deduction_master WHERE status='A' AND type='A'",$db); $other_aa_rows=DB_num_rows($q6) ;?>
<br>
	<div style="width:1250px; overflow:auto; margin:auto;">	
	<table width="140%" id="tableDataProduction" cellpadding="3" cellspacing="0" border="0" class="thborder">
	<tr>
	  <th colspan="6" ></th>
		<th style="text-align:center" colspan="<?php echo $all_rows+2;?>"><b>EARNINGS</b></th>
		<th style="white-space:nowrap;"><b>GROSS WAGES</b></th>
		<th style="text-align:center" colspan="<?php echo $ded_rows+$other_dd_rows+3;?>"><b>DEDUCTIONS</b></th>
		<?php if(isset($other_aa_rows) && $other_aa_rows>=1){?>
		<th style="text-align:center" colspan="<?php echo $other_aa_rows+1;?>"><b>ADDITIONS</b></th>
		<?php } ?>		
		<th colspan="6" style="text-align:center">Reserve Amt  <b><?php //echo $reversalamt;  ?></b><input type="hidden" id="revamt" value="<?php echo $reversalamt; ?>"> </th>
		<th style="text-align:center;"></th>
	</tr>
	<tr>
    	<th width="3%"><input name="SalaryProcessed" type="checkbox" id="SalaryProcessed" onclick="LeadData()" /></th>
        <th width="6%" style="white-space:nowrap;">Emp Code</th>
        <th width="16%"  style="white-space:nowrap;">Emp Name</th>
        <th width="15%" style="white-space:nowrap;">Designation</th>
        <th width="3%" style="white-space:nowrap;">Month Days</th>		
	    <th width="3%" style="white-space:nowrap;">Sal Days</th>  
	    <th width="3%" style="white-space:nowrap;">No. Of <br/>Sunday Deduction</th>  
        <!-- <th >Monthly Salary</th> -->
        <th width="3%" style="white-space:nowrap;">Basic</th>
		<?php
	  		$net_earning=0;
	  		$query_allowances =DB_query("Select * from allowmaster",$db); 
	  		$j=1;
	  		$n=DB_num_rows($query_allowances);
	  		$nx= round(70/$n,2);
	  		while($row_allowances=DB_fetch_array($query_allowances))
	  		{ 		  
		?> 
    	<th width="3%">
    		<?php echo $row_allowances['allowcode'];?><input name="allowmasterid[]" type="hidden"  value="<?php echo $row_allowances['id'];?>"/></th>
		<?php if($row_allowances['allowcode']=='LTA') {?>
		<!--<th>Special Allowance</th>-->
		<?php } ?>
     	<?php } ?>
		<th width="3%">Spl. Allowance</th>
		<th width="3%">&nbsp;</th>
        <?php 
		$essi='';
		$query_allowances =DB_query("Select * from deduction_master",$db); 
	 	   	$n=DB_num_rows($query_allowances);
	   	   	$nx1= round(70/($n+3),1);
	  		while($row_allowances=DB_fetch_array($query_allowances)){
			$essi[]=$row_allowances['code'];
			?> 
    	<th width="3%"><?php echo $row_allowances['code'];?><input name="deductionid[]" type="hidden"  value="<?php echo $row_allowances['id'];?>"/></th>         
     	<?php } ?>
     	<?php 
     	$GetOther_Ddmaster = DB_query("SELECT id,name FROM other_deduction_master WHERE status='A' and type='D' AND CompanyId='".$_SESSION['ACGCompanyId']."'",$db);
	  				while($RecOthr_Dd=DB_fetch_array($GetOther_Ddmaster))
	  				{?>
                    <th><?php echo ''.$RecOthr_Dd['name'].'';
                   $ddArr[]=$RecOthr_Dd['id'];
					?>
				 </th>
					<?php } ?>		
	    <th width="3%">Adv</th>   
		<th width="3%">Loan</th>      	
     	<th width="3%" style="white-space:nowrap;">Total(A)</th>
     	<?php 
     	$GetOther_Amaster = DB_query("SELECT id,name FROM other_deduction_master WHERE status='A' and type='A' AND CompanyId='".$_SESSION['ACGCompanyId']."'",$db);
	  				while($RecOthr_A=DB_fetch_array($GetOther_Amaster))
	  				{?>
                    <th><?php echo ''.$RecOthr_A['name'].'';
                   $aaArr[]=$RecOthr_A['id'];
					?>

				 </th>
					<?php } ?>
		<th width="3%" style="white-space:nowrap;">Total(B) </th>
		<th width="3%" style="white-space:nowrap;">OT Amount</th> 
      	<th width="3%" style="white-space:nowrap;">Gross Wages</th>    	
    	<th width="3%" style="white-space:nowrap;">TDS</th>
    	<th width="3%" style="white-space:nowrap;">Reserve Pay</th>			   	
		<th width="3%" style="white-space:nowrap;">Net Pay</th>		
     	
		
    </tr>
   <?php 
      
      $i=0;
    

      $monthlyotherded=DB_query("SELECT B.amount as amt,B.other_ded as other_ded,B.other_ded_type as ded_type,A.empid as emp_id FROM          monthly_other_deducation_details B INNER JOIN `monthly_other_deducation` A 
      	                ON A.id=B.parentid WHERE A.month='".$_REQUEST['paymonth']."' 
      	                AND A.year='".$_REQUEST['payyear']."' AND A.site='".$_REQUEST['site']."'",$db);
      while($monthly_other_row=DB_fetch_array($monthlyotherded))
      {
      	$monthly_ded_amt[$monthly_other_row['emp_id']][$monthly_other_row['other_ded']][$monthly_other_row['ded_type']]=$monthly_other_row['amt'];
      }
    
   

      $sql=DB_query("select * from master_process_salary where $filter2 and status='N'",$db);
      while($RowData=DB_fetch_array($sql)) {  
      $sql_allowance=DB_query("select * from payslip_salary where mst_prosal='".$RowData['id']."' ",$db);
      while($row_allowance=DB_fetch_array($sql_allowance)) {
      	$allowance_amt[$row_allowance['emp_id']][$row_allowance['allowance_id']][$row_allowance['allowance_type']]=$row_allowance['allowance_amount'];}

      

       $Locked_payment=DB_fetch_array(DB_query("SELECT B.locked FROM payment_revised AS A 
					   INNER JOIN payment_revised_details AS B ON A.id=B.payment_revised_id 
					   WHERE A.payment_month='".$_REQUEST['paymonth']."' 
					   and A.payment_year='".$_REQUEST['payyear']."' 
					   and B.empid='".$RowData['emp_id']."'",$db));				
				
				if($Locked_payment['locked']=='Y')
				$paymentlock="disabled";
				else
				$paymentlock='';	
			?>
   <tr>
   	<td><input name="SalaryProcessed[]" id="SalaryProcessed_<?php echo $i;?>" type="checkbox" value="<?php echo $RowData['id']; ?>"</td>
   	<td style=""><?php echo $s->getField('empmaster','id',$RowData['emp_id'],'emp_code'); ?>&nbsp;</td>
    <td><?php if($s->getField('empmaster','id',$RowData['emp_id'],'payment_mode')=='Cash')	
            { echo  $s->getField('empmaster','id',$RowData['emp_id'],'emp_name') ;}
	   			else{ echo $s->getField('empmaster','id',$RowData['emp_id'],'emp_name');}
					?></td>
       				<td><?php echo $s->getField('desigmaster','id',$s->getField('empmaster','id',$RowData['emp_id'],'designation'),'designame');?></td>
        			<td><?php echo cal_days_in_month(CAL_GREGORIAN, $RowData['payslip_month'],$RowData['payslip_year']);; ?></td>		
					<td><?php echo $RowData['workingdays']; ?></td>	
					<td><?php echo $RowData['sunday_deduction_count']; ?></td>
        			<td><?php echo $gbasic= $RowData['basic_salary'];?></td>
        			<?php $q1 =DB_query("Select * from allowmaster",$db); while($rq1=DB_fetch_array($q1)) { ?>
       				<td><?php echo $allowance_amt[$RowData['emp_id']][$rq1['id']]['A']; ?></td>
       				<?php } ?>	
       				<td><?php echo $allowance_amt[$RowData['emp_id']][100]['A']; ?></td>	
                    <td><?php echo $RowData['gross_salary']; ?></td>
               <?php $q2 =DB_query("Select * from deduction_master",$db); while($rowded=DB_fetch_array($q2)){ ?>
                   <td><?php echo $dedamt[$RowData['emp_id']][]= $allowance_amt[$RowData['emp_id']][$rowded['id']]['D']; ?></td>
                   <?php } ?>
                   <?php if($ddArr){ foreach($ddArr As $value){ ?>
					<td><?php echo $dedamt[$RowData['emp_id']][]= $monthly_ded_amt[$RowData['emp_id']][$value]['D'] ?></td>
					<?php } } ?>
					<td><?php echo $dedamt[$RowData['emp_id']][]= $RowData['advance_balance']; ?></td>
					<td><?php echo $dedamt[$RowData['emp_id']][]= $RowData['loan']; ?></td>					
					<td><?php if(!empty($dedamt[$RowData['emp_id']])) echo $totalded= array_sum($dedamt[$RowData['emp_id']]); ?></td>
					<?php if($aaArr){ $otherdedA=0;	foreach($aaArr As $value){ ?>
					<td><?php echo $addamt[$RowData['emp_id']][]= $monthly_ded_amt[$RowData['emp_id']][$value]['A'] ?></td>
					<?php } } ?>
					<td><?php if(!empty($addamt[$RowData['emp_id']])) echo $total_add= array_sum($addamt[$RowData['emp_id']]); ?></td>
					<td><?php echo $RowData['OTBasicAmount']; ?></td>
					<td><?php echo round(($RowData['gross_salary']+$total_add)-$totalded); ?></td>
					<td><?php echo $RowData['tds_deduction']; ?><input type="hidden" id="net_<?php echo $i; ?>"
					   value="<?php echo round($RowData['net_earning']); ?>" ></td>
				<td><input type="text" style="width:120px;" name="reservalamt[<?php echo $RowData['id']; ?>]" id="reversalamt_<?php echo $i; ?>" class="areaSum" onkeyup="calamt(<?php echo $i; ?>,this.value)" value=""></td>
				<td><input type="text"  style="width:120px;" name="netamt[<?php echo $RowData['id']; ?>]" id="netamt_<?php echo $i; ?>" value="<?php echo round($RowData['net_earning']); ?>" ></td>		
				
   </tr>

    <?php $i++; } ?>
    <input type="hidden" name="salrerveamt" id="salrerveamt" value="">
    </table>
  </div>
    <p align="center"><input type="submit" name="Save" value="Save" class="search" /></p>
    <?php } ?>
	
	 
  </form>    


<script language="javascript">
	function calamt(str,val)
	{

            var revamt=document.getElementById("revamt").value;
            if(revamt=='') revamt=0;
		    var sumOfArea=0;			
			$('#tableDataProduction').find('input[type="text"][class="areaSum"]').each(function(){
		    if($(this).val()!='')
		    sumOfArea= sumOfArea + parseFloat($(this).val());
		    else
		    sumOfArea= sumOfArea;
		    });
		    if(sumOfArea>revamt)
		    {
               alert("Reserve amt should be less then total Reserve amt");
               document.getElementById("reversalamt_"+str).value='';
               var val=0;
               var net=document.getElementById("net_"+str).value;
			   if(net=='') net=0;   
			  var totalamt=parseFloat(val)+parseFloat(net);	
			  document.getElementById("netamt_"+str).value=totalamt.toFixed(2);
			  document.getElementById("salrerveamt").value=sumOfArea.toFixed(2);
            }
		    else
		    {		  
			   
			  var net=document.getElementById("net_"+str).value;
			   if(net=='') net=0;   
			  var totalamt=parseFloat(val)+parseFloat(net);	
			   document.getElementById("netamt_"+str).value=totalamt.toFixed(2);
			   document.getElementById("salrerveamt").value=sumOfArea.toFixed(2);
            }  

	} 

function LeadData()
{	
	//var test=document.getElementById("SalaryProcessed").value;
	myCheckboxArray = document.myform.elements["SalaryProcessed[]"];
	var t=myCheckboxArray.length;
	if(document.getElementById('SalaryProcessed').checked==true)
	{	
		if(t==undefined)
		document.getElementById('SalaryProcessed_'+0).checked=true;		
		for (var i = 0; i < t; i++)
		{
			//if(document.getElementById('process_status_'+i).value=='N'){
				document.getElementById('SalaryProcessed_'+i).checked=true;
			//}else{
			//	document.getElementById('SalaryProcessed_'+i).disabled=true;
			//}
		}	
	}
	else
	{
		if(t==undefined)		
		document.getElementById('SalaryProcessed_'+0).checked=false;		
	
		for (var i = 0; i < t; i++)
		{
			document.getElementById('SalaryProcessed_'+i).checked=false;	
		}
	}
}

function chksalprocess()
{
		var today = new Date();
		var dd = today.getDate();
		var currmonth = today.getMonth()+1; //January is 0!
		var CurrentYear=today.getFullYear();
		
		var selmonth=document.getElementById("paymonth").value;
		var selyear=document.getElementById("payyear").value;
		
		//if(selmonth>=currmonth)
		//{
			//alert("You Can Process Only Previous Month Salary");
			//return false;
		//}
		
	//return false;
}
function chk_type_employee()
{
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)
	{
           //alert(xmlhttp.responseText);
	  document.getElementById("employee_code").innerHTML=xmlhttp.responseText;
	}
	}
	var site=document.getElementById("site").value;
	var month=document.getElementById("paymonth").value;
	var year=document.getElementById("payyear").value;
	var type=document.getElementById("emptype").value;
	xmlhttp.open("GET","check_data_ajax.php?section=chk_type_employee&site="+site+"&month="+month+"&year="+year+"&type="+type,true);
	xmlhttp.send();
}

function chk_type_dept_employee()
{
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)
	{
           //alert(xmlhttp.responseText);
	  document.getElementById("employee_code").innerHTML=xmlhttp.responseText;
	}
	}
	var site=document.getElementById("site").value;
	var month=document.getElementById("paymonth").value;
	var year=document.getElementById("payyear").value;
	var type=document.getElementById("dept").value;
	xmlhttp.open("GET","check_data_ajax.php?section=dept_wise_employee&site="+site+"&month="+month+"&year="+year+"&type="+type,true);
	xmlhttp.send();
}


</script>
</div>
</div>