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

include 'db.php';

use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;

use SimpleSoftwareIO\QrCode\Generator;



// Get the secret from database or generate it
//$secret = 'JJBFGV2ZGNCFARKIKBFTGUCYKA======';
$secrete = random_bytes(10);
//$secret = Base32::encode(random_bytes(10));
$qrContent = "otpauth://totp/MyAuthenticatorApp?secret=$secret&issuer=MyCompany";

if (isset($_SESSION['user_email'])) {
    $label = $_SESSION['user_email'];  // Example: user@example.com
} else {
    // Set a fallback value in case the session doesn't have a user_email
    $label = 'user@example.com';  // Default value for testing, replace with real value
}

// Ensure the qrcodes folder exists
 if (!is_dir('qrcodes')) {
     mkdir('qrcodes', 0777, true);  // Create the folder if it doesn't exist
 }
  // Path where the QR code image will be stored
  $qrCodePath = 'qrcodes/qr_code_' . $_SESSION['user_id'] . '.png';


// Insert into the database
$user_id = $_SESSION['user_id']; // Replace with the logged-in user ID
$stmt = $conn->prepare("INSERT INTO authentications (user_id, secret,label, qr_code_path) VALUES (?, ?, ?, ?)");
$stmt->bind_param("isss", $user_id, $secret, $label, $qrCodePath);
$stmt->execute();
$stmt->close();
$conn->close();




// QR Code options
$options = new QROptions([
    'outputType' => QRCode::OUTPUT_IMAGE_PNG,
    'eccLevel' => QRCode::ECC_L,
    'imageBase64' => false,
]);

// Generate QR Code
header('Content-Type: image/png');
$qrcode = (new QRCode($options))->render($qrContent);
echo $qrcode;



// Check if the file was created successfully
if (file_exists($qrCodePath)) {
    echo "✅ QR Code generated successfully!<br>";
    echo "<img src='$qrCodePath' alt='Test QR Code'>";
  //  echo '<br /><a href="dashboard.php"> Home </a>';
    // Redirect to the dashboard
       header("Location: dashboard.php");
} else {
    echo "❌ Failed to generate QR Code.";
}

exit;


?>
