
<style>.top-bar-minimize{display:none;}
thead, tfoot {display: table-header-group;}
.top-bar+.well,.accordion .accordion-heading+.accordion-body{display: inline-block !important;width: 100% !important;overflow: inherit !important;} 
.recepit {
	width: 717px !important;
	height: 344px !important;
}
</style><?php
$pgMod="add_salary";
$pgAct="view"; 
if(isset($_GET['action']) && trim($_GET['action'])!='')
		$pgAct=strtolower($_GET['action']);

if(isset($_POST['saveme']))
{
    $tc = $_POST["totalcomponents"][0];
    // echo $totalcomponents;
    $totalcomponents = count(json_decode($tc));

    $tc = json_decode($tc);

    $j = 0;
    foreach($_POST["idno"] as $idno){

        $detail = array();
        
        for($i = 0; $i < $totalcomponents; $i++){
            $temp = $idno."_".$tc[$i];
            $val = $_POST[$temp];
            $detail[$tc[$i]] = "".$val;
        }

        $staff = $db->getRow("select * from staff where idno='$idno' ");

        $absentamount = $_POST["one_day_payment"][$j]*$_POST["total_absent"][$j];
    
        $check = $db->getVal("select id from salery where idno='$idno' and month='$_POST[month]' and session='".$_SESSION["admin"]["session"]."' ");
        if($check > 0){
                $saveAry=array(
                    "basic_salary"      =>  $_POST["basic_salary$idno"],
                    "detail"            =>  json_encode($detail),
                    "one_day_payment"   =>  $_POST["one_day_payment"][$j],
                    "absent_amount"     =>  $absentamount,
                    "total_absent"      =>  $_POST["total_absent"][$j],
                    "cl"                =>  $_POST["cl"][$j],
                    "gross_total"       =>  $_POST["grasstotal"][$j],
                    "added_by"          =>  $_SESSION["admin"]["uid"]
    			);
            $flgIn=$db->updateAry("salery",$saveAry, "where idno='$idno' and month='$_POST[month]' and session='".$_SESSION["admin"]["session"]."' ");
        }   else {
                $saveAry=array(
                    "idno"              =>  $idno,
                    "name"              =>  $staff["name"],
                    "accountno"         =>  $staff["accountno"],
                    "basic_salary"      =>  $_POST["basic_salary$idno"],
                    "detail"            =>  json_encode($detail),
                    "one_day_payment"   =>  $_POST["one_day_payment"][$j],
                    "absent_amount"     =>  $absentamount,
                    "total_absent"      =>  $_POST["total_absent"][$j],
                    "cl"                =>  $_POST["cl"][$j],
                    "gross_total"       =>  $_POST["grasstotal"][$j],
                    "month"             =>  $_POST["month"],
                    "session"           =>  $_SESSION["admin"]["session"],
                    "school_id"         =>  1,
                    "added_by"          =>  $_SESSION["admin"]["uid"]
			    );
            $flgIn=$db->insertAry("salery",$saveAry);
        }
        $j++;
    }


    // die();

// $resulr1=$_POST['idno'];
// foreach($resulr1 as $x => $x_value) {

// 	$db->delete("salery","where  idno='".$x_value."' and month='".$_POST["month"]."'");
 
//     $saveAry=array(
//                 "idno"              =>  $x_value,
//                 "one_day_payment"   =>  $_POST["one_day_payment"][$x],
//                 "total_absent"      =>  $_POST["total_absent"][$x],
//                 "total_cl"          =>  $_POST["total_cl"][$x],
//                 "advance_payment"   =>  $_POST["advance_payment"][$x],
//                 "grass_total"       =>  $_POST["grasstotal"][$x],
//                 "month"             =>  $_POST["month"]
// 			);
//     $flgIn=$db->insertAry("salery",$saveAry);
// }

/*
if($flgIn>0)
{
?>
	echo "<script>window.location = 'print/?page_id=salery&action=print&month=<?php echo $_POST["month"] ?>';</script>"; 
<?php
}
*/

    
}

