<?php 
ob_start();
session_start();
include('../dbconnect.php');
if( !isset($_SESSION['user']) ) {
 header("Location: ../index.php");
 exit;
}
if($_SESSION['userlevel'] != 'user'){
  header("Location: ../accessdenied.php");
}
$user = $_SESSION['user'];
$sqla = "SELECT * FROM account WHERE userid = '$user'";
$resulta = mysqli_query($conn, $sqla);
$rowa  = mysqli_fetch_assoc($resulta);
$acclevel = $rowa['level'];
$accstat = $rowa['status'];

$sqlb = "SELECT * FROM empinfo JOIN empdetails ON empinfo.empid = empdetails.detailid WHERE empinfo.empid = '$user'";
$resultb = mysqli_query($conn, $sqlb);
$rowb = mysqli_fetch_assoc($resultb);
$pic = $rowb['picture'];
$team = $rowb['team'];
$position = $rowb['generalpos'];
$accountname = $rowb['firstname'].' '.$rowb['surname'];
if(empty($pic)){
  $pic = "profile.png";
  $accountname = $rowa['level'];
}

function computeDuration($reqDate){

   
    $curdate = strtotime(date('Y-m-d H:i'));

  

  $datadate = strtotime($reqDate);
  if($datadate > $curdate){
    $diff = $datadate - $curdate;
    

    $min = floor($diff/(60))+30;

  }else{
    $diff = $curdate - $datadate;
    $min = floor($diff/(60));


  
  }



   return $min;



}





if(isset($_POST['genpin'])){

  $shift_date = $_POST['shift_date']; 
   
   
   $query = $conn->query("SELECT * FROM empinfo where userid='$user' ");
   $row = $query->fetch_assoc();
   $work_from_home = $row['work_from_home'];
    $date_now = date('Y-m-d');
   
   $get_sched = $conn->query("SELECT * FROM schedule WHERE date='$shift_date' and empid='$user' ");
   $sched_row = $get_sched->fetch_assoc();
    $starttime = $sched_row['pststarttime'];
   $endtime = $sched_row['endtime'];
   
   $req_date = $shift_date.' '.$starttime;
   
      $minutes_duration = computeDuration($req_date);
   
   
    $get_upass = $conn->query("SELECT * FROM empinfo where userid='$user'");
    $row_pass = $get_upass->fetch_assoc();
   
    //echo $work_from_home;
     //$info = 'Number of Minutes: '.$minutes_duration.' | schedule : '.$req_date.' | current date & time : '.date('Y-m-d H:i');
  //$time_stamp = date('Y-m-d H:i');

  
   //$conn->query("INSERT INTO `pin_logs`(`info`, `empid`, `time_stamp`) VALUES ('$info','$user','$time_stamp') ");
   
   
   if($work_from_home == '1' && $minutes_duration <= 60 && $minutes_duration >= 0 && $row['upassword'] == ''){

      $random_pin = substr(rand(),0, 4);
      $sql = $conn->query("UPDATE empinfo SET upassword = '$random_pin'  WHERE empid= '$user'");
  
       
     
   
    
   }else{
       $random_pin ='';

    $error = '<div class="alert alert-danger" role="alert">
     You can only generate PIN 30 minutes before to 1 hour after shift.
  </div>';


      
   
   }
   $info = 'Number of Minutes: '.$minutes_duration.' | schedule : '.$req_date.' | current date & time : '.date('Y-m-d H:i').' | PIN : '.$random_pin;
  $time_stamp = date('Y-m-d H:i');

  
   $conn->query("INSERT INTO `pin_logs`(`info`, `empid`, `time_stamp`) VALUES ('$info','$user','$time_stamp') ");

   

}


?>
<title>Employee</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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <nav class="navbar navbar-expand navbar-dark bg-dark static-top">

<a class="navbar-brand mr-1" href="dashboard.php"><?php echo $acclevel?></a>

<button class="btn btn-link btn-sm text-white order-1 order-sm-0" id="sidebarToggle" href="#">

  <i class="fas fa-bars"></i>


  
</button>




