<?php
session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}
require "../config/db.php";
require "../vendor/autoload.php";

use PragmaRX\Google2FA\Google2FA;

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

$user_id = $_SESSION["user_id"];

$google2fa = new Google2FA();

$secret = $google2fa->generateSecretKey();

$stmt = $conn->prepare("SELECT email FROM users WHERE id=?");
$stmt->bind_param("i",$user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

$email = $user["email"];

$otpUrl = $google2fa->getQRCodeUrl(
    "TradersHub",
    $email,
    $secret
);

echo json_encode([
    "secret"=>$secret,
    "otpUrl"=>$otpUrl
]);