<?php
// Start session
session_start();
require_once('../_db.php');
// SQL query to add a unique constraint to the email column
// $alterTableQuery = "ALTER TABLE user_login ADD UNIQUE (email)";

// if ($conn->query($alterTableQuery) === TRUE) {
//     echo "Unique constraint added successfully.";
// } else {
//     echo "Error adding unique constraint: " . $conn->error;
// }

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $email = $_POST['email'];
    $password = $_POST['password'];

    // Query to check if the user exists in the database
    $stmt = $conn->prepare("SELECT * FROM user_login WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // User exists, fetch user data
        $user = $result->fetch_assoc();

        // Verify password
        if (password_verify($password, $user['password'])) {
            // Password is correct
            // Clear previous session data
            session_unset();
            session_regenerate_id(true);

            // Set session variables
            $_SESSION['userid'] = $user['userid'];
            $_SESSION['email'] = $user['email'];
            
            // Redirect to different dashboards based on user's dlevel
            if ($user['dlevel'] == 'user') {
                $_SESSION['user'] = true;  
                $_SESSION['message'] = "Login successful as user.";
                header("Location: ../dashboard.php");
            } else {
                $_SESSION['message'] = "Login successful as user.";
                header("Location: ../dashboard.php");
            }
            exit();
        } else {
            // Incorrect password
            $_SESSION['message'] = '<div class="alert alert-warning" role="alert">
                <strong>Fail!</strong> 
                <p>Invalid Email or Password.</p>
            </div>';
            header("Location: ../login.php");
            exit();
        }
    } else {
        // User does not exist
        $_SESSION['message'] = '<div class="alert alert-danger" role="alert" style="display:flex; align-items:start;justify-content:start; flex-direction:column">
            <strong>Fail!</strong> 
            <p>User Doesnt Exist.</p>
        </div>';
        header("Location: ../login.php");
        exit();
    }
} else {
    // If form is not submitted via POST method, redirect back to the index page
    $_SESSION['message'] = '<div class="alert alert-warning" role="alert">
        <strong>Fail!</strong> 
        <p>Form submission method not allowed.</p>
    </div>';
    header("Location: ../login.php");
    exit();
}
?>
