<?php
include('connection.php');
// Capture form data
$email = $_POST['email'];
$password = $_POST['password'];

// Check if email already exists
$sql_check_email = "SELECT * FROM rr_410_profile WHERE email = '$email'";
$result = $conn->query($sql_check_email);
if ($result->num_rows > 0) {
    // If email exists, show an error and stop registration
    echo "<script>alert('Email already registered. Please use another email.'); location.href='../html/register.html'; </script>";
    exit();
}

// Hash the password before storing it for security
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// SQL query to insert data into the database
$sql = "INSERT INTO rr_410_profile (email, password) VALUES ('$email', '$hashed_password')";

if ($conn->query($sql) === TRUE) {
    // Registration successful, redirect to main page
    echo "<script>alert('Profile registered succesfully.');</script>";
    echo "<script> location.href='../html/login.html'; </script>";
} else {
    // Registration failed, show error
    echo "<script>alert('Error registering profile.'); location.href='../html/register.html'; </script>";
}

// Close connection
$conn->close();
?>
