<?php 

include('../dbconnect.php');
ob_start();
session_start();

if(!isset($_SESSION['user'])) {
 header("Location: ../index.php");
 exit;
}
include('uppernav.php'); 
$empid = $_SESSION['user'];


$datefiled = date('m/d/Y');


$empdetails = "SELECT gender FROM empinfo WHERE empid='$empid'";
$empres = mysqli_query($conn, $empdetails);
$emprow = mysqli_fetch_assoc($empres);
$gender = $emprow['gender'];
$duration = array();


$ptosql = "SELECT * FROM pto WHERE empid='$empid' AND name='Paid Time Off'";
$ptores = mysqli_query($conn, $ptosql);
$ptorow = mysqli_fetch_assoc($ptores);
$Apto = $ptorow['availablepto'];



if(isset($_POST['submitleave'])){
  
$leavetype = $_POST['leavetype'];
$leavename = $_POST['leavename'];
 
$datefrom = $_POST['from'];
$dateto = $_POST['to'];

$days = $_POST['days'];
$datefiled = $_POST['datefiled'];
$filed = date('Y-m-d', strtotime($datefiled));
$notes = $_POST['noted'];




  for($a = 0; $a < count($leavetype); $a++){

    $existdate = "SELECT * FROM `leave` WHERE empid='$empid' AND datefrom='$datefrom[$a]' OR dateto='$dateto[$a]' AND `status` IN ('0','1','2','3')";
    $existsql = mysqli_query($conn, $existdate);

    $duration[] = array_sum($days);

    $ptosql  ="SELECT * FROM pto WHERE empid='$empid' AND name='$leavetype[$a]'";
    $query = mysqli_query($conn, $ptosql);
    $row = mysqli_fetch_assoc($query);
   $availablepto = $row['availablepto'];
   $ptoid = $row['id'];
   $usedpto = $row['usedpto'];

   


   if($leavetype[$a] == "LWOP"){
        $d = 0;



   }else{

    $d = $duration[0];
   }


    

  

    if(mysqli_num_rows($existsql) > 0){

      $alert ='<div class="alert alert-danger" role="alert"> Given leave date is not available </div>';

    }else if($d > $availablepto){

        

        $alert ='<div class="alert alert-danger" role="alert">
        You dont have enough leave
        </div>';
        break;
        
    }

    else{

      
    if($leavetype[$a] == "LWOP"){

      
      if($position == 'Team Head'){
    
      $idl = $empid.$datefrom[$a].$dateto[$a].$time;

        
        
        $submitleave = "INSERT INTO `leave`(`idl`,`type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`,`name`) 
        VALUES ('$idl','LWOP','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','1','$empid','$leavename[$a]')";

              if(mysqli_query($conn, $submitleave)){

                if($datefrom[$a] != $dateto[$a]){

                    $begin = new DateTime($datefrom[$a]);
                    $end = new DateTime($dateto[$a]);
                    $end = $end->modify( '+1 day' ); 
        
                    $interval = new DateInterval('P1D');
                    $daterange = new DatePeriod($begin, $interval ,$end);
        
                    $range = array();
        
                    foreach($daterange as $dates){         
        
                    $range[] = $dates->format("Y-m-d");
        
                    }
                    for($a=0; $a < count($range); $a++){
        
                        $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";
    
                        if(mysqli_query($conn, $schedupdate)){
                       
    
                 
                        }
        
                    }
        
        
                  }
                  else{
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom[$a]'";
    
                    if(mysqli_query($conn, $schedupdate)){


    
                 
                    }
    
    
    
                  }

        
        $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
      //header('location: leave.php?alert='.$alert.''); 



      }
      else{
        echo mysqli_error($conn);
      }

     
        


      }else if($position == 'Director of Shared Service'){
         $idl = $empid.$datefrom[$a].$dateto[$a].$time;

        $submitleave = "INSERT INTO `leave`(  `idl`, `type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`,`name`) 
        VALUES ('$idl','LWOP','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','3','$empid','$leavename[$a]')";

            if(mysqli_query($conn, $submitleave)){
                if($datefrom[$a] != $dateto[$a]){

                    $begin = new DateTime($datefrom[$a]);
                    $end = new DateTime($dateto[$a]);
                    $end = $end->modify( '+1 day' ); 
        
                    $interval = new DateInterval('P1D');
                    $daterange = new DatePeriod($begin, $interval ,$end);
        
                    $range = array();
        
                    foreach($daterange as $dates){         
        
                    $range[] = $dates->format("Y-m-d");
        
                    }
                    for($a=0; $a < count($range); $a++){
        
                        $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";
    
                        if(mysqli_query($conn, $schedupdate)){
    
                 
                        }
        
                    }
        
        
                  }
                  else{
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom[$a]'";
    
                    if(mysqli_query($conn, $schedupdate)){
                 
    
                 
                    }
    
    
    
                  }

                    
                $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
            //header('location: leave.php?alert='.$alert.''); 



            }
            else{
                echo mysqli_error($conn);
            }

     

      } else if($position == 'Associate Director of Shared Service'){
      $idl = $empid.$datefrom[$a].$dateto[$a].$time;

        $submitleave = "INSERT INTO `leave`(`idl`, `type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`,`name`) 
        VALUES ('$idl','LWOP','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','2','$empid','$leavename[$a]')";

            if(mysqli_query($conn, $submitleave)){

                if($datefrom[$a] != $dateto[$a]){

                    $begin = new DateTime($datefrom[$a]);
                    $end = new DateTime($dateto[$a]);
                    $end = $end->modify( '+1 day' ); 
        
                    $interval = new DateInterval('P1D');
                    $daterange = new DatePeriod($begin, $interval ,$end);
        
                    $range = array();
        
                    foreach($daterange as $dates){         
        
                    $range[] = $dates->format("Y-m-d");
        
                    }
                    for($a=0; $a < count($range); $a++){
        
                        $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";
    
                        if(mysqli_query($conn, $schedupdate)){
    
                 
                        }
        
                    }
        
        
                  }
                  else{
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom[$a]'";
    
                    if(mysqli_query($conn, $schedupdate)){
                 
    
                 
                    }
    
    
    
                  }

                    
                $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
            //header('location: leave.php?alert='.$alert.''); 



            }
            else{
                echo mysqli_error($conn);
            }

     

      }
      else{
          $idl = $empid.$datefrom[$a].$dateto[$a].$time;


        $submitleave = "INSERT INTO `leave`(`idl`,`type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`,`name`) 
        VALUES ('$idl','LWOP','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','0','$empid','$leavename[$a]')";

        if(mysqli_query($conn, $submitleave)){

            if($datefrom[$a] != $dateto[$a]){

                $begin = new DateTime($datefrom[$a]);
                $end = new DateTime($dateto[$a]);
                $end = $end->modify( '+1 day' ); 
    
                $interval = new DateInterval('P1D');
                $daterange = new DatePeriod($begin, $interval ,$end);
    
                $range = array();
    
                foreach($daterange as $dates){         
    
                $range[] = $dates->format("Y-m-d");
    
                }
                for($a=0; $a < count($range); $a++){
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";

                    if(mysqli_query($conn, $schedupdate)){

                       

             
                    }
    
                }
    
    
              }
              else{

                $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom[$a]'";

                if(mysqli_query($conn, $schedupdate)){


                   
         
             

             
                }



              }

                
            $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
        //header('location: leave.php?alert='.$alert.''); 



        }
        else{
            echo mysqli_error($conn);
        }

     


      }





    }

    else{


 
       $available = $availablepto - $days[$a] .'<br/>';
      $used = $usedpto + $days[$a];
      $leavetype[$a];

      
       if($postion == 'Team Head'){
          $idl = $empid.$datefrom[$a].$dateto[$a].$time;

        $submitleave = "INSERT INTO `leave`( `idl`,`type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`, `ptoid`, `name`) 
        VALUES ('$idl','$leavetype[$a]','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','1','$empid','$ptoid','$leavename[$a]')";

        $updatepto = "UPDATE pto SET availablepto='$available', usedpto='$used' WHERE id='$ptoid'";

        if(mysqli_query($conn, $submitleave) && mysqli_query($conn, $updatepto)){

            if($datefrom[$a] != $dateto[$a]){

                $begin = new DateTime($datefrom[$a]);
                $end = new DateTime($dateto[$a]);
                $end = $end->modify( '+1 day' ); 
    
                $interval = new DateInterval('P1D');
                $daterange = new DatePeriod($begin, $interval ,$end);
    
                $range = array();
    
                foreach($daterange as $dates){         
    
                $range[] = $dates->format("Y-m-d");
    
                }
                for($a=0; $a < count($range); $a++){
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";

                    if(mysqli_query($conn, $schedupdate)){

             
                    }
    
                }
    
    
              }
              else{

                $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom[$a]'";

                if(mysqli_query($conn, $schedupdate)){
             

             
                }



              }

        
            $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
          header('location: leave.php?alert='.$alert.''); 
    
    
          }
        
     
        


      }else if($position == 'Director of Shared Service'){
          $idl = $empid.$datefrom[$a].$dateto[$a].$time;

        $submitleave = "INSERT INTO `leave`( `idl`,`type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`, `ptoid`, `name`) 
        VALUES ('$idl','$leavetype[$a]','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','3','$empid','$ptoid','$leavename[$a]')";
        $updatepto = "UPDATE pto set availablepto='$available', usedpto='$used' WHERE id='$ptoid'";
        if(mysqli_query($conn, $submitleave) && mysqli_query($conn, $updatepto)){

            if($datefrom[$a] != $dateto[$a]){

                $begin = new DateTime($datefrom[$a]);
                $end = new DateTime($dateto[$a]);
                $end = $end->modify( '+1 day' ); 
    
                $interval = new DateInterval('P1D');
                $daterange = new DatePeriod($begin, $interval ,$end);
    
                $range = array();
    
                foreach($daterange as $dates){         
    
                $range[] = $dates->format("Y-m-d");
    
                }
                for($a=0; $a < count($range); $a++){
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";

                    if(mysqli_query($conn, $schedupdate)){

             
                    }
    
                }
    
    
              }
              else{

                $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom' OR date='$dateto' ";

                if(mysqli_query($conn, $schedupdate)){
             

             
                }



              }

        
            $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
          header('location: leave.php?alert='.$alert.''); 
    
    
          }
     

      } else if($position == 'Associate Director of Shared Service'){

          $idl = $empid.$datefrom[$a].$dateto[$a].$time;
          
        $submitleave = "INSERT INTO `leave`( `idl`,`type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`, `ptoid`, `name`) 
        VALUES ('$idl','$leavetype[$a]','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','2','$empid','$ptoid','$leavename[$a]')";
        $updatepto  = "UPDATE pto set availablepto='$available', usedpto='$used' WHERE id='$ptoid'";
        if(mysqli_query($conn, $submitleave) && mysqli_query($conn, $updatepto)){

            if($datefrom[$a] != $dateto[$a]){

                $begin = new DateTime($datefrom[$a]);
                $end = new DateTime($dateto[$a]);
                $end = $end->modify( '+1 day' ); 
    
                $interval = new DateInterval('P1D');
                $daterange = new DatePeriod($begin, $interval ,$end);
    
                $range = array();
    
                foreach($daterange as $dates){         
    
                $range[] = $dates->format("Y-m-d");
    
                }
                for($a=0; $a < count($range); $a++){
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";

                    if(mysqli_query($conn, $schedupdate)){

             
                    }
    
                }
    
    
              }
              else{

                $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom[$a]'";

                if(mysqli_query($conn, $schedupdate)){
             

             
                }



              }
            

        
            $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
          header('location: leave.php?alert='.$alert.''); 
    
    
          }
     

      }
      else{
       $idl = $empid.$datefrom[$a].$dateto[$a].$time;

        $submitleave = "INSERT INTO `leave`(`idl`, `type`, `datefiled`, `datefrom`, `dateto`, `duration`, `description`, `status`, `empid`, `ptoid`, `name`) 
        VALUES ('$idl','$leavetype[$a]','$filed','$datefrom[$a]','$dateto[$a]','$days[$a]','$notes[$a]','0','$empid','$ptoid','$leavename[$a]')";
        $updatepto = "UPDATE pto set availablepto='$available', usedpto='$used' WHERE id='$ptoid'";



        if(mysqli_query($conn, $submitleave) && mysqli_query($conn, $updatepto)){

            if($datefrom[$a] != $dateto[$a]){

                $begin = new DateTime($datefrom[$a]);
                $end = new DateTime($dateto[$a]);
                $end = $end->modify( '+1 day' ); 
    
                $interval = new DateInterval('P1D');
                $daterange = new DatePeriod($begin, $interval ,$end);
    
                $range = array();
    
                foreach($daterange as $dates){         
    
                $range[] = $dates->format("Y-m-d");
    
                }
                for($a=0; $a < count($range); $a++){
    
                    $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$range[$a]'";

                    if(mysqli_query($conn, $schedupdate)){

             
                    }
    
                }
    
    
              }
              else{

                $schedupdate = "UPDATE schedule SET idl='$idl' WHERE empid='$empid' AND date='$datefrom[$a]'";

                if(mysqli_query($conn, $schedupdate)){
             

             
                }



              }

              

        
            $alert ='<div class="alert alert-success" role="alert"> Leave successfully submitted </div>';
         // header('location: leave.php?alert='.$alert.''); 
    
    
          }
     


      }

 



     




    


  
  
       


    


    
  }
  



    }
    

    
  


    
}
}

