<?php
require __DIR__ . '/../includes/bootstrap.php';

$token = trim($_GET['token'] ?? '');
if ($token === '') {
    http_response_code(400);
    echo 'Missing token.';
    exit;
}

$filename = 'qr-' . preg_replace('/[^a-zA-Z0-9_-]/', '', $token) . '.png';
$download = filter_var($_GET['download'] ?? $_GET['dl'] ?? null, FILTER_VALIDATE_BOOLEAN);
$provider = config('qr.provider', 'auto');

$imageData = null;
$useLocal = extension_loaded('gd') && is_readable(__DIR__ . '/../includes/phpqrcode/qrlib.php');

if ($provider === 'phpqrcode' || ($provider === 'auto' && $useLocal)) {
    require_once __DIR__ . '/../includes/phpqrcode/qrlib.php';
    ob_start();
    QRcode::png($token, null, QR_ECLEVEL_M, 6, 2);
    $imageData = ob_get_clean();
} else {
    $size = config('qr.goqr_size', '300x300');
    if (!preg_match('/^\d+x\d+$/', $size)) {
        $size = '300x300';
    }
    $goqrUrl = sprintf(
        'https://api.qrserver.com/v1/create-qr-code/?size=%s&data=%s',
        $size,
        rawurlencode($token)
    );
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
        ],
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true,
        ],
    ]);
    $imageData = @file_get_contents($goqrUrl, false, $context);
    if ($imageData === false) {
        http_response_code(502);
        echo 'Unable to generate QR code. Please try again later.';
        exit;
    }
}

header('Content-Type: image/png');
header(sprintf(
    'Content-Disposition: %s; filename="%s"',
    $download ? 'attachment' : 'inline',
    $filename
));

echo $imageData;
