<?php
session_start();
include 'connect.php';
include("header.php");
include("footer.php");
include("nav.php");
include 'function.php';




// Check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the user input
    $emailadd = $_POST['emailadd'];
    $pass = $_POST['pass'];

    // Check the connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    // Query the database for the user
    $result = mysqli_query($conn, "SELECT * FROM tbl_user WHERE emailadd = '$emailadd'");

    // Check if the query returned a result
    if (mysqli_num_rows($result) === 1) {
        // Fetch the user data
        $user = mysqli_fetch_assoc($result);

        // Verify the password
        if (password_verify($pass, $user['pass'])) {
            // Save the user data in the session
            $_SESSION['emailadd'] = $user['emailadd'];
            $_SESSION['f_name'] = $user['f_name'];
            $_SESSION['l_name'] = $user['l_name'];
            $_SESSION['nokp'] = $user['nokp'];
            $_SESSION['role'] = $user['role'];

            // Redirect the user back to the index page
            header('Location: main.php');
        } else {
            // If the password is incorrect, show an error message
            echo 'Incorrect password';
        }
    } else {
        // If the email address is not found, show an error message
        echo 'Email address not found';
    }

    // Close the database connection
    mysqli_close($conn);
}
?>

<html>
  
    <main>
      <h2>Login</h2>
      <form action="" method="post">
        <label for="emailadd">Email:</label>
        <input type="emailadd" name="emailadd" required><br>
        <label for="pass">Password:</label>
        <input type="pass" name="pass" required><br>
        <input type="submit" name="login_user" value="Login">
      </form>
      <p>Don't have an account? <a href="register.php">Sign up</a> now.</p>
    </main>

  </body>
</html>

