<?php
include 'db_con_splitrow_employee.php';

/* start the session */
session_start();

if(!isset($_SESSION['username'])){ // Jika session username ada berarti dia sudah login   
  echo "<script>  window.location.href='../E-Leave/login.php';</script>"; // Kita Redirect ke halaman welcome.php
}

//cek level user
if($_SESSION['level'] ==='Users'){ // Jika session level users kita redirect to index page    
    echo '            
            <script>                 
                window.location.href="..//E-Leave/level_validate.php";                            
            </script>;            
        ';         
    }

if (isset($_SESSION['username'])) {       
    $data = mysqli_query($conn,"SELECT * FROM usr_profile WHERE status IN ('I','D') AND user_id ='".$_SESSION['username']."'");
    $cek_usrBaned = mysqli_num_rows($data);

    if($cek_usrBaned > 0){ // found the banned user       
       session_destroy(); 
       echo "<script>  window.location.href='../E-Leave/login.php';</script>";
    }

} else {    
//echo "You need to login!";
}

//update timestamp
$cek_uid =$_SESSION['username'];  
$timezone = "Asia/Jakarta";
date_default_timezone_set($timezone);  
$datetime = new DateTime(date("Y-m-d H:i:s"));
$str_datetime = $datetime->format("Y-m-d H:i:s");
$sql  = ("UPDATE usr_profile SET last_activity = '$str_datetime' WHERE user_id = '$cek_uid'");
$query = mysqli_query($conn, $sql);

$list = "SELECT employee_id FROM usr_profile WHERE user_id ='".$_SESSION['username']."'";
$rs_list = $conn->query($list);

while($row_list = $rs_list->fetch_assoc()) {						
    $list_empID = $row_list['employee_id'];                        		
}
$getname = "SELECT name FROM employee WHERE employee_id ='".$list_empID."'";
$rs_getname = $conn->query($getname);

while($row_getname = $rs_getname->fetch_assoc()) {						
    $list_empName = $row_getname['name'];                        		
}     


if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $results_per_page;
$sql_group_emp = "SELECT *, employee.ID as eID FROM employee INNER JOIN department_group ON employee.department_G = department_group.ID WHERE employee.status = 0 ORDER BY employee.ID LIMIT $start_from," .$results_per_page;
$rs_result_GP = $conn->query($sql_group_emp);

//Delete Employee Submit
if(isset($_POST["employee_delete"])) {
// Attempt update query execution employee status
$sql  = ("UPDATE employee SET status = 1, user_id_updated = '$cek_uid', date_update = '$str_datetime' WHERE ID = '".$_POST["employee_id_del"]."'");
$query = mysqli_query($conn, $sql);

// Attempt update query execution users profile status
$sql_empID  = ("SELECT employee_id FROM employee WHERE ID = '".$_POST["employee_id_del"]."'");
$rs_result_empID = $conn->query($sql_empID);
$row_empID = $rs_result_empID->fetch_assoc();
$get_empID = $row_empID['employee_id'];         

$sql2  = ("UPDATE usr_profile SET status = 'D' WHERE employee_id = '$get_empID'");
$query2 = mysqli_query($conn, $sql2);

// Attempt update query execution users permision status 
$sql3  = ("UPDATE users_permission SET status = 1 WHERE user_employee_id = '".$_POST["employee_id_del"]."' OR approval_employee_id = '".$_POST["employee_id_del"]."'");
$query3 = mysqli_query($conn, $sql3);

echo "<script>  window.location.href='..//E-Leave/employee.php';</script>";
} 

?>

<html lang="en">

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  
  <link rel="stylesheet" href="iconfont/material-icons.css">
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <!-- Bootstrap core CSS -->
  <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <!-- Custom styles for this template -->
  <link href="css/simple-sidebar.css" rel="stylesheet">
  <!-- Custom styles material-icons -->
  <link rel="stylesheet" href="iconfont/material-icons.css">
  <!-- Custom styles material-icons-param -->
  <link rel="stylesheet" href="iconfont/material-icons-param.css"> 
  <!-- Alert Java -->
  <script src="sweetalert-master/docs/assets/sweetalert/sweetalert.min.js"></script>
  
<script type="text/javascript">
    function myFn(){
        swal({ 
              title: "Success",
              text: "Thank you for contacting us. We will get back to you soon!",
              type: "success" 
        },
             function(){
                //event to perform on click of ok button of sweetalert
        });
    }
