<?php
// includes/qr_helper.php
// Server-side QR code generation using endroid/qr-code v6.
//
// Returns a base64-encoded PNG data URI suitable for embedding directly
// in an <img src="..."> tag — works in both browser HTML and Dompdf PDF
// rendering. Dompdf cannot execute JavaScript, so this helper is a hard
// prerequisite for PDF output (the old qrcodejs client-side approach
// produces a blank QR box in every PDF).
//
// Requires: vendor/autoload.php must exist (run `composer install` first).
// The library is already locked at endroid/qr-code v6.0.9 in composer.lock.

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\ErrorCorrectionLevel;

/**
 * Generates a QR code for the given $text and returns a PNG data URI.
 *
 * @param string $text  The payload to encode (typically the verify.php URL).
 * @param int    $size  Output PNG pixel size. Caller controls display size via CSS.
 *                      Default 200px produces a sharp image at all certificate sizes.
 *
 * @return string  A complete data URI: "data:image/png;base64,..."
 *                 On failure (vendor missing, etc.) returns a 1×1 transparent PNG
 *                 data URI so the certificate still renders without a broken-image icon.
 */
function generateQrCodeDataUri(string $text, int $size = 200): string
{
    // Clamp size to a safe range: below 50px the matrix becomes unreadable;
    // above 1000px is wasteful for what is ultimately a small embedded image.
    $size = max(50, min(1000, $size));

    try {
        $qrCode = new QrCode(
            data: $text,
            // ErrorCorrectionLevel::Medium (M) — 15% redundancy.
            // H (30%) is NOT better for small print: it forces a denser matrix
            // that is harder to scan from a phone at certificate print sizes.
            errorCorrectionLevel: ErrorCorrectionLevel::Medium,
            size: $size,
            margin: 0,
        );

        $writer  = new PngWriter();
        $result  = $writer->write($qrCode);

        // getDataUri() returns the full "data:image/png;base64,..." string.
        return $result->getDataUri();

    } catch (\Throwable $e) {
        // Log silently; never expose library internals in the HTTP response.
        error_log('[qr_helper] QR generation failed: ' . $e->getMessage());

        // 1×1 transparent PNG — certificate renders; QR box is just blank.
        return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
    }
}
