<?php 

session_start(); // Start the session

include "connection.php"; 

// Collecting form data
$username = $_POST["username"];
$number = $_POST["number"];
$email = $_POST["email"];
$password = $_POST["password"];
$pin = $_POST["pin"];
$date = date('Y-M-d');

// Fetch the maximum userid
$userid_query = "SELECT MAX(userid) AS max_userid FROM student";
$userid_result = mysqli_query($con, $userid_query);

// Initialize userid to 1 if no records exist
if ($row = mysqli_fetch_assoc($userid_result)) {
    $max_userid = $row['max_userid'];
    $new_userid = $max_userid + 1; // Increment the max userid by 1
} else {
    $new_userid = 1; // Start with 1 if no users exist
}

// Insert query to add data to the table including the new userid
$sql = "INSERT INTO student (userid, username, number, email, password, pin, entry_date) 
        VALUES ('$new_userid', '$username', '$number', '$email', '$password', '$pin', '$date')";

// Execute the query
$result = mysqli_query($con, $sql);

// Check if the query was successful
if($result) {
    $_SESSION['success_message'] = "Account created successfully! Your User ID is: " . $new_userid;
    header("Location: UserPanel/index.php"); // Redirect to login page (or dashboard)
    exit();
} else {
    $_SESSION['error_message'] = "Some error occurred: " . mysqli_error($con); // Show error details
    header("Location: user-login.php"); // Redirect back to form page
    exit();
}

// Close connection
$stmt->close();
$con->close();
?>