<!-- Navbar -->

<ul class="nav navbar-nav navbar-right">

</ul>

<ul class="navbar-nav  ml-auto mr-0 mr-md-3 my-2 my-md-0">
<!-- 
  <li class="nav-item dropdown no-arrow mx-1">
    <a class="nav-link dropdown-toggle togle" href="#" id="alertsDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <span class="badge badge-pill badge-danger count"></span>  <i class="fas fa-bell fa-fw"></i>
    </a>
    <div id="livenotif" class="dropdown-menu dropdown-menu-right" aria-labelledby="alertsDropdown">
    
    </div>
  </li> -->


  <li class="nav-item dropdown no-arrow">
    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      <img src = "../files/pictures/<?php echo $pic;?>" class="rounded-circle" height="20" width="20"> &nbsp <?php echo $accountname ?> &nbsp<i class="fa fa-sort-down"></i>
    </a>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown">
    <a class="dropdown-item" href="useraccount.php"> <i class="fas fa-user"></i> User Account</a>

      <div class="dropdown-divider"></div>
      <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal"><i class="fas fa-sign-out-alt"></i> Logout  </a>
    </div>
  </li>
</ul>


</nav>

 <!-- 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="../logout.php?logout" >Logout</a>
          </div>
        </div>
      </div>
    </div>

 

    <div class="modal fade" id="pin" 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">Utilization PIN</h5>
            <button class="close" type="button" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </div>
          <form method="POST" >
            <div class="modal-body">
              <?php echo $error?>

              <?php 

                $utilpin ="SELECT upassword FROM empinfo WHERE empid='$user'";
                $pinres = mysqli_query($conn, $utilpin);

                $pinrow = mysqli_fetch_assoc($pinres);

              ?>


              <h1 class="text-center" id="pin_pass"><?php echo isset($pinrow['upassword'])? $pinrow['upassword']  : '' ?></h1>
              <label for=""> Shift Date </label>
              <input type="date" class="form-control" name="shift_date" id="shift_date" required>
            
            </div>
            <div class="modal-footer">
              <button class="btn btn-secondary btn-info" id="genpin" name="genpin" type="submit" <?php  echo $pinrow['upassword'] != ''? 'disabled' : '' ?> >Generate PIN</button>

              <button class="btn btn-secondary" type="button" data-dismiss="modal">Close</button>

            </div>
          </form>
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $(document).ready(function () {



      /* $('#genpin').click(function(){

       // $('#pin_pass').text('');


        $.ajax({
          type: "POST",
          url: "ajax.php",
          data: {
            empid : "<?php echo $user?>",
            genkey :  1
          },
          success: function (response) {

            //alert(response);


            $('#pin_pass').text(response);

            $('#genpin').prop('disabled', true);


            
          }
        });



      });

      $('#shift_date').change(function(){
       // alert('sadas');
        $.ajax({
          type: "POST",
          url: "ajax.php",
          data: {
            getsched : 1,
            shiftdate : $('#shift_date').val(),
            empid : '<?php echo $user?>'
          },
        
          success: function (response) {
           // alert(response);

            var jsonres = $.parseJSON(response);

            if(jsonres.buttons == 'disabled'){
              alert(jsonres.buttons);
              $('#genpin').prop('disabled', true);
            }else{
              alert(jsonres.buttons);
              $('#genpin').prop('disabled', false);
            }

            
            
          }
        });
      }); */
      
    });

    </script>

<!-- <script>
  
$(document).ready(function(){

  function load_unseen_notification(view = ''){
    $.ajax({
      url: "fetchnotif.php",
      method: "POST",
      data:{view:view, empid: "<?php echo $user;?>"},
      dataType:"json",
      success:function(data){

        $('#livenotif').html(data.notification);
        if(data.unseen_notification > 0){
          $('.count').html(data.unseen_notification);
        }
      }

    });
  }


  load_unseen_notification();

$(document).on('click', '.togle', function(){
  $('.count').html('');
  load_unseen_notification('yes');

});

setInterval(function(){
  load_unseen_notification();
}, 5000)



});



</script>

 -->