<?php
session_start();
require '../includes/db_connect.php';

if (!isset($_SESSION['user_id'])) { exit("Bạn cần đăng nhập."); }

$newUsername = $_POST['new_username'];
$newPassword = $_POST['new_user_password'];

// Kiểm tra xem username đã tồn tại chưa
$stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
$stmt->bind_param("s", $newUsername);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    $stmt->close();
    header("Location: ../settings.php?error=userexists");
    exit();
}
$stmt->close();

// Hash mật khẩu
$passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);

// Thêm user mới vào database
$insertStmt = $conn->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
$insertStmt->bind_param("ss", $newUsername, $passwordHash);

if ($insertStmt->execute()) {
    header("Location: ../settings.php?success=useradded");
} else {
    header("Location: ../settings.php?error=dberror");
}

$insertStmt->close();
$conn->close();
exit();
?>