<?php
require('config.php');

// Check if the necessary POST data is present
if (isset($_POST['userData'])) {

    $userData = $_POST['userData'];

    // Decode the JSON data
    $usersArray = json_decode($userData, true);

    foreach ($usersArray as $row) {
        // Prepare the SQL statement using parameterized queries to prevent SQL injection
                $hashedPassword = password_hash($row["password"], PASSWORD_BCRYPT);
        $stmt = $connect->prepare("INSERT INTO users (name, email, phone, role, password, dateCreated, createdBy) VALUES (?, ?, ?, ?, ?, ?, ?)");
        
        // Bind parameters to the SQL statement
        $stmt->bind_param("ssssssi", 
            $row["name"], 
            $row["email"], 
            $row["phone"], 
            $row["role"], 
            $hashedPassword, 
            $row["dateCreated"], 
            $row["createdBy"]
        );

        // Execute the prepared statement
        $stmt->execute();
    }

    $response['error'] = false;
    $response['message'] = "User added successfully";

} else {
    $response['error'] = true;
    $response['message'] = "Insufficient parameters, please provide user data.";
}

// Output the response as JSON
echo json_encode($response);
?>
