<?php
session_start();
require 'db.php';
require 'vendor/autoload.php'; // OTP library

use OTPHP\TOTP;

if (!isset($_SESSION['user_id'])) {
    die("Unauthorized access.");
}

if (!isset($_GET['auth_id'])) {
    die("Invalid request.");
}

$userId = $_SESSION['user_id'];
$authId = intval($_GET['auth_id']);

// Fetch secret key from the database
$stmt = $conn->prepare("SELECT secret FROM authentications WHERE id = ? AND user_id = ?");
$stmt->bind_param("ii", $authId, $userId);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

if (!$row) {
    die("Authentication record not found.");
}

$secret = $row['secret'];

// Generate OTP
$totp = TOTP::create($secret);
$otpCode = $totp->now();

echo json_encode(["otp" => $otpCode]);
?>
