<?php 
session_start();
include('connect.php');

$message = '';
if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    $sqlUsername = "SELECT * FROM tbl_admin WHERE username = ?";
    $stmt = $conn->prepare($sqlUsername);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $resultUsername = $stmt->get_result();

    if ($resultUsername->num_rows > 0) {
        $rowUsername = $resultUsername->fetch_assoc();

        if ($password == $rowUsername["password"]) {
            $_SESSION['username'] = $rowUsername['username'];
            $_SESSION['level'] = $rowUsername['level'];
            $userlevel = $rowUsername['level'];

            if ($userlevel == 0) {
                header('Location: dashboard/index.php');
                exit;
            } else {
                header('Location: dashboard/indexcollection.php');
                exit;
            }
        } else {
            $message = '<p class="text-danger mb-0">Wrong Password</p>';
        }
    } else {
        $message = '<p class="text-danger mb-0">Wrong Username</p>';
    }

    $stmt->close();
}
?>

<!DOCTYPE html>
<html>
<head>
<title>AMWDS PORTAL</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes"/>
<link rel="apple-touch-icon" href="images/affiliates-icon512.png">
<?php include_once('linkStyle.php'); ?>
<link rel="stylesheet" type="text/css" href="css/login.css">
<link rel="manifest" href="manifest.json">
</head>
<body class="hold-transition layout-top-nav layout-footer-fixed layout-fixed">
<div id="preloader" class="loading" style="display: none;"></div>
<div class="wrapper">
<br><br>  

 





  <form class="pl-3 pr-3 pt-4" method="POST" id="userDetails">
    <center>
      <img src="dashboard/images/FS-Big.png" width="200">
 
      <?php 
        echo $message; 

        if(isset($_SESSION['success'])) {
          echo $_SESSION['success'];
          unset($_SESSION['success']);
        }
      ?>
    </center>
    <div class="form-group mt-4 pr-2 pl-2">
      <input type="text" name="username" id="username" class="form-control" placeholder="Username" autocomplete="off" required>
      <small id="availability"></small>
    </div>

    <div class="form-group mb-0 pr-2 pl-2">
      <input type="password" name="password" id="viewpassword" class="form-control" placeholder="Password" required>
    </div>
          <div class="icheck-dark pr-2 pl-2">
             <input type="checkbox" onclick="myFunction()" id="remember">
             <label for="remember">
               <small>Show Password</small>
             </label>
          </div>

    <div class="form-group mt-3 pr-2 pl-2">
      <input type="hidden" name="login" value="login">
      <button type="button" id="action" class="btn btn-primary btn-block btn-login">
       <span id="button-text">Login</span> 
      </button>
    </div>
 
  </form>

 
 


  <footer class="main-footer pb-0 add-to" style="box-shadow: 0 2px 5px 0 rgba(0,0,0,.16), 0 2px 10px 0 rgba(0,0,0,.12)!important;">
   <div class="card-body pl-0 pr-0 pt-1">
      <div class="row">
      <div class="col-2 col-lg-1">
          <img src="images/affiliates-icon180.png" class=" elevation-2" width="55">        
      </div>
      <div class="col-10 col-lg-11 pl-4">
      <button class="add-to-btn btn btn-warning"><b>→ DOWNLOAD THE MOBILE APP</b></button>
    <p class="text-muted font-weight-light"><small>https://amwd-services.com/</small></p> 
      </div>
    
    </div>
  
  </div>
</footer>
</div>
<script src="dashboard/plugins/jquery/jquery.min.js"></script>
<script src="dashboard/plugins/jquery-validation/jquery.validate.min.js"></script>
<script src="dashboard/plugins/jquery-validation/additional-methods.min.js"></script>
<script src="dashboard/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="dashboard/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script type="text/javascript">
if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

let deferredPrompt;
var div = document.querySelector('.add-to');
var button = document.querySelector('.add-to-btn');
div.style.display = 'none';

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  div.style.display = 'block';

  button.addEventListener('click', (e) => {
  // hide our user interface that shows our A2HS button
  div.style.display = 'none';
  // Show the prompt
  deferredPrompt.prompt();
  // Wait for the user to respond to the prompt
  deferredPrompt.userChoice
    .then((choiceResult) => {
      if (choiceResult.outcome === 'accepted') {
        console.log('User accepted the A2HS prompt');
      } else {
        console.log('User dismissed the A2HS prompt');
      }
      deferredPrompt = null;
    });
});
});

$(document).ready(function(){ 
var form = $("#userDetails");
form.validate({ // initialize plugin
  ignore:":not(:visible)",      
  rules: {
    username : "required",
    password : "required"
  },

  errorElement: 'span',
  errorPlacement: function (error, element) {
    error.addClass('invalid-feedback');
    element.closest('.form-group').append(error);
  },
  highlight: function (element, errorClass, validClass) {
    $(element).addClass('is-invalid');
  },
  unhighlight: function (element, errorClass, validClass) {
    $(element).removeClass('is-invalid');
  }
});

  $('#action').click(function() {
    if ($('#userDetails').valid() === true){
      $('#button-text').html('Please wait...');
      $('#action').attr('disabled', true);
      $('#userDetails').submit();
    }
  });

  $('#username').keyup(function() {
   var username = $(this).val();
   var btn_action = 'checkUsername';
   $.ajax({
     method:"POST",
     data:{user_name:username, btn_action:btn_action},
     url:"fetch.php",
     success:function(data){
       if(data != '0') {
          $('#availability').html('');
          $('#action').attr("disabled", false);
       }else{
          $('#availability').html('<span class="text-danger">Username not available.</span>');
          $('#action').attr("disabled", true);
       }  
     }
   });
  });

  $('.click-link').click(function() {
    $('.loading').show();
  });

});

function myFunction() {
  var x = document.getElementById("viewpassword");
  if (x.type === "password") {
    x.type = "text";
  } else {
    x.type = "password";
  }
}
if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}
</script>
</body>
</html>