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

    if (empty($username) || empty($email) || empty($password)) {
        echo "All fields are required. <a href='signup.html'>Go back</a>";
        exit;
    }

    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    $username = htmlspecialchars($username);

    // Check if email already exists
    $users = file('users.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($users as $user) {
        list($savedUsername, $savedEmail, $savedPassword) = explode('|', $user);
        if ($savedEmail === $email) {
            echo "Email already exists. <a href='signup.html'>Try again</a>";
            exit;
        }
    }

    // Store plain password
    $entry = "$username|$email|$password\n";

    if (file_put_contents("users.txt", $entry, FILE_APPEND)) {
        header("Location: login.html");
        exit;
    } else {
        echo "An error occurred. Please try again.";
    }
}
?>
