<?php
// Checks if the form was submitted using the POST method
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';

    // Loads users and passwords
    $users = file('users.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $isValidUser = false;

    foreach ($users as $user) {
        list($userEmail, $userPassword) = explode(',', $user);
        if ($email === $userEmail && $password === $userPassword) {
            $isValidUser = true;
            break;
        }
    }

    if ($isValidUser) {
        // Sets or renews the authentication cookie for 24 hours.
        setcookie('user_email', $email, time() + 86400, "/");
        // Redirects to the protected page
        header('Location: instructions.php');
        exit;
    } else {
        $errorMessage = 'Invalid login credentials.';
    }
    

}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<div class="form-container">
    <?php if (!empty($errorMessage)): ?>
        <p class="error"><?php echo $errorMessage; ?></p>
    <?php endif; ?>
    <form action="login.php" method="post">
        <h2>Login</h2>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <div class="form-group">
            <input type="submit" value="Login">
        </div>
    </form>
</div>
</body>
</html>
