<?php
// Start or resume the session
session_start();

// Connecting to the database
require_once '/my_custom_url/PRIVATE/db_config.php';
$conn = new mysqli($servername, $username, $password, $dbname);

// Checking the connection
if ($conn->connect_error) {
  die("Server connection error. Please try again later.");
}

$message = "";

/*
"Generating a CSRF token for the form."

A CSRF (Cross-Site Request Forgery) token is used to secure forms by ensuring that the request being submitted is coming from a legitimate user session.
It prevents malicious sites from performing actions on behalf of a user without their consent.
The token is unique to each user session and must be validated on the server side to process the form submission.
We check if a CSRF token has already been generated and stored in the session. If not, we create a new CSRF token by generating a string of 32 random bytes.
*/
if (!isset($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Processing the Login Form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Checking the CSRF token
  if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    /*
    When handling security errors, it's crucial not to be overly explicit in the user response.
    It's best to keep error messages generic to maintain security while still informing the user that their action was not successful.
    */
    die('An error has occurred.');
  }

  // Cleaning user inputs
  $usernameInput = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
  $password = $_POST['password']; // The password will be verified, no need to clean it

  /*
  Preparing a SQL statement to select the usernameIndex, password, and level from the USERS table where the usernameIndex matches the provided input.
  This prepares the statement for execution and prevents SQL injection by using parameterized queries.
  */
  $stmt = $conn->prepare("SELECT usernameIndex, password, level FROM USERS WHERE usernameIndex = ?");
  // Binding the input username to the parameter in the SQL query. The "s" indicates that the parameter is a string.
  $stmt->bind_param("s", $usernameInput);


  // Executes the previously prepared SQL query on the database.
  $stmt->execute();
  $result = $stmt->get_result();
  if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if (password_verify($password, $row['password'])) {
      /*
      Regenerates a new session ID for the current session. It is used to prevent session fixation attacks by generating a new session identifier while keeping the current session data.
      This is particularly useful after a successful login to ensure the integrity and security of the session.
      */
      session_regenerate_id();

      /*
      // Here, we are assigning user-specific information to the session.
      The 'username' session variable is being set to the 'usernameIndex' retrieved from the database, which represents the user's unique username.
      Similarly, the 'level' session variable is set to the user's access level.
      These session variables will be used throughout the application to personalize the user experience and control access to different features based on the user's level.
      */
      $_SESSION['username'] = $row['usernameIndex'];
      $_SESSION['level'] = $row['level'];

      // Updating the user's last login date and time
      $stmtUpdate = $conn->prepare("UPDATE USERS SET last_login = NOW() WHERE usernameIndex = ?");
      $stmtUpdate->bind_param("s", $usernameInput);
      $stmtUpdate->execute();
      $stmtUpdate->close();

      // Redirecting to dashboard.php
      header("Location: dashboard.php");
      exit;
    } else {
      /*
      There's no need to specify to the user the reason for the login failure: either the account is not found or the password is incorrect.
      */
      $message = "Incorrect username or password.";
    }
  } else {
    $message = "Incorrect username or password.";
  }

  // Closing the statement
  $stmt->close();
}

// Closing the connection
$conn->close();
?>
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Lean-C IOT</title>
  <link rel="stylesheet" href="./style_index.css">
</head>
<body>

  <div class="login-page">
    <div class="form">
      <img src="logo.png" alt="Logo" class="login-logo">
      <form class="login-form" method="POST" action="index.php">
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

        <input type="text" placeholder="Username" id="username" name="username" required/>
        <input type="password" placeholder="Password" id="password" name="password" required/>
        <button type="submit">Sign In</button>
      </form>

      <?php
      if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($message)) {
        echo $message;
      }
      ?>
    </div>
  </div>

  <script src='https://code.jquery.com/jquery-3.4.1.min.js'></script>
  <script src='https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/popper.min.js'></script>
  <script src='https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js'></script>
  <script src="./script2.js"></script>


</body>
</html>
