<?php
include('db_connect.php');

extract($_POST);

if (isset($id) && !empty($id)) {
    // Update user
    if (!empty($password)) {
        $hashed_pass = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $conn->prepare("UPDATE users SET name = ?, username = ?, password = ? WHERE id = ?");
        $stmt->bind_param("sssi", $name, $username, $hashed_pass, $id);
    } else {
        $stmt = $conn->prepare("UPDATE users SET name = ?, username = ? WHERE id = ?");
        $stmt->bind_param("ssi", $name, $username, $id);
    }
} else {
    // New user
    if (empty($password)) {
        echo "Password is required for new user.";
        exit;
    }
    $hashed_pass = password_hash($password, PASSWORD_BCRYPT);
    $stmt = $conn->prepare("INSERT INTO users (name, username, password) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $username, $hashed_pass);
}

if ($stmt->execute()) {
    echo 1;
} else {
    echo "Error: " . $stmt->error;
}
?>
