<?php
header("Content-Type: application/json");
require_once "config_pdo.php"; // Ensure this file initializes a PDO connection ($conn)

$response = [];

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($input["username"] ?? "");
    $email = trim($input["email"] ?? "");
    $password = trim($input["password"] ?? "");

    if (empty($username) || empty($email) || empty($password)) {
        echo json_encode(["status" => "error", "message" => "All fields are required"]);
        exit;
    }

    try {
        // Check if email already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);

        if ($stmt->rowCount() > 0) {
            echo json_encode(["status" => "error", "message" => "Email already registered"]);
            exit;
        }

        // Hash the password
        $hashedPassword = password_hash($password, PASSWORD_BCRYPT);

        // Generate tokens
        $rememberToken = bin2hex(random_bytes(16));
        $totSecret = bin2hex(random_bytes(10));
        $apiKey = bin2hex(random_bytes(20));

        // Insert user
        $stmt = $pdo->prepare("INSERT INTO users (username, email, password, remember_token, totp_secret, api_key, created_at)
                                VALUES (:username, :email, :password, :remember_token, :totp_secret, :api_key, NOW())");

        $stmt->execute([
            ":username" => $username,
            ":email" => $email,
            ":password" => $hashedPassword,
            ":remember_token" => $rememberToken,
            ":totp_secret" => $totSecret,
            ":api_key" => $apiKey
        ]);

        $userId = $pdo->lastInsertId();

        echo json_encode([
            "status" => "success",
            "message" => "Registration successful",
            "user_id" => $userId,
            "remember_token" => $rememberToken,
            "totp_secret" => $totSecret,
            "api_key" => $apiKey
        ]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => "Registration failed: " . $e->getMessage()]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Invalid request method"]);
}
?>