</script>

  <title>employee</title>
 
  <style type="text/css">
    body {
        color: #566787;
		background: #f5f5f5;
		font-family: 'Varela Round', sans-serif;
		font-size: 13px;
	}
	.table-wrapper {
        background: #fff;
        padding: 1px 25px;
        margin: 30px 0;
		border-radius: 3px;
        box-shadow: 0 1px 1px rgba(0,0,0,.05);        
    }
	.table-title {        
		padding-bottom: 15px;
		background: #435d7d;
		color: #fff;
		padding: 16px 30px;
		margin: -20px -25px 10px;
		border-radius: 3px 3px 0 0;
    }
    .table-title h2 {
		margin: 5px 0 0;
		font-size: 24px;
	}
	.table-title .btn-group {
		float: right;
	}
	.table-title .btn {
		color: #fff;
		float: right;
		font-size: 13px;
		border: none;
		min-width: 50px;
		border-radius: 2px;
		border: none;
		outline: none !important;
		margin-left: 10px;
	}
	.table-title .btn i {
		float: left;
		font-size: 21px;
		margin-right: 5px;
	}
	.table-title .btn span {
		float: left;
		margin-top: 2px;
	}
    table.table tr th, table.table tr td {
        border-color: #e9e9e9;
		padding: 5px 15px;
		vertical-align: middle;
    }
	table.table tr th:first-child {
		width: 60px;
	}
	table.table tr th:last-child {
		width: 100px;
	}
    table.table-striped tbody tr:nth-of-type(odd) {
    	background-color: #fcfcfc;
	}
	table.table-striped.table-hover tbody tr:hover {
		background: #f5f5f5;
	}
    table.table th i {
        font-size: 13px;
        margin: 0 5px;
        cursor: pointer;
    }	
    table.table td:last-child i {
		opacity: 0.9;
		font-size: 20px;
        margin: 0 5px;
    }
	table.table td a {
		font-weight: bold;
		color: #566787;
		display: inline-block;
		text-decoration: none;
		outline: none !important;
	}
	table.table td a:hover {
		color: #2196F3;
	}
	table.table td a.edit {
        color: #FFC107;       
    }
        
    table.table td a.delete {
        color: #F44336;
    }
    table.table td i {
        font-size: 19px;
    }
	table.table .avatar {
		border-radius: 50%;
		vertical-align: middle;
		margin-right: 10px;
	}
        
    table {
        display: block;
        overflow-x: auto;
        white-space: nowrap;
        }
        
    .pagination {
        float: right;
        margin: 0 0 5px;
    }
    .pagination li a {
        border: none;
        font-size: 13px;
        min-width: 30px;
        min-height: 30px;
        color: #999;
        margin: 0 2px;
        line-height: 30px;
        border-radius: 2px !important;
        text-align: center;
        padding: 0 6px;
    }
    .pagination li a:hover {
        color: #666;
    }	
    .pagination li.active a, .pagination li.active a.page-link {
        background: #03A9F4;
    }
    .pagination li.active a:hover {        
        background: #0397d6;
    }
	.pagination li.disabled i {
        color: #ccc;
    }
    .pagination li i {
        font-size: 16px;
        padding-top: 6px
    }
    .hint-text {
        float: left;
        margin-top: 10px;
        font-size: 13px;
    }    
	/* Custom checkbox */
	.custom-checkbox {
		position: relative;
	}
	.custom-checkbox input[type="checkbox"] {    
		opacity: 0;
		position: absolute;
		margin: 5px 0 0 3px;
		z-index: 9;
	}
	.custom-checkbox label:before{
		width: 18px;
		height: 18px;
	}
	.custom-checkbox label:before {
		content: '';
		margin-right: 10px;
		display: inline-block;
		vertical-align: text-top;
		background: white;
		border: 1px solid #bbb;
		border-radius: 2px;
		box-sizing: border-box;
		z-index: 2;
	}
	.custom-checkbox input[type="checkbox"]:checked + label:after {
		content: '';
		position: absolute;
		left: 6px;
		top: 3px;
		width: 6px;
		height: 11px;
		border: solid #000;
		border-width: 0 3px 3px 0;
		transform: inherit;
		z-index: 3;
		transform: rotateZ(45deg);
	}
	.custom-checkbox input[type="checkbox"]:checked + label:before {
		border-color: #03A9F4;
		background: #03A9F4;
	}
	.custom-checkbox input[type="checkbox"]:checked + label:after {
		border-color: #fff;
	}
	.custom-checkbox input[type="checkbox"]:disabled + label:before {
		color: #b8b8b8;
		cursor: auto;
		box-shadow: none;
		background: #ddd;
	}
	/* Modal styles */
	.modal .modal-dialog {
		max-width: 1200px;
	}
        .modal .modal-dialog-del {
		max-width: 400px;
	}        
	.modal .modal-header, .modal .modal-body, .modal .modal-footer {
		padding: 20px 30px;
	}
	.modal .modal-content {
		border-radius: 3px;
	}
	.modal .modal-footer {
		background: #ecf0f1;
		border-radius: 0 0 3px 3px;
	}
    .modal .modal-title {
        display: inline-block;
    }
	.modal .form-control {
		border-radius: 2px;
		box-shadow: none;
		border-color: #dddddd;
                font-size: 14px;
                width: 400px;
	}
	.modal textarea.form-control {
		resize: vertical;
	}
	.modal .btn {
		border-radius: 2px;
		min-width: 100px;                
	}	
	.modal form label {
		font-weight: normal;
	}
        
        #fileElem {
         /* Note: display:none on the input won't trigger the click event in WebKit.
        Setting visibility: hidden and height/width:0 works great. */
        visibility: hidden;
        width: 0;
        height: 0;
        }
        #fileElem_edit {
         /* Note: display:none on the input won't trigger the click event in WebKit.
        Setting visibility: hidden and height/width:0 works great. */
        visibility: hidden;
        width: 0;
        height: 0;
        }
        #fileSelect {
        /* style the button any way you want */
        }
        
        div.posisi {
            position: relative;
            left: 152px;
            width: 90%;
        }
