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

$message = '';
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['login'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $branch = 'Laguna';

    $stmt = $conn->prepare("SELECT * FROM tbl_admin WHERE username = ? AND branch = ?");
    $stmt->bind_param("ss", $username, $branch);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows) {
        $user = $result->fetch_assoc();

        if ($password === $user['password']) {
            $_SESSION['username'] = $user['username'];
            $_SESSION['level'] = $user['level'];

            $redirect = ($user['level'] == 0) ? 'dashboard/index.php' : 'dashboard/indexcollection.php';
            header("Location: $redirect");
            exit;
        } else {
            $message = '<div class="alert alert-danger text-center py-2 mb-3">Wrong Password</div>';
        }
    } else {
        $message = '<div class="alert alert-danger text-center py-2 mb-3">Wrong Username or not part of Laguna branch</div>';
    }
    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AMWDS Laguna PORTAL - Login</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS (only once) -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
 <link rel="stylesheet" type="text/css" href="css/login.css">
  <!-- Optional: Custom CSS -->
  <style>
    body {
      background-color: #f0traf2f5;
    }
    .login-card {
      margin-top: 60px;
      padding: 30px;
 
    }
 
    .spinner-border {
      margin-left: 10px;
    }
    .bg-white {
      padding: 30px;
      margin-top:50px;
    background-color: #ffffff00 !important;
 .shadow {
    box-shadow: 0 .5rem 1rem rgb(255 255 255 / 0%) !important;
}
 
}
  </style>
</head>
<body>

<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-6 col-lg-5">
      <div class="bg-white">
        <div class="">

          <div class="text-center mb-4">
            <img src="dashboard/images/FS-Big.png" width="120" alt="Logo">
            <br><b class="text-branch">— LAGUNA —</b>
          </div>

          <?= $message; ?>

          <?php 
            if (isset($_SESSION['success'])) {
              echo '<div class="alert alert-success p-2">'.$_SESSION['success'].'</div>';
              unset($_SESSION['success']);
            }
          ?>

          <form method="POST" id="userDetails" novalidate>
            <div class="form-group">
           
              <input type="text" name="username" id="username" class="form-control" placeholder="Enter username" required>
              <small id="availability" class="form-text text-danger"></small>
            </div>

            <div class="form-group">
 
              <input type="password" name="password" id="viewpassword" class="form-control" placeholder="Enter password" required>
            </div>

            <div class="form-group form-check">
              <input type="checkbox" class="form-check-input" onclick="togglePassword()" id="remember">
              <label class="form-check-label" for="remember">Show Password</label>
            </div>

            <div class="form-group">
              <input type="hidden" name="login" value="login">
              <button type="button" id="action" class="pinkbutton btn btn-primary btn-block">
                <span id="button-text">Login</span>
                <span id="spinner" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
              </button>
            </div>
          </form>

        </div>

           <br> <a href="#"><b class="text-small">— Login to Cavite —</b> </a>
      </div>
    </div>
  </div>
</div>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="dashboard/plugins/jquery-validation/jquery.validate.min.js"></script>

<script>
$(document).ready(function () {
  var form = $("#userDetails");

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

  $('#action').on('click', function () {
    if (form.valid()) {
      $('#button-text').text('Logging in...');
      $('#spinner').removeClass('d-none');
      $('#action').prop('disabled', true);
      form.submit();
    }
  });

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

function togglePassword() {
  const input = document.getElementById("viewpassword");
  input.type = input.type === "password" ? "text" : "password";
}
</script>
</body>
</html>
