<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start(); // Start the session
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve user inputs
    $email = $_POST['email'];
    $password = $_POST['password'];

    // Fetch the user from the database
    $sql = "SELECT * FROM users WHERE email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

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

        // Verify the entered password against the hashed password
        if (password_verify($password, $user['password'])) {
            // Save the user ID in the session
            $_SESSION['user_id'] = $user['id'];
            
            // Redirect to the homepage on success
            header("Location: homepage.html");
            exit;
        } else {
            echo "Invalid password! <a href='index.html'>Try again</a>";
        }
    } else {
        echo "User not found! <a href='index.html'>Register here</a>";
    }

    // Close the statement and connection
    $stmt->close();
    $conn->close();
}
?>
