<?php
require '../vendor/autoload.php';
require '../db_config.php';
require 'authenticate.php'; // Secure API

header("Content-Type: application/json");

// Authenticate API Key
$api_key = $_SERVER['HTTP_API_KEY'] ?? '';
$stmt = $pdo->prepare("SELECT user_id, app_id FROM registered_apps WHERE api_key = ?");
$stmt->execute([$api_key]);
$app = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$app) {
    echo json_encode(["error" => "Invalid API Key"]);
    exit;
}

$user_id = $app['user_id'];
$app_id = $app['app_id'];

// Generate QR Code for this app
$secret = bin2hex(random_bytes(10));
$totp = OTPHP\TOTP::create($secret);
$totp->setLabel($app_id);
$totp->setIssuer("MyAuthenticator");

$qrCodeUrl = $totp->getProvisioningUri();

// Store in DB
$stmt = $pdo->prepare("INSERT INTO scanned_auths (user_id, app_id, secret) VALUES (?, ?, ?)");
$stmt->execute([$user_id, $app_id, $secret]);

echo json_encode([
    "app_id" => $app_id,
    "qr_code" => $qrCodeUrl
]);
?>
