<!-- Autors:Ervīns Jēkabsons; Koda daļa kura atbild par lietotāja pieslēgšanos pie mājās lapas un dati tiek saglabāti datubazē
Veidots 2024.gadā, jaunākā vesrija-->
<?php
    // Database connection
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "car_registration";

    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // User details
        $username = $_POST['username'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $hashed_password = password_hash($password, PASSWORD_DEFAULT); // Hash the password for security
        $default_role = 'user'; // Default role for new users

        // Check if the email already exists
        $stmt = $conn->prepare("SELECT email FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // Email already exists
            echo "<script>alert('This email is already registered. Please use a different email.');</script>";
            echo "<script>window.location.href = '../html/register_user.html';</script>";
        } else {
            // Check if the username already exists
            $stmt = $conn->prepare("SELECT username FROM users WHERE username = ?");
            $stmt->bind_param("s", $username);
            $stmt->execute();
            $stmt->store_result();

            if ($stmt->num_rows > 0) {
                // Username already exists
                echo "<script>alert('Username already taken. Please choose a different username.');</script>";
                echo "<script>window.location.href = '../html/register_user.html';</script>";
            } else {
                // Insert the new user into the database with the default role
                $stmt = $conn->prepare("INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("ssss", $username, $email, $hashed_password, $default_role);

                if ($stmt->execute()) {
                    // Registration successful
                    echo "<script>alert('Your account has been successfully registered!');</script>";
                    echo "<script>window.location.href = '../html/login.html';</script>";
                } else {
                    // Error during registration
                    echo "<script>alert('There was an error during registration. Please try again.');</script>";
                    echo "<script>window.location.href = '../html/register_user.html';</script>";
                }
            }
        }

        $stmt->close();
    }
    $conn->close();
    ?>