<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Add logging to a file for more detailed errors
$logFile = 'generate_error.log';
ini_set('error_log', $logFile);

// Log the start of the script
error_log(date('[Y-m-d H:i:s]') . " generate.php started\n", 3, $logFile);




if (!isset($_SESSION['username'])) {
    http_response_code(403);
    echo "Access Denied";
    exit;
}
require_once __DIR__ . '/vendor/autoload.php';
require_once 'db_config.php';

use OTPHP\TOTP;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;

$username = $_SESSION['username'];

$secret = TOTP::generateSecret();
$totp = TOTP::create($secret);
$provisioningUri = $totp->getProvisioningUri($username . '@example.com', 'My App');

$renderer = new ImageRenderer(
    new RendererStyle(400),
    new BaconQrCode\Renderer\Image\SvgImageBackEnd()
);
$writer = new Writer($renderer);
$qrCode = $writer->writeString($provisioningUri);

try {
    $stmt = $conn->prepare("UPDATE users SET secret = ? WHERE username = ?");
    $stmt->bind_param("ss", $secret, $username);

    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'secret' => $secret, 'qrcode' => $qrCode]);
    } else {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Error storing secret: ' . $stmt->error]);
    }

    $stmt->close();
} catch (mysqli_sql_exception $exception) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $exception->getMessage()]);
} finally {
    $conn->close();
}
?>