</style>

  <script src="../E-Leave/jquery/jquery.min.js"></script>
  <script src="../E-Leave/jquery/bootstrap.min.js"></script>
  <script src="../E-Leave/jquery/jquery-3.4.1.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
	// Activate tooltip
	$('[data-toggle="tooltip"]').tooltip();	
});
</script>

<script type="text/javascript">
//alert("myEdit");
$(function(){ //jQuery shortcut for .ready (ensures DOM ready)
 $('.edit').click(function(){  
  var serviceID = this.id;
  var grpID = this.name;
  //alert(grpID);  
  var employeeID = $('#employeeID_'+serviceID).text();
  //alert(employeeID);
  var name = $('#name_'+serviceID).text();
  var nik = $('#nik_'+serviceID).text();
  var address = $('#address_'+serviceID).text();
  var birthDate = $('#birthDate_'+serviceID).text();
  var gender = $('#gender_'+serviceID).text();
  var maritalStatus = $('#maritalStatus_'+serviceID).text();
  var nationality = $('#nationality_'+serviceID).text();
  var joinDate = $('#joinDate_'+serviceID).text();
  var phone = $('#phone_'+serviceID).text();
  var email = $('#email_'+serviceID).text();
  var img = $('#img_'+serviceID).text();
  var image = "/E-Leave/image/"+img;
  
  //alert(emp_Grp);  
  $('#edit_employee_id').val(employeeID);
  $('#edit_employee_name').val(name);
  $('#edit_employee_nik').val(nik);
  $('#edit_employee_address').val(address);
  $('#edit_employee_BoD').val(birthDate);  
  $('#edit_employee_gender').val(gender);
  $('#edit_employee_MS').val(maritalStatus);
  $('#edit_employee_nationality').val(nationality);
  $('#edit_employee_join').val(joinDate);
  $('#edit_employee_phone').val(phone);
  $('#edit_employee_email').val(email);  
  $('#edit_employee_group').val(grpID);
  $('#employee_id_edit').val(serviceID);   
  $('#edit_output').attr("src",image);
  $('#employee_id_img').val(employeeID);
  $('#last_img').val(img);  
  
  var im = document.getElementById('edit_output'); // or select based on classes
    im.onerror = function(){
        // image not found or change src like this as default image:
    im.src = '/E-Leave/image/blank.png';   
};
  //alert(image);
  
  if(gender=="Male"){
	$("#employee_gender_Male").prop("checked", true);
  }else{
	$("#employee_gender_Female").prop("checked", true);
  }
  
  if(maritalStatus=="Single"){
	$("#employee_MS_Single").prop("checked", true);
  }else{
	$("#employee_MS_Maried").prop("checked", true);
  }

 });
});
</script>

<script>
$(document).ready(function(){   
    $(".postsubmit").click(function(){                                       
        //siteName = document.getElementById('last_img').value;
        //localStorage.setItem('store0', siteName);         
        var employee_BoD = $(this).closest('form') //target common parent
                            .find('[name=employee_BoD]') //target element
                            .val();        
        var employee_join = $(this).closest('form') //target common parent
                            .find('[name=employee_join]') //target element
                            .val();
        var employee_group = $(this).closest('form') //target common parent
                            .find('[name=employee_group]') //target element
                            .val();                                
        var employee_id = $(this).closest('form') //target common parent
                            .find('[name=employee_id]') //target element
                            .val();        
        var employee_name = $(this).closest('form') //target common parent
                            .find('[name=employee_name]') //target element
                            .val();        
        var employee_address = $(this).closest('form') //target common parent
                            .find('[name=employee_address]') //target element
                            .val();        
        var employee_gender = $(this).closest('form') //target common parent
                            .find(jQuery('input[name="employee_gender"]:checked')) //target element
                            .val();         
        var employee_MS = $(this).closest('form') //target common parent
                            .find(jQuery('input[name="employee_MS"]:checked')) //target element
                            .val();        
        var employee_nik = $(this).closest('form') //target common parent
                            .find('[name=employee_nik]') //target element
                            .val();        
        var employee_nationality = $(this).closest('form') //target common parent
                            .find('[name=employee_nationality]') //target element
                            .val();        
        var employee_phone = $(this).closest('form') //target common parent
                            .find('[name=employee_phone]') //target element
                            .val();        
        var employee_email = $(this).closest('form') //target common parent
                            .find('[name=employee_email]') //target element
                            .val();       
        var fileElem = $(this).closest('form') //target common parent
                            .find('[name=employee_picture]') //target element
                            .val().split('\\').pop();                          
        //var fileElem = $("#fileElem").val().split('\\').pop();
        var submit_val = $(this).attr("value");         
        var employee_id_edit = $("#employee_id_edit").val();       
        //var employee_img = $("#employee_img").val();        
       //var fileElem = $("#fileElem").val().split('\\').pop();
            var dataPost_employee = {
                "employee_BoD": employee_BoD, 
                "employee_join": employee_join,
                "employee_group": employee_group,
                "employee_id": employee_id,
                "employee_name": employee_name, 
                "employee_address": employee_address,
                "employee_gender": employee_gender,                
                "employee_MS": employee_MS,             
                "employee_nik": employee_nik, 
                "employee_nationality": employee_nationality,
                "employee_phone": employee_phone,
                "employee_email": employee_email,
                "fileElem": fileElem,
                "submit_val": submit_val,
                "employee_id_edit": employee_id_edit
                };
            var dataString = JSON.stringify(dataPost_employee);
            var flag = 0;
            
            if(submit_val == 'Add'){
                x=0;          
            }else{
                x=1; 
            }
            
            if($("form")[x].checkValidity()) {
            $.ajax({
                type: "POST",
                url: "..//E-Leave/employee_validate.php",
                dataType: "json",        
                //data: {"employee_BoD": employee_BoD},
                data: {data_employee: dataString},
                async:false,
                success : function(data){
                      //alert("sukses");
                      //alert(data.result);
                    if(data.result == "wrong_date"){
                       //alert("Invalid Date");
                       swal("Warning!", "Invalid Date", "error"); 
                       flag = 1;
                   }else if(data.result == "SDG"){
                       //alert("Please Select Department Group");
                       swal("Warning!", "Please Select Department Group", "error");
                       flag = 1;
                   }else if(data.result == "level_invalid"){ 
                       swal("Warning!", "This Group Level has been use in users permission", "warning"); 
                       flag = 1;                  
                   }else if(data.result == "duplicate"){
                       //alert("Employee Already Exist");
                       swal("Warning!", "Employee Already Exist", "warning");
                       flag = 1;
                   }
                    else if(data.result == "kosong"){
                       alert("Employee ID Cannot be Empty");
                       flag = 1;
                   }   
                    else{
                       //alert("TRAP");
                       //flag = 1;
                   }
                },
                error : function(data){ 
                    alert("Data Failed to send");
                    //alert(data.result);
                    flag = 1;
                    //return false;
                }
            });        
                if(flag == 1){            
                    return false;
                    //flag = 0;            
                }else{            
                    return true;            
                }
            }
    });                   
});    
</script>

