<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],
                    "epf"               =>  $_POST["epf"][$j], 
                    "esic"              =>  $_POST["esic"][$j],
                    "gross_total"       =>  $_POST["grasstotal"][$j],
                    "latedays"          =>  $_POST["latedays"][$j],
                    "latededuction"     =>  $_POST["latededuction"][$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],
                    "epf"               =>  $_POST["epf"][$j],
                    "esic"              =>  $_POST["esic"][$j],
                    "gross_total"       =>  $_POST["grasstotal"][$j],
                    "latedays"          =>  $_POST["latedays"][$j],
                    "latededuction"     =>  $_POST["latededuction"][$j],
                    "month"             =>  $_POST["month"],
                    "session"           =>  $_SESSION["admin"]["session"],
                    "school_id"         =>  1,
                    "added_by"          =>  $_SESSION["admin"]["uid"]
			    );
            $flgIn=$db->insertAry("salery",$saveAry);
        }
        $j++;
    }


}

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="get" style=" margin:20px">
        <input type="hidden" name="src" value="Payroll" />
        <input type="hidden" name="page_id" value="<?php echo $pgMod; ?>" />

        	<div class="row-fluid">
        <!--<div class="span12">-->
            <div class="well no-padding">
                <div class="controls controls-row">

            <div class="control-group span3">
                <label class="control-label">Salary Month</label>
                <div class="controls">
                    <select class="input-block-level" name="bmonth" id="bmonth">
                    <?php
                    	$month = $_GET["bmonth"];
                    	if($month==""){
                    	    $month=date("m");
                    	}
            
                        $monthAry = ["4"=>"April", "5"=>"May", "6"=> "June","7"=> "July","8"=> "August","9"=> "September","10"=> "October", "11"=>"November", "12"=>"December",
                        "1"=>"January", "2"=>"February", "3"=>"March"];
                        $i = 0;
                        foreach($monthAry as $key => $val){$i++;
                    ?>
                        <option value="<?php echo $key; ?>" <?php if($month == $key)echo "selected"; ?> ><?php echo $val ?></option>
                        <?php
                        }
                    ?>
                </select>
                </div>
            </div>

            <div class="control-group span3">
                <label class="control-label">Year</label>
                <div class="controls">
                    <select class="input-block-level" name="year" id="Year">
                    <?php
                    	$year = $_GET["year"];
                    	if($year==""){
                    	    $year=date("Y");
                    	}

                        $yearAry = ["2023", "2024", "2025", "2026"];
                        $i = 0;
                        foreach($yearAry as $key => $val){$i++;
                    ?>
                        <option value="<?php echo $key; ?>" <?php if($month == $key)echo "selected"; ?> ><?php echo $val ?></option>
                        <?php
                        }
                    ?>
                </select>
                </div>
            </div>

            <div class="control-group span3">
                <label class="control-label">Department</label>
                <div class="controls">
                    <select class="input-block-level" 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"]==$_GET["department"])echo 'selected';?> value="<?php echo $cla["name"] ?>">
            					<?php echo $cla["name"] ?>
                            </option>
            				<?php
            			}
            		?>
            	</select>
            	</div>
            </div>

            <div class="control-group span3">
                <label class="control-label">Teacher</label>
                <div class="controls" id="facultydiv">
                    <select class="input-block-level" name="teacher_id" id="teacher_id">
                      <option value="">--Select Teacher--</option>
                      <?php $staff = $db->getRows("select * from staff where school_id='".$_SESSION["admin"]["school_id"]."' and status=1 order by name");
                            foreach($staff as $teacher){
                                $selected = "";
                                if($teacher['idno']==$_GET['teacher_id']){
                                    $selected = "selected";
                                }
                                echo "<option value='$teacher[idno]' $selected>$teacher[name]</option>";
                            }
                            ?>
                        </select>
                </div>
            </div>

            <div style="width:100%;margin-top:50px;display:block;">
                <label class="btn btn-info" onclick="print()" style="float:right;margin-left:30px;">Print</label>
                <button class="btn btn-primary" type="submit" style="float:right;">Search</button>
                
            </div>

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

   </form>

