<?php
header('Content-Type: application/json');
require 'db.php'; // Your PDO DB connection ($pdo)

// Sanitize and validate inputs
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';

if (!$username || !$email || !$password) {
    echo json_encode(['success' => false, 'error' => 'All fields are required.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'error' => 'Invalid email address.']);
    exit;
}

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

try {
    $stmt = $pdo->prepare("INSERT INTO users (username, email, password, points, level) VALUES (?, ?, ?, 0, 1)");
    $stmt->execute([$username, $email, $hashedPassword]);

    session_start();
    $_SESSION['username'] = $username;

    echo json_encode(['success' => true]);
} catch (PDOException $e) {
    // Check for duplicate email or username
    if ($e->getCode() == 23000) { // Integrity constraint violation
        echo json_encode(['success' => false, 'error' => 'Email or username already exists.']);
    } else {
        echo json_encode(['success' => false, 'error' => 'Database error.']);
    }
}