?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Employee | Dashboard</title>

    <!-- Bootstrap core CSS-->
    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom fonts for this template-->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">

    <!-- Page level plugin CSS-->
    <link href="../vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet">

    <!-- Custom styles for this template-->
        <link href="../css/sb-admin.css" rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">

    <script>
    function deleteRow(obj) {
        var index = obj.parentNode.parentNode.rowIndex;
        var table = document.getElementById("Tabledata");
        table.deleteRow(index);
    }
    </script>


</head>

<body id="page-top">
	<div id="preloader">
   		<img src="../images/loaderS.gif" alt="processing..." height="150px" width="200px"/>
	</div>






    <!-- Sidebar -->

    <?php 
      $dashboard="active";
      include('sidebar.php');
       ?>
    <div id="content-wrapper">

        <div class="container-fluid">



            <!-- Breadcrumbs-->
            <ol class="breadcrumb">

                <li class="breadcrumb-item "><a href="leave.php">Leave</a></li>
                <li class="breadcrumb-item active">Add Leave</li>
            </ol>


            <form method="POST" id="theForm">

                <div class="row">
                    <div class="col-lg-12">
                        <?php echo $alert?>
                        <div class="alert alert-danger alert-dismissible fade show" id="datealert" role="alert" hidden>
                        Date to must be greater than Date from
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        </div>

                        <div class="alert alert-danger alert-dismissible fade show" id="datemonth" role="alert" hidden>
                        Date leave must be 1 month before filling date
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        </div>


                        <div class="alert alert-danger alert-dismissible fade show" id="APTOalert" role="alert" hidden>
                        You dont have enough PTO 
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        </div>


                        <h5>Add Leave</h5>
                        <hr>
                    </div>





                    <div class="col-lg-6">
                        <div class="row">



                            <div class="col-sm-6 form-group">
                                <label for="type" class="label-control"><b>Date Filed </b></label>
                                <input type="text" name="datefiled" id="datefiled" class="form-control"
                                    value="<?php echo $datefiled?>" readOnly required>

                            </div>
                            <div class="col-sm-6 form-group">
                                <label for="type" class="label-control"><b>Type </b></label>

                                <select name="type" id="type" class="form-control" required>
                                    <option disabled selected> Type </option>
                                    <option value="Paid Time Off"> Emergency Leave</option>
                                    <option value="Paid Time Off"> Sick Leave</option>
                                    <option value="Paid Time Off"> Vacation Leave</option>

                                    <option value="LWOP"> LWOP - Unpaid Leave</option>
                                    <?php
                            
                         
                                $sqltype ="SELECT * FROM pto WHERE empid='$empid' AND name !='Paid Time Off'";
                            
                      
                            $sqlquery = mysqli_query($conn, $sqltype);
                            while($typerow = mysqli_fetch_assoc($sqlquery)){
                                if($type == $typerow['id']){

                                    echo'<option value="'.$typerow['name'].'" selected>'.$typerow['name'].' Leave</option>';

                                }
                                else{

                                    echo'<option value="'.$typerow['name'].'">' .$typerow['name'].' Leave</option>';

                                }

                                

                            }
                            ?>
                                </select>

                            </div>
                            <div class="col-sm-12">
                              <div class="row">

                              <!-- HIDDEN FIELD-->
                              <input type="hidden" name="" id="APTO" value="<?php echo $Apto?>">


                                <div class="col-sm-12">
                                <label for="type" class="label-control"><b>Leave Date </b></label>
                                </div>




                                <div class="col-sm-4">
                         
                                <input type="date" name="from" id="from" class="form-control" 
                                    value="<?php echo $datefrom?>" onchange="daterangecheck()" required>
                                </div>
                                <div class="col-sm-4">
                                    <input type="date" name="to" id="to" class="form-control" 
                                    value="<?php echo $dateto?>"  onchange="daterangecheck()" required>
                                </div>

                                <div class="col-sm-3">
                                    <input type="number" name="duration" id="duration" class="form-control"
                                    value="<?php echo $datefrom?>" placeholder="Duration" required readonly>
                                </div>


                                <div class="col-sm-1">

                                <div class="custom-control custom-checkbox my-1 mr-sm-2">
                                  <input type="checkbox" class="custom-control-input" id="cb" onclick="daterangecheck()">
                                  <label class="custom-control-label" for="cb">0.5</label>
                                </div>

                                </div>


                                
                              </div>
                              








                            </div>
                            <div class="col-sm-12 form-group">
                            <br>
                                <label for="type" class="label-control"><b>Reason </b></label>
                                <textarea name="notes" id="notes" cols="30" rows="10" class="form-control"
                                    placeholder="Reason" required><?php echo $notes?></textarea>



                            </div>

                            <div class="col-sm-12 form-group">

                                <span class="pull-right"><button type="button" class="btn btn-primary" id="add"
                                        onclick="addRow()"><i class="fas fa-plus"></i> Add </button></span>

                            </div>



                        </div>

                    </div>
                    <div class="col-lg-6">

                        <table class="table" id="Tabledata">
                            <thead class="thead-dark">
                                <tr>
                                    <th>Type</th>
                                    <th>Leave Date</th>
                                    <th>Duration</th>

                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>

                        </table>
                        <p></p>



                    </div>
                    <div class="col-sm-12 form-group">

                        <span class="pull-right"><button type="button" class="btn btn-success"  id="submitleave" name="dup"><i class="fas fa-check"></i> Submit
                            </button></span>

                    </div>

                </div>

                <div class="modal fade" id="leavemodal" tabindex="-1" role="dialog"
                    aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLongTitle">Confirm Leave</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                Are you sure you to submit file a leave?
                            </div>
                            <div class="modal-footer">
                                <button type="submit" class="btn btn-success" name="submitleave"><i
                                        class="fas fa-check"></i> Yes</button>
                                <button type="button" class="btn btn-danger" data-dismiss="modal"><i
                                        class="fas fa-close"></i> No</button>
                            </div>
                        </div>
                    </div>
                </div>


                <div class="modal fade" id="dupmodal" tabindex="-1" role="dialog"
                    aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLongTitle"><i class="fa fa-warning"> </i> Error</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                Duplicate Leave Date
                            </div>
                            <div class="modal-footer">

                                <button type="button" class="btn btn-danger" data-dismiss="modal"><i
                                        class="fas fa-close"></i> Close</button>
                            </div>
                        </div>
                    </div>
                </div>

            </form>

            <script>
            function daterangecheck() {

                var from = document.getElementById('from').value;
                var to = document.getElementById('to').value;
                var cb = document.getElementById('cb').value;
                var APTO = document.getElementById('APTO').value;  
                var du = document.getElementById('duration');
                var leavetype = document.getElementById('type').value;

          

                var datefrom = new Date(from);
                var dateto = new Date(to);

                var today = new Date().toISOString().split('T')[0];
                
                var startDate = Date.parse(from);
                var endDate = Date.parse(to);
                var timeDiff = endDate - startDate;
                
                daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24)+1);

                
                if(document.getElementById("cb").checked == true){
                  du.value = daysDiff - 0.5;

                }
                else{
                  du.value = daysDiff;
                }






                if (datefrom > dateto) {

           

                    document.getElementById('datealert').hidden = false;
                    document.getElementById('add').disabled = true;

                    

                } 
         
                else {

                document.getElementById('datealert').hidden = true;
                document.getElementById('add').disabled = false;



             


                }

                if(leavetype == 'Paid Time Off'){


                    if(APTO < du.value){
                    
                    document.getElementById('add').disabled = true;
                    document.getElementById('APTOalert').hidden = false;


                    }
                    else {

                    document.getElementById('APTOalert').hidden = true;
                    document.getElementById('add').disabled = false;

                    }


                }


                ///1month duration 

              




               
