<?php
// konekcijas piesaiste
include('connection.php');

//iegūst ievdformas datus, glabā tos lokāli
$email = $_POST['email'];
$password = $_POST['password'];

// pārbauda vai šāds e-pasta jua nav reģistrēts DB
$stmt = $conn->prepare("SELECT * FROM rr_410_profile WHERE email = ?");//vaicājums
$stmt->bind_param('s', $email);//nodod e-pastu
$stmt->execute();
$result = $stmt->get_result();//saglabā rezultātu

if ($result->num_rows > 0) {
    // ziņojums, ka tāds e-pasts jau pastāv
    echo "<script>alert('Email already registered. Please use another email.'); location.href='../html/register.html'; </script>";
    exit();
}

// Hash the password before storing it
$hashed_password = password_hash($password, PASSWORD_DEFAULT); //šifrē paroli

// Insert data into the database using a prepared statement
$stmt = $conn->prepare("INSERT INTO rr_410_profile (email, password) VALUES (?, ?)");
$stmt->bind_param('ss', $email, $hashed_password);//nodod šifrētu paroli un e-pastu

if ($stmt->execute()) {
    echo "<script>alert('Profile registered successfully.');</script>";//veiksmīgs ziņojums
    echo "<script> location.href='../html/login.html'; </script>";//pāradresē uz sākumlapu
} else {
    echo "<script>alert('Error registering profile.'); location.href='../html/register.html'; </script>";//kļūdas ziņojums
}

//aizver konekciju
$stmt->close();
$conn->close();
?>