if(isset($_SESSION['msg']) && $_SESSION['msg']!="")
{
	?>
	<div class="alert alert-success">
	  <a class="close" data-dismiss="alert">×</a>
	  <i class="icon icon-thumbs-up-alt"></i> <b>Notice</b><?php echo $_SESSION['msg'] ?></i>
	</div>
	<?php
	unset($_SESSION["msg"]);
}
if(is_array($alert_err) && count($alert_err)>0)
{
	?>
	<div class="alert alert-error">
	  <a class="close" data-dismiss="alert">×</a>
	  <i class="icon icon-warning-sign"></i> <b>Notice</b> <?php echo $alert_err[0] ?></i>
	</div>
	<?php
}

	?>
	<div class="row-fluid"><div class="span12"><div class="top-bar">
    <h3><i class="icon-eye-open"></i> <?php echo ucwords($pgAct." ".$pgMod); ?></h3>
    <!-- <button type="button" style="float:right" onclick="printDiv('printDiv')" class="btn btn-danger">Print</button> !-->
    </div>
    <div class="well no-padding">
    <form method="post" style=" margin:20px">
    <label>Salary Month</label>
   
    <select class="span6" name="bmonth" id="bmonth">
     <?php
     $monthAry = ["April", "May", "June", "July", "August", "September", "October", "November", "December", "January", "February", "March"];
     $i = 0;
     foreach($monthAry as $m){$i++;
     ?>
         <option value="<?php echo $i; ?>" <?php if($_POST['bmonth'] == "$i")echo "selected"; ?> ><?php echo $m ?></option>
         <?php
     }
     /*
        for($m = 1;$m <= 12; $m++){ 
            $month =  date("F", mktime(0, 0, 0, $m));
            $selected="";
			if(isset($_POST["bmonth"]) &&  $_POST["bmonth"] == $m) $selected="selected";
			elseif($m == date("m", (time()))) $selected="selected"  ;
			
            echo "<option $selected value='$m'>$month</option>"; 
        }*/
     ?> 
    </select>
    <?php/*
    $years=explode("-",$_SESSION["admin"]["session"]);
    if(is_array($years) && count($years)>0){
        ?><select class="span6" name="byear" id="byear"><?php 
		$selected="";
        foreach($years as $y){
			if(isset($_POST["byear"]) && $_POST["byear"] == $y) $selected="selected";
            echo "<option $selected value='$y'>$y</option>"; 
        }
        ?></select><?php
    }*/
    ?>
    <label>Department</label>
    <select class="span6" name="department" id="department" onchange="getfaculty(this.value)">
		<option value=""> All</option>
		<?php 
			$class=$db->getRows("select * from department where school_id='".$_SESSION["admin"]["school_id"]."' ");
			foreach($class as $cla){
				?>
				<option <?php if($cla["name"]==$aryForm["department"])echo 'selected';?> value="<?php echo $cla["name"] ?>">
					<?php echo $cla["name"] ?>
                </option>
				<?php
			}
		?>
	</select>
    
    <div style="display:inline-block;width:30%" id="facultydiv">
      <select class="" name="teacher_id">
      <option value="">--Select Teacher--</option>
      <?php $staff = $db->getRows("select * from staff where session='".$_SESSION["admin"]["session"]."' and status=1 order by name");
            foreach($staff as $teacher){
                echo "<option value='$teacher[idno]'>$teacher[name]</option>";
                }
            ?>
        </select>
    </div>
    
    <button class="btn btn-default" type="submit">Search</button>
   </form>
<div id="printDiv">
	<?php
	$teacherid  = "";
	
	if(isset($_POST['teacher_id']) && trim($_POST["teacher_id"])!=""){
	    $teacherid = " and idno ='$_POST[teacher_id]' ";
	}
	
	$dept = "";
	if(isset($_POST['department']) && trim($_POST["department"])!=""){
	    $dept = " and department ='$_POST[department]' ";
	}

	$month = $_POST["bmonth"]; 