/*                 var datetoday = Date.parse(today);
                var monthdays =  startDate - datetoday;
                daymonth = Math.floor(monthdays / (1000 * 60 * 60 * 24));

             

                
                if(daymonth < 29){
                  document.getElementById('add').disabled = true;
                  document.getElementById('datemonth').hidden = false;
                }
                else{
                  document.getElementById('add').disabled = false;
                  document.getElementById('datemonth').hidden = true;

                }


                
 */


         


                
              
                






            
 


            }
            </script>



            <!-- Icon Cards-->

            <!-- /.container-fluid -->

            <!-- Sticky Footer -->
            <!--  -->

        </div>
        <!-- /.content-wrapper -->

    </div>
    <!-- /#wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="login.html">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Page level plugin JavaScript-->
    <script src="../vendor/chart.js/Chart.min.js"></script>
    <script src="../vendor/datatables/jquery.dataTables.js"></script>
    <script src="../vendor/datatables/dataTables.bootstrap4.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="../js/sb-admin.min.js"></script>

    <!-- Demo scripts for this page-->
    <script src="../js/demo/datatables-demo.js"></script>
    <script src="../js/demo/chart-area-demo.js"></script>
    <script>
    function checkDuplicates() {
        // get all input elements
        var $elems = $('.dateleave');

        // we store the inputs value inside this array
        var values = [];
        // return this
        var isDuplicated = false;
        // loop through elements
        $elems.each(function() {
            //If value is empty then move to the next iteration.
            if (!this.value) return true;
            //If the stored array has this value, break from the each method
            if (values.indexOf(this.value) !== -1) {
                isDuplicated = true;
                return false;
            }
            // store the value
            values.push(this.value);
        });

        return isDuplicated;
    }
    $('button[name=dup]').on('click', function(e) {
        e.preventDefault();
        if (checkDuplicates())
        $('#dupmodal').modal('show');
            
            

            

 
   
        else $('#leavemodal').modal('show');
    })

    function addRow() {


        var form = document.getElementById('theForm');
        var errors = 'NULL';

        for (var i = 0; i < form.elements.length; i++) {

            if (form.elements[i].value === '' && form.elements[i].hasAttribute('required')) {
                errors = 'yes';

                form.elements[i].reportValidity();
                break;

            }


        }
        if (errors == 'NULL') {


            var leavetype = document.getElementById('type');
            var leavedate = document.getElementById('from');
            var todate = document.getElementById('to');

            var datefiled = document.getElementById('datefiled');
            var notes = document.getElementById('notes');
            var table = document.getElementById('Tabledata');
            var duration = document.getElementById('duration');

            var type = leavetype.options[leavetype.selectedIndex].text





            var rowCount = table.rows.length;



            var row = table.insertRow(rowCount);


            row.insertCell(0).innerHTML = type + "<input type='text' name='leavetype[]' value='" + leavetype.value +
                "' hidden> <input type='text' name='leavename[]' value='" + type +
                "' hidden>" ;
            row.insertCell(1).innerHTML = leavedate.value + " - " + todate.value +
                "<input type='text' class='dateleave' name='from[]' value='" + leavedate.value + "' hidden> <input type='text' class='dateleave1' name='to[]' value='" + todate.value + "' hidden>" ;

            row.insertCell(2).innerHTML = duration.value + "<input type='text' name='days[]' value='" + duration.value + "' hidden> <textarea name='noted[]' hidden> "+ notes.value + "</textarea>";

            row.insertCell(3).innerHTML =
                '<button type = "button" class="btn btn-danger btn-sm" onclick="deleteRow(this)"><i class="fa fa-minus"></i></i> </button>';

        }




    }
    </script>

        <script language="javascript" type="text/javascript">
            $(document).ready(function(){
            $("form").on("submit", function(){
                $("#pageloader").fadeIn();
            });//submit

             $('#preloader').fadeOut();
            });//document ready



        </script>
</body>

</html>