<?php
// Fetch roles from the database
$roles = [];
$roleQuery = $db->query("SELECT id, name FROM res_roles ORDER BY name ASC");
if ($roleQuery) {
    $roles = $roleQuery->fetch_all(MYSQLI_ASSOC);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && 
    isset($_POST['name'], $_POST['email'], $_POST['address'], $_POST['role_id'], $_POST['password'])) {

    $name     = trim($_POST['name']);
    $email    = trim($_POST['email']);
    $address  = trim($_POST['address']);
    $role_id  = intval($_POST['role_id']); 
    $password = $_POST['password'];

    // Hash the password before storing
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Use prepared statement to avoid SQL injection
    $stmt = $db->prepare("CALL proc_user_create(?, ?, ?, ?, ?)");
    $stmt->bind_param("sssds", $name, $email, $address, $role_id, $hashed_password);

    if ($stmt->execute()) {
        echo "<div class='alert alert-success'>User Added Successfully.</div>";
    } else {
        echo "<div class='alert alert-danger'>Error: " . $db->error . "</div>";
    }

    $stmt->close();
}
?>

<h4 style="text-align: center;">Add Users</h4>
<form method="post">
    <div style="margin: 10px;">
        <label>Name</label>
        <input type="text" name="name" class="form-control" required>
    </div>

    <div style="margin: 10px;">
        <label>Email</label>
        <input type="email" name="email" class="form-control" required>
    </div>

    <div style="margin: 10px;">
        <label>Address</label>
        <input type="text" name="address" class="form-control" required>
    </div>

    <div style="margin: 10px;">
        <label>Role</label>
        <select name="role_id" class="form-control" required>
            <option value="">Select Role</option>
            <?php foreach ($roles as $role) { ?>
                <option value="<?php echo htmlspecialchars($role['id']); ?>">
                    <?php echo htmlspecialchars($role['name']); ?>
                </option>
            <?php } ?>
        </select>
    </div>

    <div style="margin: 10px;">
        <label>Password</label>
        <input type="password" name="password" class="form-control" required>
    </div>

    <div style="margin: 10px;">
        <input type="submit" value="Add New" class="btn btn-success w-100">
    </div>
</form>