<script>   
$(document).on('keydown keyup input click','#employee_id', function (e) {
if($('#addEmployeeModal').is(':visible')) {
            var key = e.which;
                if (key === 32) { //This is an Space 
                    return false;
                }
        }
    });
</script>

<script>   
$(document).on('keydown keyup input click','#edit_employee_id', function (e) {
if($('#editEmployeeModal').is(':visible')) {
            var key = e.which;
                if (key === 32) { //This is an Space 
                    return false;
                }
        }
    });
</script>    

<script type="text/javascript">
//Delete ID Row Define
$(function(){ //jQuery shortcut for .ready (ensures DOM ready)
 $('.delete').click(function(){  
  var serviceID = this.id;    
  $('#Id_del').val(serviceID);
 
 });
});
</script> 

<script>
//cek idle user on client side (5 menit)
var timeoutID; 
function setup() {
    this.addEventListener("mousemove", resetTimer, false);
    this.addEventListener("mousedown", resetTimer, false);
    this.addEventListener("keypress", resetTimer, false);
    this.addEventListener("DOMMouseScroll", resetTimer, false);
    this.addEventListener("mousewheel", resetTimer, false);
    this.addEventListener("touchmove", resetTimer, false);
    this.addEventListener("MSPointerMove", resetTimer, false);
 
    startTimer();
}
setup();
 
function startTimer() {
    // wait 5 minutes before calling goInactive
    timeoutID = window.setTimeout(goInactive, 300000);
}
 
function resetTimer(e) {
    window.clearTimeout(timeoutID);
    goActive();
}
 
function goInactive() {
    // do something
    //alert('Idle');
    window.location.href='../E-Leave/logout.php';    
}
 
function goActive() {
    // do something
         
    startTimer();
}    
</script>    

<script type="text/javascript">
    //cek interval setiap 10 menit
         jQuery(document).ready(function(){
             setInterval(function(){
                 jQuery.ajax({
                     type: 'POST',
                     url: '..//E-Leave/activity_upd.php',                     
                     success:function(){
                         //alert("Update Timestamp");
                         //window.location.href='..//E-Leave/index.php';
                         //return true;
                     }
                 });
             }, 600000);
         });
</script>

</head>

<body>

  <div class="d-flex" id="wrapper">

    <!-- Sidebar -->
    <div class="border-right" id="sidebar-wrapper">      
      <div class="list-group list-group-flush">
        <div style=" padding: 0.875rem 1.25rem; font-size: 1.2rem; width: 200px; height: 60px;">
                <h1>Start</h1> 
        </div>
        
            <button class="dropdown-btn list-group-item list-group-item-action">
                Manage <i class="nav-drop-icon material-icons">keyboard_arrow_down</i>
            </button>
        <div class="dropdown-container" style="display: none;">
            <a href="group.php" class="list-group-item list-group-item-action">Group</a>
            <a href="employee.php" class="list-group-item list-group-item-action">Employee</a>
            <a href="users.php" class="list-group-item list-group-item-action">Users</a>
            <a href="leave_types.php" class="list-group-item list-group-item-action">Leave Types</a>
        </div>            
        <button class="dropdown-btn list-group-item list-group-item-action">
                Setting <i class="nav-drop-icon material-icons">keyboard_arrow_down</i>
            </button>
        <div class="dropdown-container" style="display: none;">
            <a href="holiday_date.php" class="list-group-item list-group-item-action">Holiday Date</a>
            <a href="users_permission.php" class="list-group-item list-group-item-action">Users Permission</a> 
            <a href="leaves_parameter.php" class="list-group-item list-group-item-action">Leaves Parameter</a>
        </div>          
        
