<?php
session_start();
require 'db.php'; // Database connection

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

    // Validate input
    if (empty($email) || empty($password)) {
        die("All fields are required.");
    }

    // Fetch user from database
    $stmt = $conn->prepare("SELECT id, username, password FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($userId, $username, $hashedPassword);
        $stmt->fetch();

        // Verify password
        if (password_verify($password, $hashedPassword)) {
            $_SESSION['user_id'] = $userId;
            $_SESSION['username'] = $username;

            // Handle "Remember Me" functionality
            if (!empty($_POST['remember'])) {
                setcookie("email", $email, time() + (30 * 24 * 60 * 60), "/"); // 30 days
            } else {
                setcookie("email", "", time() - 3600, "/"); // Expire cookie
            }

            echo "<script>alert('Login successful! Redirecting to dashboard...'); window.location='dashboard.php';</script>";
        } else {
            echo "<script>alert('Invalid password. Please try again.'); window.location='login.php';</script>";
        }
    } else {
        echo "<script>alert('No account found with that email. Please register.'); window.location='register.php';</script>";
    }

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