<div id="printDiv">
	<?php
	$teacherid  = "";
	
	if(isset($_GET['teacher_id']) && trim($_GET["teacher_id"])!=""){
	    $teacherid = " and idno ='$_GET[teacher_id]' ";
	}
	
	$dept = "";
	if(isset($_GET['department']) && trim($_GET["department"])!=""){
	    $dept = " and department ='$_GET[department]' ";
	}

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

// 	if($month=="")$month=date("m", (time()));
 
    $years=explode("-",$_SESSION["admin"]["session"]);
	if($month < 4){
	    $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"));

        $salarydays = $db->getRow("select * from salary_days where session='".$_SESSION["admin"]["session"]."'  ");

        $totaldays = cal_days_in_month(CAL_GREGORIAN,$month,$y);

        if($salarydays['days_type']=="2"){ 
            $totaldays = $salarydays['days'];
        }
        
        if($salarydays['days_type']=="3"){
            $sundays=0;
            $total_days=cal_days_in_month(CAL_GREGORIAN, $month, $y);
            for($i=1;$i<=$total_days;$i++)
            if(date('N',strtotime($year.'-'.$month.'-'.$i))==7)
            $sundays++;
            $totaldays = $totaldays - $sundays;
        }

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

    $late = $db->getRow("select * from late_deduction where session='".$_SESSION["admin"]["session"]."' ");

	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";

    $sql="select * from staff where school_id='".$_SESSION["admin"]["school_id"]."' $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 Salary for <?php $monthname = date("F",strtotime($year."-".$month."-1")); echo $monthname." ".$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>1 Day Payment</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;
                $latedays = 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->getRow("SELECT * FROM attendance_new WHERE cast(timestamp as date) = '".$y."-".$mn."-".$i."' and teacher_id='".$clist["idno"]."' and (att_type='IN' or att_type='OD' or att_type='HF' or att_type='LV' ) ");

                        $chkAtt_time=$db->getRow("SELECT * FROM attendance_new WHERE cast(timestamp as date) = '".$y."-".$mn."-".$i."' and teacher_id='".$clist["idno"]."' ");

    					if(strtolower($day)=="sun") {$msg="S";}
    					elseif($chkHoli===1) {$msg="H";}
    					elseif($chkAtt['att_type']=="LV") {$msg="LV";}
    					elseif(count($chkAtt) > 1) {$msg="P";

    					 $att_time = $db->getRow("SELECT * FROM attendance_timing WHERE date = '".$y."-".$mn."-".$i."' and teacher='$clist[idno]' and session='".$_SESSION["admin"]["session"]."' ");
                            if(count($att_time)>1){
                                $attstart = strtotime("$att_time[date] $att_time[start_time]");
                                $att_in = strtotime($chkAtt_time['timestamp']);
                                if($att_in > $attstart){
                                    $latedays++;
                                }
                            }

                        }

                        if($msg=="A"){
    					    $totalabsent++;
    					}
                }
                // 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 style="border-bottom:solid 2px red;">
						<td><?php echo $ijk; ?><script>$(document).ready(function(){getFacultySaleryTotal('<?php echo $clist['idno'] ?>','<?php echo $recordfound; ?>')})</script></td>
						<td style="width:70px;"><?php echo $clist["name"]; ?><br>
						<?php echo $clist["accountno"] ?></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"] ?>"  style="width:50px;" /><br>
                            EPF<br>
                            <input class="py" type="text" name="epf[]" id="epf<?php echo $clist['idno']; ?>" value="<?php if($paydetail['epf']==0 || $paydetail['epf'] == ""){echo 0; } else {echo $paydetail['epf']; } ?>" style="width:50px;" readonly />
                            <input type="hidden" id="epfenabled<?php echo $clist['idno'] ?>" value="<?php echo $clist['epf']; ?>" />
                            </br>
                            ESIC<br>
                            <input class="py" type="text" name="esic[]" id="esic<?php echo $clist['idno']; ?>" value="<?php if($paydetail['esic']==0 || $paydetail['esic'] == ""){echo 0; } else {echo $paydetail['esic']; } ?>" style="width:50px;" readonly />
                            <input type="hidden" id="esicenabled<?php echo $clist['idno'] ?>" value="<?php echo $clist['esic']; ?>" />
                        </td>

                        <?php $leaveused = 0; $extraleaves = 0;
                            $leavedata =  $db->getRows("select * from teacher_leave where teacher_id='$clist[idno]' and leave_status='1' and session='".$_SESSION["admin"]["session"]."' ");
                            foreach($leavedata as $data){
                              if($data['leave_status']=="1" && $data["is_half_day"]=="0"){
                                  $leaveused++;
                              }
                              if($data['leave_status']=="1" && $data["is_half_day"]=="1"){
                                  $leaveused=$leaveused+0.5;
                              } 
                              if($data['leave_status']=="1" && $data["is_half_day"]=="2"){
                                //   $leaveused++;
                              }
                            }

                        $leavededuction = $db->getVal("select deduction_enable from leave_deduction where session='".$_SESSION["admin"]["session"]."' ");

                         $extraleaves = $clist['cl_count']-$leaveused;
                         if($extraleaves < 0 && $leavededuction == "1"){
                             $extraleaves = abs($extraleaves);
                         } else {
                             $extraleaves = 0;
                         }
                         ?>


						<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"] ?>" style="width:50px;" /><br>
                        CL <br>
                        <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']; ?>')" style="width:50px;" />
                        <br>
                        Day Absent<br>
                        <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;"/>
						</td>

                        <td><label>Addition Components 
                            <span style="color:red;">
                                <span style="color:black;border-left:solid 5px;"></span>&nbsp; Total Leave - <?php echo $total_leave = $clist['cl_count']; ?>
                                <span style="color:black;border-left:solid 5px;"></span>&nbsp; 
                                <span onclick="showLeaves(<?php echo $clist['idno']; ?>, <?php echo $total_leave; ?>)">Leave Used - <?php echo $leaveused; ?></span>
                                <span style="color:black;border-left:solid 5px;"></span>&nbsp; Total Left - <?php echo $total_leave-$leaveused; ?>
                                <span style="color:black;border-left:solid 5px;"></span>&nbsp; <?php echo $monthname; ?> Leave - 
                                <?php  $monthleave = 0;
                                        $monthlyleaves = $db->getRows("select * from teacher_leave where (date between '$fdate' and '$tdate') and teacher_id='$clist[idno]' and leave_status='1' and session='".$_SESSION["admin"]["session"]."' ");
                                        foreach($monthlyleaves as $data){
                                          if($data['leave_status']=="1" && $data["is_half_day"]=="0"){
                                              $monthleave++;
                                          }
                                          if($data['leave_status']=="1" && $data["is_half_day"]=="1"){
                                              $monthleave=$monthleave+0.5;
                                          }
                                          if($data['leave_status']=="1" && $data["is_half_day"]=="2"){
                                            //   $leaveused++;
                                          }
                                        }
                                        
                                        echo $monthleave;
                                ?>
                            </span>
                        </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:50px;'>
                                    </div> 
                                    <?php
                                    if($k==8)echo "<br>";
                                }

                            $latevalue = 0;
                            if($late['deduction_enable'] == "1"){
                                
                                if($late){
                                    $latevalue = $latedays/$late['late_days'];
                                }
                                
                            }

                            ?>

                            <label>Deduction Components
                            <span style="color:red;">
                                &emsp;&emsp;&emsp;&emsp;&emsp; Late Count - <?php echo $latedays; ?>
                            </span>
                            </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:50px;'>
                                    </div>
                                    <?php
                                    if($k==4)echo "<br>";
                                }
                            ?>
                        </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"] ?>" style="border:solid 2px red;" />

                            <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><br><br>";
                                	if($_GET['teacher_id']!=''){
                                	    echo "<a href='#' onclick='deletesalary($clist[idno], $month)' class='btn btn-danger' style='width:50px;font-size:12px;'>Delete</a>";
                                	}
                                }
                            ?>
                            <br>
                            Late Ded. <br>
                            <input class="py" type="text" name="latededuction[]" id="latededuction<?php echo $clist['idno']; ?>" value="<?php echo $paydetail['latededuction'];  ?>" onkeyup="addup('<?php echo $clist['idno']; ?>')" style="width:50px;" />
                            <input class="py" type="hidden" name="latedays[]" id="latedays<?php echo $clist['idno'] ?>"  value="<?php echo floor($latevalue); ?>" />

                        </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>
			      <?php if($_GET['teacher_id']==""){ ?>
                  <a class="btn btn-danger" onclick="deleteall(<?php echo $month ?>)"> Delete All</a>
                  <?php } ?>
			  </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>