<script>
/* Loop through all dropdown buttons to toggle between hiding and showing its dropdown content - This allows the user to have multiple dropdowns without any conflict */
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;

for (i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
  this.classList.toggle("active");
  var dropdownContent = this.nextElementSibling;
  if (dropdownContent.style.display === "block") {
  dropdownContent.style.display = "none";
  } else {
  dropdownContent.style.display = "block";
  }
  });
}
</script>
          
        <a href="leave_request.php" class="list-group-item list-group-item-action bg-light">Leave Request</a>        
        <a href="leave_approval.php" class="list-group-item list-group-item-action bg-light">Leave Approval</a>
        <a href="audittrail.php" class="list-group-item list-group-item-action bg-light">Audit Trail</a>
        <a href="#" class="list-group-item list-group-item-action bg-light">Report</a>   
      </div>
    </div>
    <!-- /#sidebar-wrapper -->

    <!-- Page Content -->
    <div class="posisi">

      <nav class="navbar navbar-expand-lg navbar-light bg-light border-bottom">
        <button class="btn btn-primary" id="menu-toggle" style="display:none;">Toggle Menu</button>

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav ml-auto mt-2 mt-lg-0">
            <li class="nav-item active">
              <a class="nav-link">Welcome 
                  <?php                
                echo $list_empName;
                    ?>    
                  <span class="sr-only">(current)</span></a>
            </li>            
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="nav-drop-icon material-icons">person_pin</i>
              </a>
              <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                <a class="dropdown-item" href="#">Profile</a>
                <a class="dropdown-item" href="change_password.php">Change Password</a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" href="logout.php">Logout</a>
              </div>
            </li>
          </ul>
        </div>
      </nav>
        
    <!-- /#page-content-wrapper -->    
    <div class="container">
        <div class="table-wrapper">
            <div class="table-title">
                <div class="row">
                    <div class="col-sm-6">
						<h2>Manage <b>Employees</b></h2>
					</div>
					<div class="col-sm-6">
						<a href="#addEmployeeModal" class="btn btn-success" data-toggle="modal"><i class="material-icons">&#xE147;</i> <span>Add New Employee</span></a>						
					</div>
                </div>
            </div>
            <table class="table table-striped table-hover">
                <thead>
                    <tr>					
                        <th>Employee ID</th>
                        <th>Name</th>
			<th>NIK/NIP</th>
                        <th>Address</th>
                        <th>Birth of Date</th>
                        <th>Gender</th>
                        <th>Marital Status</th>
			<th>Nationality</th>
                        <th>Join Date</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Department Group</th>
                        <th>Action</th>
                        <th style="display:none">img</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                            while($row = $rs_result_GP->fetch_assoc()) {						
                            echo '<tr style="font-size: 13px;">
                                    <td id="employeeID_'.$row['eID'].'"  width="30%">'.$row['employee_id'].'</td>
                                    <td id="name_'.$row['eID'].'" >'.$row['name'].'</td>
                                    <td id="nik_'.$row['eID'].'"  width="10%">'.$row['NIK'].'</td>
                                    <td id="address_'.$row['eID'].'"  width="30%">'.$row['address'].'</td>
                                    <td id="birthDate_'.$row['eID'].'" >'.$row['birth_date'].'</td>
                                    <td id="gender_'.$row['eID'].'"  width="10%">'.$row['gender'].'</td>
                                    <td id="maritalStatus_'.$row['eID'].'"  width="30%">'.$row['marital_status'].'</td>
                                    <td id="nationality_'.$row['eID'].'" >'.$row['nationality'].'</td>
                                    <td id="joinDate_'.$row['eID'].'"  width="30%">'.$row['join_date'].'</td>    
                                    <td id="phone_'.$row['eID'].'"  width="10%">'.$row['phone'].'</td>                                    
                                    <td id="email_'.$row['eID'].'" >'.$row['email'].'</td>
                                    <td id="department_'.$row['ID'].'" width="10%"> '.$row['group_code'].' | '.$row['Department_G'].' </td>
                                    <td style="display:none" id="img_'.$row['eID'].'" >'.$row['employee_picture'].'</td>    
                                    <td>
                                        <a href="#editEmployeeModal" name="'.$row['ID'].'" class="edit" data-toggle="modal" id="'.$row['eID'].'" onclick="editClick()"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a>
                                        <a href="#deleteEmployeeModal" class="delete" data-toggle="modal" id="'.$row['eID'].'"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a>
                                    </td>
                                 </tr>';			
                        }	
                    ?> 
                </tbody>
            </table>                
		<div class="clearfix">
                <div class="hint-text">Showing <b><?php echo $page ?></b> out of <b>
                    <?php 
                    //$sql_to = "SELECT COUNT(ID) AS total FROM ".$datatable;
                    $sql_to = "SELECT COUNT(e.ID) AS total FROM employee e join department_group g on g.id = e.department_G WHERE g.STATUS = 0 AND e.status = 0";
                    $rs_result_GP = $conn->query($sql_to);
                    $row_to = $rs_result_GP->fetch_assoc();
                    $pages_to = ceil($row_to["total"] / $results_per_page);
                    echo"$pages_to";                    
                    ?></b> entries</div>
                <ul class="pagination">
                    <li class="page-item">
                       <?php 
                        //$sql = "SELECT COUNT(ID) AS total FROM ".$datatable;
                        $sql = "SELECT COUNT(e.ID) AS total FROM employee e join department_group g on g.id = e.department_G WHERE g.STATUS = 0 AND e.status = 0";
                        $rs_result_GP = $conn->query($sql);
                        $row = $rs_result_GP->fetch_assoc();
                        $total_pages = ceil($row["total"] / $results_per_page); // calculate total pages with results
  
                        for ($i=1; $i<=$total_pages; $i++) {  // print links for all pages
                        echo "<a href='employee.php?page=".$i."'";
                         if ($i==$page)  echo " class='curPage'";
                            echo ">".$i."</a> "; 
                        }; 
                        ?> 
                    </li>                        
                </ul>
            </div>
        </div>
    </div>
	<!-- Add Modal HTML -->
	<div id="addEmployeeModal" class="modal fade" id="add_modal">
		<div class="modal-dialog">
			<div class="modal-content">
                            <form method="POST" id="addform" enctype="multipart/form-data">
					<div class="modal-header">						
						<h4 class="modal-title">Add Employee</h4>
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					</div>
                                    <table>                                         
                                        <td width="1%"></td>                                        
                                        <td style="vertical-align: top;">
                                    <div class="text-center">
                                        <img id="output" name="output_img" src="/E-Leave/image/blank.png" alt="Image" width="200" height="200">
                                        <input type="file" id="fileElem" name="employee_picture" onchange="document.getElementById('output').src = window.URL.createObjectURL(this.files[0])">                                        
                                        <button id="fileSelect" type="button">Select Photo</button>
                                        <Br><br>
                                        <label style="font-size: 9px; color:red;">Max upload is 2MB size of image</label>
                                        <script>                                            
                                            document.querySelector('#fileSelect').addEventListener('click', function(e) {
                                             // Use the native click() of the file input.
                                            document.querySelector('#fileElem').click();                                            
                                            }, false);                                                                                        
                                        </script>                                                                            
                                        
                                    </div>        
                                        </td>                                        
                                        <td>
                                        <div class="modal-body">
                                                <div class="form-group">
							<label>Employee ID</label>
							<input type="text" class="form-control employee_id" id="employee_id" name="employee_id" required>
						</div>
						<div class="form-group">
							<label>Name</label>
							<input type="text" class="form-control employee_name" id="employee_name" name="employee_name" required>
						</div>
                                                <div class="form-group">
							<label>Address</label>
							<textarea class="form-control employee_address" id="employee_address" name="employee_address" required></textarea>
						</div>
						<div class="form-group">
							<label>Birth of Date</label>
							<input type="date" class="form-control employee_BoD" name="employee_BoD" id="employee_BoD" required>
						</div>
						<div class="form-group">
							<fieldset>
                                                            <legend>Gender</legend>                                                            
                                                            <p>
                                                            <input type = "radio" name = "employee_gender" id = "employee_gender" value = "Male" checked = "checked" /> 
                                                            <label for = "sizeSmall">Male</label>
                                                            <input type = "radio" name = "employee_gender" id = "employee_gender" value = "Female" />
                                                            <label for = "sizeMed">Female</label>
                                                            </p>
                                                        </fieldset>
						</div>
                                                <div class="form-group">
							<fieldset>
                                                            <legend>Marital Status</legend>                                                            
                                                            <p>
                                                            <input type = "radio" name = "employee_MS" id = "employee_MS" value = "Single" checked = "checked" /> 
                                                            <label for = "sizeSmall">Single</label>
                                                            <input type = "radio" name = "employee_MS" id = "employee_MS" value = "Maried" />
                                                            <label for = "sizeMed">Maried</label>
                                                            </p>
                                                        </fieldset>
						</div>
                                        </td>
                                        <td>
                                            <div class="form-group">
							<label>NIK/NIP</label>
							<input type="text" class="form-control" id ="employee_nik" name="employee_nik" required>
						</div>
                                                <div class="form-group">
							<label>Nationality</label>
							<input type="text" class="form-control" id="employee_nationality" name="employee_nationality" required>
						</div>
                                                <div class="form-group">
							<label>Phone</label>
							<input type="text" class="form-control" id="employee_phone" name="employee_phone" required>
						</div>
                                                <div class="form-group">
							<label>Join Date</label>
                                                        <input type="date" class="form-control employee_join" id="employee_join" name="employee_join" required>
						</div>
                                                <div class="form-group">
							<label>Email</label>
							<input type="email" class="form-control" id="employee_email" name="employee_email" required>
						</div>
                                                <div class="form-group">
                                                    <select name="employee_group" id="employee_group">
                                                    <option value=0>Select Department Group</option>
                                                    <?php                                                     
                                                    require_once 'db_con_splitrow_group.php';
                                                    $query = "SELECT * FROM department_group WHERE STATUS=0";
                                                    $result = mysqli_query($conn, $query);                                                    
                                                    while($data = mysqli_fetch_assoc($result) ){                                                    
                                                    echo "<option value=" . $data[ID] . ">" . $data['group_code'] . ' | ' . $data['Department_G'] . "</option>";    
                                                    }						
                                                    ?>                                                        							
                                                    </select>    
						</div>
                                        </td>
                                    </table>                                      
					<div class="modal-footer">
                                            <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" onclick="window.location=window.location;">
                                            <input type="submit" class="btn btn-success postsubmit" value="Add" name="add_employee">
					</div>
				</form>
			</div>
		</div>
	</div>
	<!-- Edit Modal HTML -->
	<div id="editEmployeeModal" class="modal fade">
		<div class="modal-dialog">
			<div class="modal-content">
				<form method="POST" enctype="multipart/form-data">
					<div class="modal-header">						
						<h4 class="modal-title">Edit Employee</h4>
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					</div>
					<table>                                         
                                        <td width="1%"></td>                                        
                                        <td style="vertical-align: top;">
                                    <div class="text-center">
                                        <img id="edit_output" name="output_img" alt="Image" width="200" height="200" >
                                        <input type="file" id="fileElem_edit" id="fileElem" name="employee_picture" onchange="document.getElementById('edit_output').src = window.URL.createObjectURL(this.files[0])">                                        
                                        <button id="fileSelect_edit" type="button">Select Photo</button>
                                        <Br><br>
                                        <label style="font-size: 9px; color:red;">Max upload is 2MB size of image</label>
                                        
                                        <script>                                            
                                            document.querySelector('#fileSelect_edit').addEventListener('click', function(e) {
                                             // Use the native click() of the file input.
                                            document.querySelector('#fileElem_edit').click();                                            
                                            }, false);                                                                                        
                                        </script>                                                                                                                    
                                    </div>        
                                        </td>                                        
                                        <td>
                                        <div class="modal-body">
                                                <div class="form-group">
							<label>Employee ID</label>
							<input id="edit_employee_id" type="text" class="form-control" id="employee_id" name="employee_id" disabled>
						</div>
						<div class="form-group">
							<label>Name</label>
							<input id="edit_employee_name" type="text" class="form-control" id="employee_name" name="employee_name" required>
						</div>
                                                <div class="form-group">
							<label>Address</label>
							<textarea id="edit_employee_address" class="form-control" id="employee_address" name="employee_address" required></textarea>
						</div>
						<div class="form-group">
							<label>Birth of Date</label>
							<input id="edit_employee_BoD" type="date" class="form-control employee_BoD" name="employee_BoD" id="employee_BoD" required>
						</div>
						<div class="form-group">
							<fieldset>
                                                            <legend>Gender</legend>                                                            
                                                            <p>
                                                            <input type = "radio" name = "employee_gender" id = "employee_gender_Male" value = "Male" checked = "checked" /> 
                                                            <label for = "sizeSmall">Male</label>
                                                            <input type = "radio" name = "employee_gender" id = "employee_gender_Female" value = "Female" />
                                                            <label for = "sizeMed">Female</label>
                                                            </p>
                                                        </fieldset>
						</div>
                                                <div class="form-group">
							<fieldset>
                                                            <legend>Marital Status</legend>                                                            
                                                            <p>
                                                            <input type = "radio" name = "employee_MS" id = "employee_MS_Single" value = "Single" checked = "checked" /> 
                                                            <label for = "sizeSmall">Single</label>
                                                            <input type = "radio" name = "employee_MS" id = "employee_MS_Maried" value = "Maried" />
                                                            <label for = "sizeMed">Maried</label>
                                                            </p>
                                                        </fieldset>
						</div>
                                        </td>
                                        <td>
                                            <div class="form-group">
							<label>NIK/NIP</label>
							<input id ="edit_employee_nik" type="text" class="form-control" id ="employee_nik" name="employee_nik" required>
						</div>
                                                <div class="form-group">
							<label>Nationality</label>
							<input id="edit_employee_nationality" type="text" class="form-control" id="employee_nationality" name="employee_nationality" required>
						</div>
                                                <div class="form-group">
							<label>Phone</label>
							<input id="edit_employee_phone" type="text" class="form-control" id="employee_phone" name="employee_phone" required>
						</div>
                                                <div class="form-group">
							<label>Join Date</label>
                                                        <input id="edit_employee_join" type="date" class="form-control employee_join" id="employee_join" name="employee_join" required>
						</div>
                                                <div class="form-group">
							<label>Email</label>
							<input id="edit_employee_email" type="email" class="form-control" id="employee_email" name="employee_email" required>
						</div>
                                                <div class="form-group">
                                                    <select id="edit_employee_group" name="employee_group" id="employee_group">
                                                    <option value=0>Select Department Group</option>
                                                    <?php                                                     
                                                    require_once 'db_con_splitrow_group.php';
                                                    $query = "SELECT * FROM department_group WHERE STATUS=0";
                                                    $result = mysqli_query($conn, $query);                                                    
                                                    while($data = mysqli_fetch_assoc($result) ){                                                    
                                                    echo "<option value=" . $data[ID] . ">" . $data['group_code'] . ' | ' . $data['Department_G'] . "</option>";    
                                                    }						
                                                    ?>                                                        							
                                                    </select>    
						</div>
                                        </td>
                                    </table>
					<div class="modal-footer">
						<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
						<input type="submit" class="btn btn-info postsubmit" value="Save" name="submit_val">
                                                <input type="hidden" id="employee_id_edit" name="employee_id_edit" />
                                                <input type="hidden" id="employee_img" name="employee_img" />
                                                <input type="hidden" id="employee_id_img" name="employee_id_img" />
                                                <input type="hidden" id="last_img" name="last_img" />
					</div>
				</form>
			</div>
		</div>
	</div>
	<!-- Delete Modal HTML -->
	<div id="deleteEmployeeModal" class="modal fade">
		<div class="modal-dialog modal-dialog-del">
			<div class="modal-content">
				<form method="POST">
					<div class="modal-header">						
						<h4 class="modal-title">Delete Employee</h4>
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
					</div>
					<div class="modal-body">					
						<p>Are you sure you want to delete these Records?</p>
						<p class="text-warning"><small>This action cannot be undone.</small></p>
					</div>
					<div class="modal-footer">
						<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel">
						<input type="submit" class="btn btn-danger" value="Delete" name="employee_delete">
                                                <input type="hidden" id="Id_del" name="employee_id_del" />
					</div>
				</form>
			</div>
		</div>
	</div>
  </div>
  <!-- /#page-content-wrapper end -->

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

  <!-- Menu Toggle Script -->
  <script>
    $("#menu-toggle").click(function(e) {
      e.preventDefault();
      $("#wrapper").toggleClass("toggled");
    });
  </script>
  