// 	$year=$_POST["byear"];

	if($month=="")$month=date("m", (time()));
 
    $years=explode("-",$_SESSION["admin"]["session"]);
	if($month > 9){
	    $year = $years[1];
	    if($_POST["bmonth"]!=""){
	        $month = $month-9;
	    }
	} else {
	    $year = $years[0];
	    if($_POST["bmonth"]!=""){
	        $month = $month+3;
	    }
	}

    // CL start
        $years1 = explode("-",$_SESSION["admin"]["session"]);

    	if($month < 4){
    	    $y = $years1[1];
    	} else {
    	    $y = $years1[0];
    	}

		$fdate  =   $y."-".$month."-"."01";
		$tdate  =   $y."-".$month."-"."31";
		$whereface = " (date between '$fdate' and '$tdate') ";
    // CL ends

    // Absent start
        $mn=date('m',strtotime($y."-".$month."-1"));

		$maxDays=date('t',strtotime($y."-".$mn."-1"));
		if(date('m')==$mn){
            $maxDays = date('d');
        }
    // Absent end


	echo "<input type='hidden' id='totalDay' value='".cal_days_in_month(CAL_GREGORIAN, $month, $year)."' />";

	$aryPgAct=array("src"=>"Payroll", "page_id"=>$pgMod,"action"=>"add");

    $sql="select * from staff where school_id='".$_SESSION["admin"]["school_id"]."' and session='".$_SESSION["admin"]["session"]."' $teacherid $dept and status=1 order by name";

	$aryList=$db->getRows($sql);

    $additioncomponents = $db->getRows("select * from salary_components where type='Addition' ");
    $deductioncomponents = $db->getRows("select * from salary_components where type='Deduction' ");

	if(is_array($aryList) && count($aryList)>0)
		{	$totpaybranch=0;
			?><hr style="clear:both">
            <h4>Teacher Salery for <?php echo date("M",strtotime($year."-".$month."-1"))." ".$year;?> <p style="float:right">Branch : <?php if($_POST["shift"]=="")echo "ALL"; else $db->getVal("select name from branch where id='".$_POST["shift"]."' and school_id='".$_SESSION["admin"]["school_id"]."'"); ?></p></h4>
		<form  method="post">
		    <div style="width:100%;overflow-x:scroll;">
			<table class="table">
				<thead>
					<tr>
						<th>S. No</th>
						<th>Name</th>
						<th>Account No.</th>
						<th>Basic salary</th>
                        <th>Components</th>
                        <th>OneDay Payment</th>
                        <th>Day Absent</th>
                        <th>Gross Total</th>
					</tr>
				</thead>
				<tbody>
				<?php foreach($aryList as $clist){ $i++; $ijk++;

                // find absent start
                $totalabsent = 0;
                
                for($i=1; $i<= $maxDays;$i++){ $day=date('D',strtotime($y."-".$mn."-".$i));
                    $msg = "A";
                        $chkHoli=$db->getVal("select status from staff_holiday where school_id='".$_SESSION["admin"]["school_id"]."' and date='".$y."-".$mn."-".$i."' and teacher='".$clist['idno']."'");

                        $chkAtt=$db->getVal("SELECT id FROM attendance_new WHERE cast(timestamp as date) = '".$y."-".$mn."-".$i."' and teacher_id='".$clist["idno"]."' and att_type='IN' ");

    					if(strtolower($day)=="sun") {$msg="S";}
    					elseif($chkHoli===1) {$msg="H";}
    					elseif($chkAtt > 0) {$msg="P";}

                        if($msg=="A"){
    					    $totalabsent+=1;
    					}
                }
                // find absent end

                $totalcl = $db->getVal("SELECT COUNT(id) FROM teacher_leave WHERE teacher_id='$clist[idno]' and leave_status='1' AND $whereface AND session='".$_SESSION["admin"]["session"]."' ");

                $paydetail = $db->getRow("select * from salery where month ='".$month."' and idno='".$clist['idno']."' and session='".$_SESSION["admin"]["session"]."' ");

                $detail = json_decode($paydetail['detail'], true);
                
                $recordfound = 0;
                if(count($paydetail) > 1){
                    $recordfound = 1;
                }
                
				?>
					<tr class="grade<?php if($i%2==0)echo "C";else "U";?>">
						<td><?php echo $ijk; ?><script>$(document).ready(function(){getFacultySaleryTotal('<?php echo $clist['idno'] ?>','<?php echo $recordfound; ?>')})</script></td>
						<td><?php echo $clist["name"]; ?></td>
						<td><?php echo $clist["accountno"] ?></td>

						<td><input class="py" type="text" readonly="readonly" data-id="<?php echo $clist['idno'] ?>" name="basic_salary<?php echo $clist['idno'] ?>" id="SchoolSalary<?php echo $clist['idno'] ?>" value="<?php echo $clist["salery"] ?>" /></td>

                        <td><label>Addition Components</label>
                            <?php $k=0;
                                $totalcomp = array();
                                foreach($additioncomponents as $comp){$k++; 
                                $totalcomp[]=$comp['id'];

                                $val = "";

                                foreach($detail as $key => $value)
                                {
                                    if($comp['id'] == $key)
                                    {
                                        $val = $value;
                                    }
                                }

                                ?>
                                    <div style='display:inline-block;padding:2px;'>
                                        <?php echo $comp['sname']." - ".$comp['calculate_mode'][0]; ?><br>
                                        <input data-type="Addition" data-mode="<?php echo $comp['calculate_mode']; ?>" name="<?php echo $clist['idno']."_".$comp['id']; ?>" id="<?php echo $clist['idno']."_".$comp['id']; ?>" class='py' onkeyup="addup('<?php echo $clist['idno']; ?>')" value="<?php echo $val; ?>" type='text' style='width:80px;'>
                                    </div> 
                                    <?php
                                    if($k==4)echo "<br>";
                                }
                            ?>

                            <label>Deduction Components</label>
                            <?php
                                foreach($deductioncomponents as $comp){ $k++;
                                $totalcomp[]=$comp['id'];
                                
                                $val = "";

                                foreach($detail as $key => $value)
                                {
                                    if($comp['id'] == $key)
                                    {
                                        $val = $value;
                                    }
                                }
                                ?>
                                    <div style='display:inline-block;padding:2px;'>
                                        <?php echo $comp['sname']." - ".$comp['calculate_mode'][0]; ?><br>
                                        <input data-type="Deduction" data-mode="<?php echo $comp['calculate_mode']; ?>" name="<?php echo $clist['idno']."_".$comp['id']; ?>" id="<?php echo $clist['idno']."_".$comp['id']; ?>" class='py' onkeyup="addup('<?php echo $clist['idno']; ?>')" value="<?php echo $val; ?>" type='text' style='width:80px;'>
                                    </div>
                                    <?php
                                    if($k==4)echo "<br>";
                                }
                            ?>
                        </td>
                        <td><input class="py" type="text" name="one_day_payment[]"  readonly="readonly" id="OneDayPayment<?php echo $clist['idno'] ?>" value="<?php echo $paydetail["one_day_payment"] ?>" /></td>
                        <td>
                            <input class="py" type="text" name="total_absent[]"  id="DayAbsent<?php echo $clist['idno'] ?>"  value="<?php if($paydetail["total_absent"]==""){echo $totalabsent; } else {echo $paydetail['total_absent']; } ?>" onkeyup="addup('<?php echo $clist['idno']; ?>')" style="width:50px;"/>
                            <br><br><br>
                            <p>
                                CL
                                <input class="py" type="text" name="cl[]" id="cl<?php echo $clist['idno']; ?>" value="<?php if($paydetail['cl']==0 || $paydetail['cl'] == ""){echo $totalcl; } else {echo $paydetail['cl']; } ?>" onkeyup="addup('<?php echo $clist['idno']; ?>')" />
                            </p>
                        </td>
                        <td><input class="py" name="grasstotal[]" type="text" data-id="<?php echo $clist['idno'] ?>" readonly="readonly" id="GrossTotal<?php echo $clist['idno'] ?>"  value="<?php echo $paydetail["gross_total"] ?>" />

                            <input class="py" name="idno[]" type="hidden" readonly="readonly" data-id="<?php echo $clist['idno'] ?>" id="GrossTotal<?php echo $clist['idno'] ?>"  value="<?php echo $clist['idno']; ?>" />
                            <input class="py" name="month" type="hidden" readonly="readonly" data-id="<?php echo $clist['idno'] ?>" value="<?php echo $month ?>" />
                            <br><br>

                            <?php //$recordfound = 0;
                            if(count($paydetail) > 1){
                                // $recordfound = 1;
                                	echo "<a href='print/?page_id=salery&idno=$clist[idno]&month=$month&session=".$_SESSION["admin"]["session"]."' target='_blank' class='btn btn-info' style='width:50px;font-size:12px;'>Print</a>";
                            }
                            ?>
                        </td>
					</tr>
				<?php } ?>
				<input name="totalcomponents[]" type="hidden" readonly="readonly" value="<?php echo json_encode($totalcomp); ?>" />
				</tbody>
			</table>
            </div>
			  <center><button type="submit" id="saveme" name="saveme"  class="btn btn-primary"> Save & Print</button></center>
			</form>
			<?php
		}
		else{
			?>
			<div class="alert alert-info">
			  <a class="close" data-dismiss="alert">×</a>
			  <i class="icon icon-warning-sign"></i> <b>Notice</b> Record not found </i>
			</div>
			<?php
		}
	?>
	<style>
