<?php
session_start();

// Include your database connection file and functions
include('config/dbcon.php');
include('config/function.php');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'];
    $password = $_POST['password'];

    // Use prepared statements to prevent SQL injection
    $query = "SELECT * FROM users WHERE email = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows == 1) {
        $row = $result->fetch_assoc();

        // Check if the plain-text password matches
        if ($password == $row['password']) {
            // Set session variables
            $_SESSION['userID'] = $row['userID'];
            $_SESSION['fname'] = $row['fname'];
            $_SESSION['role'] = $row['role'];

            // Set session timeout to 1 hour (3600 seconds)
            ini_set('session.gc_maxlifetime', 3600);
            session_set_cookie_params(3600);

            // Redirect based on the user's role
            if ($_SESSION['role'] == 'admin') {
                header('Location: admin/index.php');
            } elseif ($_SESSION['role'] == 'user') {
                header('Location: staff/index.php');
            } elseif ($_SESSION['role'] == 'manager') {
                header('Location: manager/index.php');
            }
            exit();
        } else {
            // Invalid password
            redirect('login.php', 'Invalid Email ID or Password');
        }
    } else {
        // Invalid email or no such user
        redirect('login.php', 'Invalid Email ID or Password');
    }

    $stmt->close();
    mysqli_close($conn);
}
?>