<?php
$email = $_POST['email'];
$user = $_POST['user'];
$password = $_POST['password'];

if(empty($email) || empty($user) || empty($password)) {
    header("Location: http://localhost/projectlasitava/register/register.php"); 
    exit;
}

$password_hash = password_hash($password, PASSWORD_DEFAULT);

$mysqli = require __DIR__ . "/../db/database.php";

$sql_check_email = "SELECT * FROM users WHERE email = ?";
$stmt_check_email = $mysqli->prepare($sql_check_email);
$stmt_check_email->bind_param("s", $email);
$stmt_check_email->execute();
$result_check_email = $stmt_check_email->get_result();

if ($result_check_email->num_rows > 0) {
    echo '<script>
            alert("E-pasts ' . $email . ' ir jau piereģistrēts.");
            setTimeout(function() {
                window.location.href = "http://localhost/projectlasitava/register/register.php";
            }, 0);
          </script>';
    exit;
} 

$sql_check_username = "SELECT * FROM users WHERE username = ?";
$stmt_check_username = $mysqli->prepare($sql_check_username);
$stmt_check_username->bind_param("s", $user);
$stmt_check_username->execute();
$result_check_username = $stmt_check_username->get_result();

if ($result_check_username->num_rows > 0) {
    echo '<script>
            alert("Lietotājvārds ' . $user . ' ir jau piereģistrēts.");
            setTimeout(function() {
                window.location.href = "http://localhost/projectlasitava/register/register.php";
            }, 0);
        </script>';
    exit;
} 

$sql_insert_user = "INSERT INTO users(email, username, password_hash, id_access) VALUES (?, ?, ?, 2)";
$stmt_insert_user = $mysqli->prepare($sql_insert_user);
$stmt_insert_user->bind_param("sss", 
                              $email, 
                              $user, 
                              $password_hash);

try {
    $stmt_insert_user->execute();
    echo '<script>
            alert("Lietotājs ' . $user . ' ir veiksmīgi piereģistrēts!");
            setTimeout(function() {
                window.location.href = "http://localhost/projectlasitava/homepage/homepage.php";
            }, 0); 
         </script>';
    exit; 
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage();
}