input.py {
  width: 60px;
}
</style>
<script>
    function paynow(id){
    
    	$("#btn"+id).hide();
    
    	$.post( "Faculty/ajax.php", { 	type: "paybybranch" ,
    							faculty_id      :   id,
    							totalDays       :   $("#totalDay").val(),
    							SchoolSalary    :   $("#SchoolSalary"+id).val(),
    							OneDayPayment   :   $("#OneDayPayment"+id).val(),
    							Diffrence       :   $("#Diffrence"+id).val(),
    							DayAbsent       :   $("#DayAbsent"+id).val(),
    							CLAmount        :   $("#CLAmount"+id).val(),
    							AdvancePayment  :   $("#AdvancePayment"+id).val(),
    							GrossTotal      :   $("#GrossTotal"+id).val(),
    							dmonth          :   '<?php echo $month?>',
    							dyear           :   '<?php echo $year?>',
    
    							medical         :   $("#medicalallowance"+id).val(),
                                transport       :   $("#transportallowance"+id).val(),
                                pfemployer      :   $("#pfEmployer"+id).val(),
                                gradepay        :   $("#gradepay"+id).val(),
                                dearnessallowance:  $("#dearnessallowance"+id).val(),
                                specialallowance:   $("#specialallowance"+id).val(),
                                hrallowance     :   $("#hrallowance"+id).val(),
    
                                uniform         :   $("#uniform"+id).val(),
                                tds             :   $("#tds"+id).val(),
                                pf              :   $("#pf"+id).val(),
                                esi             :   $("#esi"+id).val(),
                                houserent       :   $("#houserent"+id).val(),
                                electricitybill :   $("#electricitybill"+id).val()
    
    						} , function( data ) {
    
    		alert("Salery pay successfully");
    	});
    }

    function deletepaynow(id,payid,tid){
    	$("#btn"+id).hide();
    	$.post( "Faculty/ajax.php", { 	type: "deletepaybybranch" ,
    									payid:payid,
    									tid:tid
    								} , function( data ) {
    		alert("Salery removed successfully")	
    		$("#DayAbsent"+id).val(0);
    		$("#CLAmount"+id).val(0);
    		$("#AdvancePayment"+id).val(0);
    		getFacultySaleryTotal(id);
    	});
    }

    function getfaculty(id){
    	$.post( "Payroll/ajax.php", {type: "departmentfaculty", department:id	}, 
    		function( data ) {
    	    document.getElementById("facultydiv").innerHTML = data;
    	});
    
    }

    function getFacultySaleryTotal(id, record=0){
// alert(id);
        // var totalDays=$("#totalDay").val();
        var totalDays=26;

        var SchoolSalary = 0;
    	    SchoolSalary=$("#SchoolSalary"+id).val();

        var OneDayPayment = 0;
        if(SchoolSalary > 26){
            // alert(SchoolSalary)
            OneDayPayment=SchoolSalary/totalDays;
        } 
    
        var nu = OneDayPayment.toFixed(2);
        // alert(SchoolSalary);

        var cl = $("#cl"+id).val();
        var cltotal = nu*cl;

        var absentdays = $("#DayAbsent"+id).val();
        var leavetotal = nu*absentdays;

        var gross = parseFloat(SchoolSalary)+parseFloat(cltotal)-parseFloat(leavetotal);

        // var record = '<?php echo $recordfound; ?>';
        // console.log(record);
        // alert(record);
        if(record != 1){
            if(isNaN(gross) || gross == ""){
                gross = 0;
            }
            $("#GrossTotal"+id).val(gross.toFixed(2));
            $("#OneDayPayment"+id).val(nu);
        }

    }
    

