false, 'message' => 'An error occurred.']; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; if (empty($username) || empty($password)) { $response['message'] = 'Username and password are required.'; echo json_encode($response); exit; } try { $pdo = db(); // Check if username already exists $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?"); $stmt->execute([$username]); if ($stmt->fetch()) { $response['message'] = 'Username already taken.'; echo json_encode($response); exit; } // Hash the password $password_hash = password_hash($password, PASSWORD_DEFAULT); // Insert the new user $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); if ($stmt->execute([$username, $password_hash])) { $response['success'] = true; $response['message'] = 'Registration successful. You can now log in.'; } else { $response['message'] = 'Failed to register user.'; } } catch (PDOException $e) { // In a real application, you would log this error. $response['message'] = 'Database error: ' . $e->getMessage(); } echo json_encode($response); } ?>