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

// Log the request data
$requestData = file_get_contents("php://input");
file_put_contents("register_log.txt", date("Y-m-d H:i:s") . " - Request: " . $requestData . "\n", FILE_APPEND);

$response = [];

// Read JSON input
$input = json_decode($requestData, true);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  //  $username = trim($input["username"] ?? "");
  $username = trim($input["username"] ?? "user_" . rand(1000, 9999)); // Auto-generate if missing
    $email = trim($input["email"] ?? "");
    $password = trim($input["password"] ?? "");

    if (empty($username) || empty($email) || empty($password)) {
        file_put_contents("register_log.txt", date("Y-m-d H:i:s") . " - Error: Missing fields\n", FILE_APPEND);
        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) {
            file_put_contents("register_log.txt", date("Y-m-d H:i:s") . " - Error: Email already exists - $email\n", FILE_APPEND);
            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();

        // Log successful registration
        file_put_contents("register_log.txt", date("Y-m-d H:i:s") . " - Registered: $email (User ID: $userId)\n", FILE_APPEND);

        echo json_encode([
            "status" => "success",
            "message" => "Registration successful",
            "user_id" => $userId,
            "remember_token" => $rememberToken,
            "totp_secret" => $totSecret,
            "api_key" => $apiKey
        ]);
    } catch (Exception $e) {
        file_put_contents("register_log.txt", date("Y-m-d H:i:s") . " - Error: " . $e->getMessage() . "\n", FILE_APPEND);
        echo json_encode(["status" => "error", "message" => "Registration failed: " . $e->getMessage()]);
    }
} else {
    file_put_contents("register_log.txt", date("Y-m-d H:i:s") . " - Error: Invalid request method\n", FILE_APPEND);
    echo json_encode(["status" => "error", "message" => "Invalid request method"]);
}
?>