var totalcomponents = '<?php echo json_encode($totalcomp); ?>';
var temp1 = JSON.parse(totalcomponents);

function addup(tid){

    var basic = $("#SchoolSalary"+tid).val();
    var total = basic;
    var comp  = 0;
    var absenttotal = 0;


    var temptotal = basic;
    
    var additioncomp = 0;

    for(var i = 0; i<temp1.length; i++){
        var temp = $("#"+tid+'_'+temp1[i]).val();

        if(isNaN(temp) || temp == ""){
            temp = 0;
        }

        var type = $("#"+tid+'_'+temp1[i]).attr("data-type");
        var mode = $("#"+tid+'_'+temp1[i]).attr("data-mode");

        if(type == "Addition"){ 
            if(mode == "Amount"){
                // temptotal = parseInt(temptotal)+parseInt(temp);
                additioncomp = parseInt(additioncomp)+parseInt(temp);
            }
            if(mode == "Percent"){
                var per = (parseInt(temp)*parseInt(basic))/100;
                additioncomp = parseInt(additioncomp)+parseInt(per);
                // temptotal = parseInt(temptotal)+parseInt(per);
            }
        }
        if(type == "Deduction"){
            if(mode == "Amount"){
                temptotal = parseInt(temptotal)-parseInt(temp);
            }
            if(mode == "Percent"){
                var per = (parseInt(temp)*parseInt(basic))/100;
                temptotal = parseInt(temptotal)-parseInt(per); 
            }
        }
    }
// alert(additioncomp);
    $("#GrossTotal"+tid).val(temptotal);

    // var onedaypayment = $("#OneDayPayment"+tid).val();
    var onedaypayment = (parseFloat(additioncomp)+parseFloat(basic))/26;

    onedaypayment = parseFloat(onedaypayment);
    $("#OneDayPayment"+tid).val(onedaypayment.toFixed(2))

    var absent  =   $("#DayAbsent"+tid).val();
    if(isNaN(absent) || absent == ""){
 
    } else {
        absenttotal = parseFloat(onedaypayment * absent);
    }
// alert(onedaypayment);
    var cl = $("#cl"+tid).val();
    var cltotal = (cl*onedaypayment).toFixed(2);

    total = parseFloat(additioncomp) + parseFloat(temptotal) + parseFloat(cltotal) - parseFloat(absenttotal);

    $("#GrossTotal"+tid).val(total.toFixed(2));

}

</script>
</div>
	</div></div></div>
	<?php

?>