<?php
 
//Add Employee Submit
if(isset($_POST["add_employee"])) {    
    $employee_id = $_POST['employee_id'];   
    $target_dir = "C:/xampp/htdocs/E-Leave/image/";     
    $target_file = $target_dir . $employee_id . '_'. $_FILES["employee_picture"]["name"];     
    $fileSize = $_FILES['employee_picture']['size'];    
    $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
    //echo "<script type='text/javascript'>alert('{$fileSize}');</script>";
    
    if($imageFileType=='jpg' || $imageFileType=='jpeg' || $imageFileType=='png' || $imageFileType=='gif')
      {  
        // Move the file
        move_uploaded_file($_FILES["employee_picture"]["tmp_name"], $target_file);   
        }   
        elseif($fileSize == 0){            
        // Move the file
        move_uploaded_file($_FILES["employee_picture"]["tmp_name"], $target_file);                      
        }
        else{
         echo '<script type="text/javascript">
                    swal({
                    title: "Warning!",
                    text: "This is not Image Format",
                    type: "info"
                    }).then(function() {
                        window.location.href="..//E-Leave/employee.php";
                    });
                    </script>';    
        //echo "<script> alert('This is not Image Format');</script>";                
}}

//Edit Employee Submit
if(isset($_POST["submit_val"])) {      
    $val_image = $_POST['last_img']; 
    $employee_id = $_POST['employee_id_img'];     
    $target_dir = "C:/xampp/htdocs/E-Leave/image/";     
    $target_file = $target_dir . $employee_id . '_'. $_FILES["employee_picture"]["name"];
    $fileSize = $_FILES['employee_picture']['size'];    
    $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);    
    
    if ($fileSize == 0 && $imageFileType=='jpg' || $imageFileType=='jpeg' || $imageFileType=='png' || $imageFileType=='gif') {                         
            $sql  = ("UPDATE employee SET employee_picture = '".$val_image."' WHERE employee_id = '".$employee_id."'");
            $query = mysqli_query($conn, $sql);                   
            echo "<script>  window.location.href='..//E-Leave/employee.php';</script>";            
        }elseif($imageFileType!='jpg' && $imageFileType!='jpeg' && $imageFileType!='png' && $imageFileType!='gif' && $imageFileType!=''){
            $sql  = ("UPDATE employee SET employee_picture = '".$val_image."' WHERE employee_id = '".$employee_id."'");
            $query = mysqli_query($conn, $sql);             
            //echo "<script> alert('This is not Image Format not swal');</script>";             
            echo '<script type="text/javascript">
                    swal({
                    title: "Warning!",
                    text: "This is not Image Format",
                    type: "info"
                    }).then(function() {
                        window.location.href="..//E-Leave/employee.php";
                    });
                    </script>';
            //echo "<script>  window.location.href='..//E-Leave/employee.php';</script>";
        }elseif($imageFileType==''){
            $sql  = ("UPDATE employee SET employee_picture = '".$val_image."' WHERE employee_id = '".$employee_id."'");
            $query = mysqli_query($conn, $sql);                    
            echo "<script>  window.location.href='..//E-Leave/employee.php';</script>";
        }
        else{
         move_uploaded_file($_FILES["employee_picture"]["tmp_name"], $target_file);     
        }                   
}

?>
  
</body>

</html>
