<?php
session_start();
require_once '../../model/users.php'; // Include the User model

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user = new User(); // Create an instance of the User class

    // Get form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $inputPassword = trim($_POST['password']); // Storing plain text, consider hashing
    $phone = $_POST['number'];
    
    // Check if the email already exists using the model method
    if ($user->isEmailRegistered($email)) {
        echo "<script>alert('Email already exists. Please use a different email.');</script>";
    } else {
        // Insert the new user into the database using the model method
        if ($user->registerNewUser($name, $email, $inputPassword, $phone)) {
            $_SESSION['user_email'] = $email;
            // It's generally better to set user_full_name after fetching it post-registration or during login
            // For now, we can set it directly from the registration form data if needed for immediate use.
            $_SESSION['user_full_name'] = $name; 
            echo "<script>alert('Registration successful!'); window.location='users.php';</script>";
        } else {
            // The model method logs specific errors, so a generic message here is okay.
            echo "<script>alert('Registration failed. Please try again.');</script>";
        }
    }
    // The User class constructor handles the connection, and it will be closed when the script ends
    // or explicitly if $user->closeConnection(); is called.
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="register.css?<?php echo time();?>">
</head>

<body>
    <br><br><br><br><br><br><br><br><br><br>
    <div id="login-block">
        <h2>Register</h2>
        <form method="POST" action="" name="register">
            <div>
                <input type="text" class="input" name="name" placeholder="Full Name" required />
            </div>
            <div>
                <input type="email" class="input" required name="email" placeholder="Valid E-mail" required/>
            </div>
            <div>
                <input type="password" class="input" required name="password" placeholder="Password" required/>
            </div>
            <div>
                <input type="text" class="input" required name="number" placeholder="Phone Number" required/>
            </div>
            <div style="margin-top: 0px;">
                <button type="submit">Register</button>
            </div>
            <p>Already have an account? <a href="index.php">Login here</a></p>
        </form>
    </div>
</body>
</html>