<style>
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 10000; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  margin-left:0px;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 50%;
}

/* The Close Button */
.modal-header .close1 {
  color: white !important;
  float: right;
  font-size: 28px;
  font-weight: bold;
  z-index:10;
  margin-top:5px;
  background:crimson;
  width:25px;
  height:25px;
  border-radius:50%;
  padding:8px 0px 0px 8px;
}

.close1:hover,
.close1:focus {
  color: white;
  text-decoration: none;
  cursor: pointer;
}
.modal-header {
  padding: 0px 16px;
  background-color: #3B5999;
  color: white;
  margin:-20px;
  margin-top:-30px;
}
.modal-header h4 {
    color:white;
}
.modal-body {
    padding: 2px;
    width:100%;
}
</style>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">

    <div class="modal-header">
          <span class="close1" onclick="closeModal()">&times;</span>
          <h4>Total Leaves Used</h4>
    </div>
    <br>
    <div class="modal-body">
	    <br>
	    <h4>Total Leaves - <span id="totalleaves"></span></h4>
	    <table class="table" border="1">
	        <thead>
	            <tr>
	                <th>S.No.</th>
	                <th>Date</th>
	                <th>Leave Type</th>
	                <th>No. of Days</th>
	            </tr>
	        </thead>
	        <tbody id="leavesused">
	        </tbody>
	    </table>
	    <br>
    </div>

  </div>

