<?php
session_start();

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

    if (empty($email) || empty($password)) {
        echo "<div style='color:red; text-align:center;'>Email and password are required. <a href='login.html'>Try again</a></div>";
        exit;
    }

    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    $users = file('users.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $userFound = false;

    foreach ($users as $user) {
        list($savedUsername, $savedEmail, $savedPassword) = explode('|', $user);

        if ($savedEmail === $email) {
            $userFound = true;

            if ($password === trim($savedPassword)) {
                $_SESSION['username'] = $savedUsername;
                $_SESSION['email'] = $savedEmail;

                header("Location: index1.html");
                exit;
            } else {
                echo "<div style='color:red; text-align:center;'>Incorrect password. <a href='login.html'>Try again</a></div>";
                exit;
            }
        }
    }

    if (!$userFound) {
        echo "<div style='color:red; text-align:center;'>Email not found. <a href='signup.html'>Sign up</a></div>";
    }
}
?>
