<?php
session_start();

require_once "./connection.php";

$name = trim($_POST["username"]);
$pass = trim($_POST["upassword"]); // Ensure this matches the input name in your form
$cpass = trim($_POST["cpass"]);
$usertype = trim($_POST["user_type"]);

if ($pass !== $cpass) {
    echo '<script>alert("Passwords are not matching!"); window.location.assign("./signup.php"); </script>';
    exit();
}

if (empty($name) || empty($pass) || empty($usertype)) {
    echo '<script>alert("Some attributes are empty."); window.location.assign("./signup.php"); </script>';
    exit();
}

// Check if the user already exists
$q1 = "SELECT ID FROM userstbl WHERE username = ?";
$stmt = $conn->prepare($q1);
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    echo '<script>alert("Username is already taken."); window.location.assign("./signup.php"); </script>';
    $stmt->close();
    exit();
}

// Insert new user
$query = "INSERT INTO userstbl (username, userpass, user_type) VALUES (?, ?, ?)";
$stmt2 = $conn->prepare($query);
$hashed_pass = md5($pass); // Consider using a stronger hashing algorithm like password_hash
$stmt2->bind_param("sss", $name, $hashed_pass, $usertype);

if ($stmt2->execute()) {
    echo '<script>alert("Registration successful."); window.location.assign("./login.php"); </script>';
} else {
    echo '<script>alert("Registration failed. Please try again later."); window.location.assign("./signup.php"); </script>';
}

$stmt2->close();
$conn->close();
?>