</div>


<script> 

    function showLeaves(idno,totalleave){
    	$.post("Payroll/ajax.php", { type: "get_leaves_used" ,idno:idno, total_leave:totalleave } , function( data ) {
    	    $("#leavesused").html(data);
    	});
        $("#totalleaves").html(totalleave);    	
        var modal = document.getElementById("myModal");
        modal.style.display = "block";
    }

    function closeModal(){
        var modal = document.getElementById("myModal");
        modal.style.display = "none";
    }

    window.onclick = function(event) {
        var modal = document.getElementById("myModal");
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

    function deleteall(month){
        var r = confirm("Do you really want to delete all record? ");
        if (r == true) {
        	$.post("Payroll/ajax.php", { type: "delete_all_salary" ,month:month } , function( data ) {
        		alert('Deleted Successfully.');
        		location.reload();
        	});
        }
    }
    
    function deletesalary(idno, month){
        var r = confirm("Do you really want to delete this record? ");
        if (r == true) {
        	$.post("Payroll/ajax.php", { type: "delete_salary" ,month:month, idno:idno } , function( data ) {
        		alert('Deleted Successfully.');
        		location.reload();
        	});
        }

    }

    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=<?php echo $totaldays ?>;

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

        var OneDayPayment = 0;
        if(SchoolSalary > <?php echo $totaldays ?>){
            // 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 tempepf = parseFloat(SchoolSalary)-parseFloat(leavetotal);
        
        var epf = 0;
        var epfenabled = $("#epfenabled"+id).val();

        if(epfenabled == 1){
            epf = Math.round(((parseFloat(tempepf)*12)/100));
            
            if(epf > 1800){epf = 1800;}
        }

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

        if(esicenabled == 1 && parseFloat(SchoolSalary)<21000){
            esic = Math.ceil(((parseFloat(SchoolSalary)*0.75)/100));
        }

        var gross = parseFloat(SchoolSalary)+parseFloat(cltotal)-parseFloat(leavetotal)-parseFloat(epf)-parseFloat(esic);
        
        // var record = '<?php echo $recordfound; ?>';
        // console.log(record);
        // alert(record);
        if(record != 1){
            if(isNaN(gross) || gross == ""){
                gross = 0;
            }
            $("#GrossTotal"+id).val(Math.round(gross));
            $("#OneDayPayment"+id).val(nu);
            $("#epf"+id).val(epf);
            $("#esic"+id).val(esic);
            
            addup(id);
        }

    }
    

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");
        var compname = $("#"+tid+'_'+temp1[i]).attr("data-name");

        if(type == "Addition"){ 
            if(mode == "Amount"){
                // temptotal = parseInt(temptotal)+parseInt(temp);
                additioncomp = parseFloat(additioncomp)+parseFloat(temp);
            }
            if(mode == "Percent"){
                var per = (parseFloat(temp)*parseFloat(basic))/100;
                additioncomp = parseFloat(additioncomp)+parseFloat(per);
                // temptotal = parseInt(temptotal)+parseInt(per);
            }
        }
        if(type == "Deduction"){
            if(mode == "Amount"){
                temptotal = parseFloat(temptotal)-parseFloat(temp);
            }
            if(mode == "Percent"){
                if(compname == "EPF" && temptotal > 15000 && temp > 0){
                    temptotal = parseFloat(temptotal)-parseFloat(1800); 
                } else if(compname == "ESIC" && temptotal > 21000 ){
                    // temptotal = parseFloat(temptotal)-parseFloat(1800); 
                } else {
                    var per = (parseFloat(temp)*parseFloat(basic))/100;
                    temptotal = parseFloat(temptotal)-parseFloat(per); 
                }
            }
        }
    }

    $("#GrossTotal"+tid).val(temptotal);

    // var onedaypayment = $("#OneDayPayment"+tid).val();
    var onedaypayment = (parseFloat(additioncomp)+parseFloat(basic))/<?php echo $totaldays ?>;

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

    var absent  =   $("#DayAbsent"+tid).val();
    if(isNaN(absent) || absent == ""){

    } else {
        absenttotal = parseFloat(onedaypayment * absent);
    }

    var cl = $("#cl"+tid).val();
    var cltotal = (cl*onedaypayment).toFixed(2);

    var tempabsentamt = (parseFloat(basic)/<?php echo $totaldays ?>)*parseFloat(absent);

    var tempepf = parseFloat(basic)-parseFloat(tempabsentamt);

    var epf = 0;
    var epfenabled = $("#epfenabled"+tid).val();

    if(epfenabled == 1){
        epf = Math.round(((parseFloat(tempepf)*12)/100));
        if(epf > 1800){epf = 1800;}
    }

    var tempesic = parseFloat(basic)+parseFloat(additioncomp)-parseFloat(absenttotal);

    var esic = 0;
    var esicenabled = $("#esicenabled"+tid).val();

    if(esicenabled == 1 && parseFloat(tempesic)<21000){
        esic = Math.ceil(((parseFloat(tempesic)*0.75)/100));
    }
    
    total = parseFloat(additioncomp) + parseFloat(temptotal) + parseFloat(cltotal) - parseFloat(absenttotal) - parseFloat(epf) - parseFloat(esic) - parseFloat(latededuction) ;

    $("#epf"+tid).val(epf);
    $("#esic"+tid).val(esic);
    $("#GrossTotal"+tid).val(Math.round(total));

}

function print(){
    var month = $("#bmonth").val();
    
//     if(month > 9){
// 	        month = parseInt(month)-9;
// 	} else {
// 	        month = parseInt(month)+3;
// 	}
    
    var department = $("#department").val();
    var tid = $("#teacher_id").val();

    var session = '<?php echo $_SESSION["admin"]["session"] ?>';

    window.open('print/?page_id=salery&idno='+tid+'&month='+month+'&department='+department+'&session='+session, '_blank');
    // window.location = 'print/?page_id=salery&idno='+tid+'&month='+month+'&department='+department+'&session='+session;
    // window.location = 'print/?page_id=salery&action=print&month=<?php echo $_POST["month"] ?>';
}

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

?>
